本文整理匯總了Golang中github.com/aws/aws-sdk-go/aws/credentials.NewChainCredentials函數的典型用法代碼示例。如果您正苦於以下問題:Golang NewChainCredentials函數的具體用法?Golang NewChainCredentials怎麽用?Golang NewChainCredentials使用的例子?那麽, 這裏精選的函數代碼示例或許可以為您提供幫助。
在下文中一共展示了NewChainCredentials函數的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Golang代碼示例。
示例1: Config
// Config returns a valid aws.Config object for access to AWS services, or
// an error if the authentication and region couldn't be resolved
func (c *AccessConfig) Config() (*aws.Config, error) {
var creds *credentials.Credentials
region, err := c.Region()
if err != nil {
return nil, err
}
config := aws.NewConfig().WithRegion(region).WithMaxRetries(11)
if c.ProfileName != "" {
profile, err := NewFromProfile(c.ProfileName)
if err != nil {
return nil, err
}
creds, err = profile.CredentialsFromProfile(config)
if err != nil {
return nil, err
}
} else {
sess := session.New(config)
creds = credentials.NewChainCredentials([]credentials.Provider{
&credentials.StaticProvider{Value: credentials.Value{
AccessKeyID: c.AccessKey,
SecretAccessKey: c.SecretKey,
SessionToken: c.Token,
}},
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{Filename: "", Profile: ""},
&ec2rolecreds.EC2RoleProvider{
Client: ec2metadata.New(sess),
},
})
}
return config.WithCredentials(creds), nil
}
示例2: Connect
func (c *CloudWatch) Connect() error {
Config := &aws.Config{
Region: aws.String(c.Region),
Credentials: credentials.NewChainCredentials(
[]credentials.Provider{
&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(session.New())},
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{},
}),
}
svc := cloudwatch.New(session.New(Config))
params := &cloudwatch.ListMetricsInput{
Namespace: aws.String(c.Namespace),
}
_, err := svc.ListMetrics(params) // Try a read-only call to test connection.
if err != nil {
log.Printf("cloudwatch: Error in ListMetrics API call : %+v \n", err.Error())
}
c.svc = svc
return err
}
示例3: handleListMetrics
func handleListMetrics(req *cwRequest, c *middleware.Context) {
creds := credentials.NewChainCredentials(
[]credentials.Provider{
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{Filename: "", Profile: req.DataSource.Database},
&ec2rolecreds.EC2RoleProvider{ExpiryWindow: 5 * time.Minute},
})
svc := cloudwatch.New(&aws.Config{
Region: aws.String(req.Region),
Credentials: creds,
})
reqParam := &struct {
Parameters struct {
Namespace string `json:"namespace"`
MetricName string `json:"metricName"`
Dimensions []*cloudwatch.DimensionFilter `json:"dimensions"`
} `json:"parameters"`
}{}
json.Unmarshal(req.Body, reqParam)
params := &cloudwatch.ListMetricsInput{
Namespace: aws.String(reqParam.Parameters.Namespace),
MetricName: aws.String(reqParam.Parameters.MetricName),
Dimensions: reqParam.Parameters.Dimensions,
}
resp, err := svc.ListMetrics(params)
if err != nil {
c.JsonApiErr(500, "Unable to call AWS API", err)
return
}
c.JSON(200, resp)
}
示例4: ToServiceConfig
// ToServiceConfig creates an aws Config object from the CliConfig object.
func (cfg *CliConfig) ToServiceConfig() (*aws.Config, error) {
region := cfg.getRegion()
if region == "" {
return nil, fmt.Errorf("Set a region with the --%s flag or %s environment variable", cli.RegionFlag, cli.AwsRegionEnvVar)
}
awsDefaults := defaults.Get()
credentialProviders := cfg.getCredentialProviders(cfg.getEC2MetadataClient(&awsDefaults))
chainCredentials := credentials.NewChainCredentials(credentialProviders)
creds, err := chainCredentials.Get()
if err != nil {
return nil, err
}
// This is just a fail-fast check to ensure that valid credentials are available before returning to the caller.
if creds.AccessKeyID == "" {
return nil, fmt.Errorf("Error getting valid credentials")
}
svcConfig := awsDefaults.Config
svcConfig.Region = aws.String(region)
svcConfig.Credentials = chainCredentials
return svcConfig, nil
}
示例5: getAWSConfig
func (g *S3Getter) getAWSConfig(region string, creds *credentials.Credentials) *aws.Config {
conf := &aws.Config{}
if creds == nil {
// Grab the metadata URL
metadataURL := os.Getenv("AWS_METADATA_URL")
if metadataURL == "" {
metadataURL = "http://169.254.169.254:80/latest"
}
creds = credentials.NewChainCredentials(
[]credentials.Provider{
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{Filename: "", Profile: ""},
&ec2rolecreds.EC2RoleProvider{
Client: ec2metadata.New(session.New(&aws.Config{
Endpoint: aws.String(metadataURL),
})),
},
})
}
conf.Credentials = creds
if region != "" {
conf.Region = aws.String(region)
}
return conf
}
示例6: newS3Backend
// newS3Backend constructs a S3 backend using a pre-existing
// bucket. Credentials can be provided to the backend, sourced
// from the environment, AWS credential files or by IAM role.
func newS3Backend(conf map[string]string) (Backend, error) {
bucket, ok := conf["bucket"]
if !ok {
return nil, fmt.Errorf("'bucket' must be set")
}
access_key, ok := conf["access_key"]
if !ok {
access_key = ""
}
secret_key, ok := conf["secret_key"]
if !ok {
secret_key = ""
}
session_token, ok := conf["session_token"]
if !ok {
session_token = ""
}
endpoint, ok := conf["endpoint"]
if !ok {
endpoint = os.Getenv("AWS_S3_ENDPOINT")
}
region, ok := conf["region"]
if !ok {
region = os.Getenv("AWS_DEFAULT_REGION")
if region == "" {
region = "us-east-1"
}
}
creds := credentials.NewChainCredentials([]credentials.Provider{
&credentials.StaticProvider{Value: credentials.Value{
AccessKeyID: access_key,
SecretAccessKey: secret_key,
SessionToken: session_token,
}},
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{Filename: "", Profile: ""},
&ec2rolecreds.EC2RoleProvider{},
})
s3conn := s3.New(session.New(&aws.Config{
Credentials: creds,
Endpoint: aws.String(endpoint),
Region: aws.String(region),
}))
_, err := s3conn.HeadBucket(&s3.HeadBucketInput{Bucket: &bucket})
if err != nil {
return nil, fmt.Errorf("unable to access bucket '%s': %v", bucket, err)
}
s := &S3Backend{
client: s3conn,
bucket: bucket,
}
return s, nil
}
示例7: getCred
func getCred(providers []credentials.Provider) *credentials.Credentials {
cred := credentials.NewChainCredentials(providers)
_, credErr := cred.Get()
if credErr != nil {
panic(credErr)
}
return cred
}
示例8: discoverEc2Hosts
// discoverEc2Hosts searches an AWS region, returning a list of instance ips
// where EC2TagKey = EC2TagValue
func (c *Config) discoverEc2Hosts(logger *log.Logger) ([]string, error) {
config := c.RetryJoinEC2
ec2meta := ec2metadata.New(session.New())
if config.Region == "" {
logger.Printf("[INFO] agent: No EC2 region provided, querying instance metadata endpoint...")
identity, err := ec2meta.GetInstanceIdentityDocument()
if err != nil {
return nil, err
}
config.Region = identity.Region
}
awsConfig := &aws.Config{
Region: &config.Region,
Credentials: credentials.NewChainCredentials(
[]credentials.Provider{
&credentials.StaticProvider{
Value: credentials.Value{
AccessKeyID: config.AccessKeyID,
SecretAccessKey: config.SecretAccessKey,
},
},
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{},
defaults.RemoteCredProvider(*(defaults.Config()), defaults.Handlers()),
}),
}
svc := ec2.New(session.New(), awsConfig)
resp, err := svc.DescribeInstances(&ec2.DescribeInstancesInput{
Filters: []*ec2.Filter{
{
Name: aws.String("tag:" + config.TagKey),
Values: []*string{
aws.String(config.TagValue),
},
},
},
})
if err != nil {
return nil, err
}
var servers []string
for i := range resp.Reservations {
for _, instance := range resp.Reservations[i].Instances {
// Terminated instances don't have the PrivateIpAddress field
if instance.PrivateIpAddress != nil {
servers = append(servers, *instance.PrivateIpAddress)
}
}
}
return servers, nil
}
示例9: getAWSConfig
func getAWSConfig(c *cli.Context) *aws.Config {
creds := credentials.NewChainCredentials(
[]credentials.Provider{
&credentials.EnvProvider{},
&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(session.New(&aws.Config{})), ExpiryWindow: 5 * time.Minute},
})
region := c.GlobalString("region")
return &aws.Config{Credentials: creds, Region: aws.String(region)}
}
示例10: getMasterCreds
func (p *VaultProvider) getMasterCreds() (credentials.Value, error) {
source := p.profiles.sourceProfile(p.profile)
provider := credentials.NewChainCredentials([]credentials.Provider{
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{Filename: "", Profile: p.profile},
&KeyringProvider{Keyring: p.keyring, Profile: source},
})
return provider.Get()
}
示例11: awsConfig
func awsConfig(id, secret, region string) *aws.Config {
return &aws.Config{
Credentials: credentials.NewChainCredentials([]credentials.Provider{
&credentials.StaticProvider{
Value: credentials.Value{AccessKeyID: id, SecretAccessKey: secret},
},
}),
Logger: aws.NewDefaultLogger(),
Region: ®ion,
}
}
示例12: credentialChain
func (a *awsCredentials) credentialChain() *credentials.Credentials {
return credentials.NewChainCredentials([]credentials.Provider{
&credentials.StaticProvider{Value: credentials.Value{
AccessKeyID: a.AWSAccessKeyID,
SecretAccessKey: a.AWSAccessKeyID,
SessionToken: a.AWSSessionToken}},
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{},
&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(session.New())},
})
}
示例13: s3Factory
func s3Factory(conf map[string]string) (Client, error) {
bucketName, ok := conf["bucket"]
if !ok {
return nil, fmt.Errorf("missing 'bucket' configuration")
}
keyName, ok := conf["key"]
if !ok {
return nil, fmt.Errorf("missing 'key' configuration")
}
regionName, ok := conf["region"]
if !ok {
regionName = os.Getenv("AWS_DEFAULT_REGION")
if regionName == "" {
return nil, fmt.Errorf(
"missing 'region' configuration or AWS_DEFAULT_REGION environment variable")
}
}
accessKeyId := conf["access_key"]
secretAccessKey := conf["secret_key"]
credentialsProvider := credentials.NewChainCredentials([]credentials.Provider{
&credentials.StaticProvider{Value: credentials.Value{
AccessKeyID: accessKeyId,
SecretAccessKey: secretAccessKey,
SessionToken: "",
}},
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{Filename: "", Profile: ""},
&credentials.EC2RoleProvider{},
})
// Make sure we got some sort of working credentials.
_, err := credentialsProvider.Get()
if err != nil {
return nil, fmt.Errorf("Unable to determine AWS credentials. Set the AWS_ACCESS_KEY_ID and "+
"AWS_SECRET_ACCESS_KEY environment variables.\n(error was: %s)", err)
}
awsConfig := &aws.Config{
Credentials: credentialsProvider,
Region: regionName,
}
nativeClient := s3.New(awsConfig)
return &S3Client{
nativeClient: nativeClient,
bucketName: bucketName,
keyName: keyName,
}, nil
}
示例14: Credentials
func (c *defaultAWSCredentials) Credentials() *credentials.Credentials {
providers := []credentials.Provider{}
if c.AccessKey != "" && c.SecretKey != "" {
providers = append(providers, c.providerFactory.NewStaticProvider(c.AccessKey, c.SecretKey, c.SessionToken))
}
if c.fallbackProvider != nil {
fallbackCreds, err := c.fallbackProvider.Credentials().Get()
if err == nil {
providers = append(providers, &credentials.StaticProvider{Value: fallbackCreds})
}
}
return credentials.NewChainCredentials(providers)
}
示例15: CredChain
// CredChain returns the default credential chain.
//
// Generally you shouldn't need to use this method directly, but
// is available if you need to reset the credentials of an
// existing service client or session's Config.
func CredChain(cfg *aws.Config, handlers request.Handlers) *credentials.Credentials {
endpoint, signingRegion := endpoints.EndpointForRegion(ec2metadata.ServiceName, *cfg.Region, true)
return credentials.NewChainCredentials(
[]credentials.Provider{
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{Filename: "", Profile: ""},
&ec2rolecreds.EC2RoleProvider{
Client: ec2metadata.NewClient(*cfg, handlers, endpoint, signingRegion),
ExpiryWindow: 5 * time.Minute,
},
})
}