當前位置: 首頁>>代碼示例>>Golang>>正文


Golang credentials.NewSharedCredentials函數代碼示例

本文整理匯總了Golang中github.com/aws/aws-sdk-go/aws/credentials.NewSharedCredentials函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewSharedCredentials函數的具體用法?Golang NewSharedCredentials怎麽用?Golang NewSharedCredentials使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。


在下文中一共展示了NewSharedCredentials函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。

示例1: cmdValidate

func cmdValidate(c *cli.Context) {

	processFlags(c)

	if fileLocation == "" {
		cli.ShowCommandHelp(c, "create")
		log.Fatal("You must specify a configuration file to use")
	}

	log.Infof("Config file %s", fileLocation)

	file, e := ioutil.ReadFile(fileLocation)
	if e != nil {
		fmt.Printf("File error: %v\n", e)
		os.Exit(1)
	}

	jsontype := providers.JSONObject{}
	json.Unmarshal(file, &jsontype)

	log.Info("*********************************************************************************")
	log.Info("** Loading configuration file " + fileLocation)
	log.Info("*********************************************************************************")

	log.Info("Configuration for environment " + jsontype.Provider.ProviderConfig.Aws.Vpc.Name)
	log.Info("Environment has " + strconv.Itoa(len(jsontype.Containers)) + " servers defined")

	//Validate Provider document using JSONSchema
	validated, validateErrors := vmproviders.ValidateDocument()
	if validated {
		log.Info("Successfully validated provider configuration")
	} else {
		log.Error("Error validating provider configuration %v", validateErrors)
	}

	homedir := os.Getenv("HOME")

	creds := credentials.NewSharedCredentials(homedir+"/.aws/credentials", profile)

	credValue, err := creds.Get()
	if err != nil {
		fmt.Printf("Credential token= %v\n", credValue)
		fmt.Println(err)
		os.Exit(1)
	}

	ec2client := vmproviders.GetEC2Client(creds, "us-east-1")

	validateSuccess, validateWarnings, validateErr := vmproviders.Validate(ec2client, &jsontype)
	if validateSuccess {
		log.Infof("Successfully validated environment %v", jsontype.Provider.ProviderConfig.Aws.Vpc.Name)
		for w := range validateWarnings {
			log.Warnf(validateWarnings[w])
		}
	} else {
		for e := range validateErr {
			log.Errorf(validateErr[e].Error())
		}
	}
}
開發者ID:podtools,項目名稱:pod,代碼行數:60,代碼來源:validate.go

示例2: Svc

// Svc configures the DynamoDB service to use
func Svc(opts config.Options) *dynamodb.DynamoDB {
	awsConfig := &aws.Config{Region: aws.String(opts.Storage.AWS.Region)}

	// If a session was passed... (AWS Lambda does this)
	if opts.Storage.AWS.SessionToken != "" {
		os.Setenv("AWS_SESSION_TOKEN", opts.Storage.AWS.SessionToken)
	}

	// Look in a variety of places for AWS credentials. First, try the credentials file set by AWS CLI tool.
	// Note the empty string instructs to look under default file path (different based on OS).
	// This file can have multiple profiles and a default profile will be used unless otherwise configured.
	// See: https://godoc.org/github.com/aws/aws-sdk-go/aws/credentials#SharedCredentialsProvider
	creds := credentials.NewSharedCredentials("", opts.Storage.AWS.CredProfile)
	_, err := creds.Get()
	// If that failed, try environment variables.
	if err != nil {
		// The following are checked:
		// Access Key ID: AWS_ACCESS_KEY_ID or AWS_ACCESS_KEY
		// Secret Access Key: AWS_SECRET_ACCESS_KEY or AWS_SECRET_KEY
		creds = credentials.NewEnvCredentials()
	}

	// If credentials were passed via config, then use those. They will take priority over other methods.
	if opts.Storage.AWS.AccessKeyID != "" && opts.Storage.AWS.SecretAccessKey != "" {
		creds = credentials.NewStaticCredentials(opts.Storage.AWS.AccessKeyID, opts.Storage.AWS.SecretAccessKey, "")
	}
	awsConfig.Credentials = creds

	return dynamodb.New(session.New(awsConfig))
}
開發者ID:tmaiaroto,項目名稱:discfg,代碼行數:31,代碼來源:dynamodb.go

示例3: TestMain

func TestMain(m *testing.M) {
	flag.Parse()
	if !*integration {
		fmt.Fprintln(os.Stderr, "Skipping integration tests")
		os.Exit(0)
	}
	cfg = &aws.Config{
		Region:      aws.String("us-west-2"),
		Endpoint:    aws.String("http://localhost:8000"),
		Credentials: credentials.NewSharedCredentials("", *awsprofile),
	}
	sess = session.New(cfg)
	if *dynamodebug {
		sess.Config.LogLevel = aws.LogLevel(aws.LogDebug)
	}

	if err := loadUserFixtures(sess); err != nil {
		fmt.Fprintf(os.Stderr, "Error loading 'user' integration fixtures: %s", err)
		os.Exit(1)
	}
	if err := loadPostFixtures(sess); err != nil {
		fmt.Fprintf(os.Stderr, "Error loading 'post' integration fixtures: %s", err)
		os.Exit(1)
	}
	os.Exit(m.Run())
}
開發者ID:blang,項目名稱:posty,代碼行數:26,代碼來源:model_integration_test.go

示例4: createCommandFactory

// createCommandFactory create a command factory and wraps the command processor
func createCommandFactory(cx *cli.Context, commandFunc func(*cli.Context, *commandFactory) error) {
	awsRegion := cx.GlobalString("region")
	awsProfile := cx.GlobalString("profile")
	awsCredentials := cx.GlobalString("crendentials")

	if awsRegion == "" {
		usage(cx, "you need to specify the region or export the environment variable AWS_DEFAULT_REGION")
	}

	// step: create a default aws configuration
	cfg := &aws.Config{Region: &awsRegion}

	// step: are we specifying a aws profile, if so, we need to be using the $HOME/.aws/credentials file
	if awsProfile != "" {
		cfg.Credentials = credentials.NewSharedCredentials(awsCredentials, awsProfile)
	}

	// step: create a command line factory
	factory := &commandFactory{
		s3:  newS3Client(cfg),
		kms: newKmsClient(cfg),
	}

	if err := commandFunc(cx, factory); err != nil {
		usage(cx, err.Error())
	}
}
開發者ID:lucmichalski,項目名稱:s3secrets,代碼行數:28,代碼來源:main.go

示例5: preRun

// PreRun sets up global tasks used for most commands, some use PreRunNoop
// to remove this default behaviour.
func preRun(c *cobra.Command, args []string) error {
	if l, err := log.ParseLevel(logLevel); err == nil {
		log.SetLevel(l)
	}

	config := aws.NewConfig()

	if profile != "" {
		config = config.WithCredentials(credentials.NewSharedCredentials("", profile))
	}

	Session = session.New(config)

	Project = &project.Project{
		Log:  log.Log,
		Path: ".",
	}

	if dryRun {
		log.SetLevel(log.WarnLevel)
		Project.Service = dryrun.New(Session)
		Project.Concurrency = 1
	} else {
		Project.Service = lambda.New(Session)
	}

	if chdir != "" {
		if err := os.Chdir(chdir); err != nil {
			return err
		}
	}

	return Project.Open()
}
開發者ID:aom,項目名稱:apex,代碼行數:36,代碼來源:root.go

示例6: Start

// Start a test
func (t *Test) Start() <-chan queue.RegionsAggData {
	awsConfig := aws.NewConfig().WithRegion(t.config.Regions[0])

	if t.config.AwsProfile != "" {
		creds := credentials.NewSharedCredentials("", t.config.AwsProfile)
		if _, err := creds.Get(); err != nil {
			log.Fatal(err)
		}
		awsConfig.WithCredentials(creds)
	}

	infra, err := infrastructure.New(t.config.Regions, awsConfig)
	if err != nil {
		log.Fatal(err)
	}

	t.invokeLambdas(awsConfig, infra.QueueURL())

	results := make(chan queue.RegionsAggData)

	go func() {
		for result := range queue.Aggregate(awsConfig, infra.QueueURL(), t.config.TotalRequests) {
			results <- result
		}
		infra.Clean()
		close(results)
	}()

	return results
}
開發者ID:goadapp,項目名稱:goad,代碼行數:31,代碼來源:goad.go

示例7: Connect

func (c *Config) Connect() interface{} {

	c.readConf()

	var client AWSClient

	awsConfig := new(aws.Config)

	if len(c.Profile) > 0 {
		awsConfig = &aws.Config{
			Credentials: credentials.NewSharedCredentials(c.Awsconf, fmt.Sprintf("profile %s", c.Profile)),
			Region:      aws.String(c.Region),
			MaxRetries:  aws.Int(3),
		}

	} else {
		// use instance role
		awsConfig = &aws.Config{
			Region: aws.String(c.Region),
		}

	}

	sess := session.New(awsConfig)

	client.ec2conn = ec2.New(sess)

	return &client

}
開發者ID:mhlias,項目名稱:awscleaner,代碼行數:30,代碼來源:config.go

示例8: mount

// Mount the file system based on the supplied arguments, returning a
// fuse.MountedFileSystem that can be joined to wait for unmounting.
func mount(
	ctx context.Context,
	bucketName string,
	mountPoint string,
	flags *FlagStorage) (mfs *fuse.MountedFileSystem, err error) {

	awsConfig := &aws.Config{
		Region: &flags.Region,
		Logger: GetLogger("s3"),
		//LogLevel: aws.LogLevel(aws.LogDebug),
	}

	if len(flags.Profile) > 0 {
		awsConfig.Credentials = credentials.NewSharedCredentials("", flags.Profile)
	}

	if len(flags.Endpoint) > 0 {
		awsConfig.Endpoint = &flags.Endpoint
	}

	// deprecate flags.UsePathRequest
	if flags.UsePathRequest {
		log.Infoln("--use-path-request is deprecated, it's always on")
	}
	awsConfig.S3ForcePathStyle = aws.Bool(true)

	goofys := NewGoofys(bucketName, awsConfig, flags)
	if goofys == nil {
		err = fmt.Errorf("Mount: initialization failed")
		return
	}
	server := fuseutil.NewFileSystemServer(goofys)

	fuseLog := GetLogger("fuse")

	// Mount the file system.
	mountCfg := &fuse.MountConfig{
		FSName:                  bucketName,
		Options:                 flags.MountOptions,
		ErrorLogger:             GetStdLogger(NewLogger("fuse"), logrus.ErrorLevel),
		DisableWritebackCaching: true,
	}

	if flags.DebugFuse {
		fuseLog.Level = logrus.DebugLevel
		log.Level = logrus.DebugLevel
		mountCfg.DebugLogger = GetStdLogger(fuseLog, logrus.DebugLevel)
	}

	mfs, err = fuse.Mount(mountPoint, server, mountCfg)
	if err != nil {
		err = fmt.Errorf("Mount: %v", err)
		return
	}

	return
}
開發者ID:kahing,項目名稱:goofys,代碼行數:59,代碼來源:main.go

示例9: ProfileCredentials

// ProfileCredentials checks to see if specific profile is being asked to use
func (config SsmagentConfig) ProfileCredentials() (credsInConfig *credentials.Credentials, err error) {
	// the credentials file location and profile to load
	credsInConfig = credentials.NewSharedCredentials(config.Profile.Path, config.Profile.Name)
	_, err = credsInConfig.Get()
	if err != nil {
		return nil, err
	}
	fmt.Printf("Using AWS credentials configured under %v user profile \n", config.Profile.Name)
	return
}
開發者ID:aws,項目名稱:amazon-ssm-agent,代碼行數:11,代碼來源:appconfig.go

示例10: main

func main() {
	home := os.Getenv("HOME")
	if home == "" {
		log.Fatalf("HOME environment variable not set")
	}
	credentialsFile := fmt.Sprintf("%s/.aws/credentials", home)
	config := aws.NewConfig().WithCredentials(credentials.NewSharedCredentials(credentialsFile, *profile)).WithRegion(*region).WithMaxRetries(3)

	svc := s3.New(config)

	switch *op {
	case "get":
		params := &s3.GetObjectInput{
			Bucket: aws.String(*bucketName),
			Key:    aws.String(*objectKey),
		}

		resp, err := svc.GetObject(params)
		if err != nil {
			log.Fatal(err)
		}

		data, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Fatal(err)
		}

		if err := ioutil.WriteFile(*fileName, data, 0644); err != nil {
			log.Fatal(err)
		}
	case "put":
		data, err := ioutil.ReadFile(*fileName)
		if err != nil {
			log.Fatal(err)
		}
		params := &s3.PutObjectInput{
			Bucket:               aws.String(*bucketName),
			Key:                  aws.String(*objectKey),
			Body:                 bytes.NewReader(data),
			ServerSideEncryption: aws.String("AES256"),
		}
		if *publicRead {
			params.ACL = aws.String("public-read")
		}
		if *contentType != "" {
			params.ContentType = aws.String(*contentType)
		}
		if _, err = svc.PutObject(params); err != nil {
			log.Fatal(err.Error())
		}
	default:
		log.Fatalf("Operation not supported %s\n", *op)
	}
}
開發者ID:ae6rt,項目名稱:s3rw,代碼行數:54,代碼來源:main.go

示例11: LoadDefaultOptions

// LoadDefaultOptions is used to load in the default options into the globally
// available options struct. This is typically one of the first things called
// on start up. After this all options can be overridden
func LoadDefaultOptions() {
	Options.CacheDir = "/tmp/S3Proxy/"
	Options.BindAddress = ":9090"
	Options.ObjectCacheTTL = time.Duration(1 * time.Minute)
	Options.Region = "eu-west-1"
	Options.Bucket = "example-bucket"
	Options.TokenKey = "test_keys/sample_key"
	Options.TokenMethod = jwt.SigningMethodRS512
	Options.CookieMaxAge = 3600
	Options.AwsCredentials = credentials.NewSharedCredentials("", "default")
}
開發者ID:gitu,項目名稱:S3Proxy,代碼行數:14,代碼來源:options.go

示例12: checkCreds

func checkCreds() (err error) {
	creds := credentials.NewEnvCredentials()
	_, err = creds.Get()
	if err == nil {
		// If ENV credentials are present, I don't need to check shared credentials on fs
		return
	}
	creds = credentials.NewSharedCredentials("", "")
	_, err = creds.Get()
	return
}
開發者ID:cloudacademy,項目名稱:s3zipper,代碼行數:11,代碼來源:s3.go

示例13: getService

func getService(debug bool, profile string) *route53.Route53 {
	config := aws.Config{}
	if profile != "" {
		config.Credentials = credentials.NewSharedCredentials("", profile)
	}
	// ensures throttled requests are retried
	config.MaxRetries = aws.Int(100)
	if debug {
		config.LogLevel = aws.LogLevel(aws.LogDebug)
	}
	return route53.New(session.New(), &config)
}
開發者ID:TheBigBear,項目名稱:cli53,代碼行數:12,代碼來源:util.go

示例14: rootCredentials

func (c *CredentialConfig) rootCredentials() client.ConfigProvider {
	config := &aws.Config{
		Region: aws.String(c.Region),
	}
	if c.AccessKey != "" || c.SecretKey != "" {
		config.Credentials = credentials.NewStaticCredentials(c.AccessKey, c.SecretKey, c.Token)
	} else if c.Profile != "" || c.Filename != "" {
		config.Credentials = credentials.NewSharedCredentials(c.Filename, c.Profile)
	}

	return session.New(config)
}
開發者ID:jeichorn,項目名稱:telegraf,代碼行數:12,代碼來源:credentials.go

示例15: main

func main() {

	reportTable := map[string]float64{}
	constTable := map[string]string{}
	screds := credentials.NewSharedCredentials("/Users/ilyakravchenko/.aws/credentials", "myal")
	config := aws.Config{Region: aws.String("us-east-1"), Credentials: screds}
	sess := session.New(&config)
	if sess == nil {
		fmt.Println("problems with authorization")
	}
	svc := ec2.New(sess)
	params := &ec2.DescribeInstancesInput{}
	resp, err := svc.DescribeInstances(params)
	if err != nil {
		fmt.Println(err.Error())
		return
	}

	for index, _ := range resp.Reservations {
		for _, instance := range resp.Reservations[index].Instances {
			for _, tag := range instance.Tags {
				if *tag.Key == "Name" {
					extraInfo := *instance.InstanceType + "," + *instance.PrivateIpAddress //store extra info
					constTable[*tag.Value] = extraInfo
					_, ok := reportTable[*tag.Value]
					if !ok {
						reportTable[*tag.Value] = getPrice(*instance.InstanceType)

					} else {
						reportTable[*tag.Value] += getPrice(*instance.InstanceType)
					}
				}
			}
		}
	}
	for key, _ := range reportTable {
		_, ok := constTable[key]
		if ok {
			val := reportTable[key]
			constTable[key] = strconv.FormatFloat(val, 'f', 2, 64) + "," + constTable[key]
		}
	}
	table := tablewriter.NewWriter(os.Stdout)
	table.SetHeader([]string{"Type", "Price", "IP", "Name"})
	for k, v := range constTable {
		s := strings.Split(v, ",")
		s = []string{s[1], s[0], s[2]}

		table.Append(append(s, k))
	}
	table.Render()
}
開發者ID:ikrauchanka,項目名稱:tahoa-cleo,代碼行數:52,代碼來源:ec2_stat.go


注:本文中的github.com/aws/aws-sdk-go/aws/credentials.NewSharedCredentials函數示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。