本文整理汇总了Golang中github.com/aws/aws-sdk-go/aws/credentials.NewChainCredentials函数的典型用法代码示例。如果您正苦于以下问题:Golang NewChainCredentials函数的具体用法?Golang NewChainCredentials怎么用?Golang NewChainCredentials使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewChainCredentials函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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
}
开发者ID:lvjp,项目名称:packer,代码行数:36,代码来源:access_config.go
示例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
}
开发者ID:skwong2,项目名称:telegraf,代码行数:27,代码来源:cloudwatch.go
示例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)
}
开发者ID:wangy1931,项目名称:grafana,代码行数:35,代码来源:cloudwatch.go
示例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
}
开发者ID:uttarasridhar,项目名称:amazon-ecs-cli,代码行数:26,代码来源:config.go
示例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
}
开发者ID:PagerDuty,项目名称:nomad,代码行数:28,代码来源:get_s3.go
示例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
}
开发者ID:svanharmelen,项目名称:vault,代码行数:62,代码来源:s3.go
示例7: getCred
func getCred(providers []credentials.Provider) *credentials.Credentials {
cred := credentials.NewChainCredentials(providers)
_, credErr := cred.Get()
if credErr != nil {
panic(credErr)
}
return cred
}
开发者ID:daichenge,项目名称:AWSnycast,代码行数:8,代码来源:aws.go
示例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
}
开发者ID:luizbafilho,项目名称:fusis,代码行数:60,代码来源:command.go
示例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)}
}
开发者ID:opsee,项目名称:vinz-clortho,代码行数:9,代码来源:main.go
示例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()
}
开发者ID:simpsora,项目名称:aws-vault,代码行数:11,代码来源:provider.go
示例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,
}
}
开发者ID:TV4,项目名称:s3,代码行数:11,代码来源:s3.go
示例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())},
})
}
开发者ID:jszwedko,项目名称:ec2-metadatafs,代码行数:11,代码来源:main.go
示例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
}
开发者ID:NextGenIntelligence,项目名称:terraform,代码行数:53,代码来源:s3.go
示例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)
}
开发者ID:u-foka,项目名称:machine,代码行数:13,代码来源:awscredentials.go
示例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,
},
})
}
开发者ID:40a,项目名称:bootkube,代码行数:18,代码来源:defaults.go
示例16: CreateImageRepo
// CreateImageRepo create a repository for the image on amazon's ECR(EC2 Container Repository)
// if it doesn't exist as repository needs to be present before pushing and image into it.
func CreateImageRepo(reponame string, params map[string]string) error {
var (
accessKey string
secretKey string
regionName string
ok bool
)
accessKey, ok = params["accesskey"]
if !ok {
accessKey = ""
}
secretKey, ok = params["secretkey"]
if !ok {
secretKey = ""
}
regionName, ok = params["region"]
if !ok || fmt.Sprint(regionName) == "" {
return fmt.Errorf("No region parameter provided")
}
region := fmt.Sprint(regionName)
creds := credentials.NewChainCredentials([]credentials.Provider{
&credentials.StaticProvider{
Value: credentials.Value{
AccessKeyID: accessKey,
SecretAccessKey: secretKey,
},
},
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{},
&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(session.New())},
})
awsConfig := aws.NewConfig()
awsConfig.WithCredentials(creds)
awsConfig.WithRegion(region)
svc := ecr.New(session.New(awsConfig))
repoInput := &ecr.CreateRepositoryInput{
RepositoryName: aws.String(reponame),
}
_, err := svc.CreateRepository(repoInput)
if err != nil {
if s3Err, ok := err.(awserr.Error); ok && s3Err.Code() == "RepositoryAlreadyExistsException" {
return nil
}
return err
}
return nil
}
开发者ID:bacongobbler,项目名称:builder,代码行数:52,代码来源:image_repo.go
示例17: getCreds
// This function is responsible for reading credentials from the
// environment in the case that they're not explicitly specified
// in the Terraform configuration.
func getCreds(key, secret, token, profile, credsfile string) *awsCredentials.Credentials {
// build a chain provider, lazy-evaulated by aws-sdk
providers := []awsCredentials.Provider{
&awsCredentials.StaticProvider{Value: awsCredentials.Value{
AccessKeyID: key,
SecretAccessKey: secret,
SessionToken: token,
}},
&awsCredentials.EnvProvider{},
&awsCredentials.SharedCredentialsProvider{
Filename: credsfile,
Profile: profile,
},
}
// We only look in the EC2 metadata API if we can connect
// to the metadata service within a reasonable amount of time
metadataURL := os.Getenv("AWS_METADATA_URL")
if metadataURL == "" {
metadataURL = "http://169.254.169.254:80/latest"
}
c := http.Client{
Timeout: 100 * time.Millisecond,
}
r, err := c.Get(metadataURL)
// Flag to determine if we should add the EC2Meta data provider. Default false
var useIAM bool
if err == nil {
// AWS will add a "Server: EC2ws" header value for the metadata request. We
// check the headers for this value to ensure something else didn't just
// happent to be listening on that IP:Port
if r.Header["Server"] != nil && strings.Contains(r.Header["Server"][0], "EC2") {
useIAM = true
}
}
if useIAM {
log.Printf("[DEBUG] EC2 Metadata service found, adding EC2 Role Credential Provider")
providers = append(providers, &ec2rolecreds.EC2RoleProvider{
Client: ec2metadata.New(session.New(&aws.Config{
Endpoint: aws.String(metadataURL),
})),
})
} else {
log.Printf("[DEBUG] EC2 Metadata service not found, not adding EC2 Role Credential Provider")
}
return awsCredentials.NewChainCredentials(providers)
}
开发者ID:discogestalt,项目名称:terraform,代码行数:52,代码来源:config.go
示例18: TestGetCredentialProvidersWhenEC2MetadataServiceReturnsFailure
func TestGetCredentialProvidersWhenEC2MetadataServiceReturnsFailure(t *testing.T) {
server := initTestServer("2016-06-19T00:00:00Z", true)
defer server.Close()
metadataClient := ec2metadata.New(session.New(), &aws.Config{Endpoint: aws.String(server.URL + "/latest")})
ecsConfig := NewCliConfig(clusterName)
ecsConfig.Region = region
credentialProviders := ecsConfig.getCredentialProviders(metadataClient)
chainCredentials := credentials.NewChainCredentials(credentialProviders)
_, err := chainCredentials.Get()
if err == nil {
t.Error("Expected an error while retrieving credentials from EC2 metadata service")
}
}
开发者ID:uttarasridhar,项目名称:amazon-ecs-cli,代码行数:15,代码来源:config_test.go
示例19: handleDescribeInstances
func handleDescribeInstances(req *cwRequest, c *middleware.Context) {
sess := session.New()
creds := credentials.NewChainCredentials(
[]credentials.Provider{
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{Filename: "", Profile: req.DataSource.Database},
&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(sess), ExpiryWindow: 5 * time.Minute},
})
cfg := &aws.Config{
Region: aws.String(req.Region),
Credentials: creds,
}
svc := ec2.New(session.New(cfg), cfg)
reqParam := &struct {
Parameters struct {
Filters []*ec2.Filter `json:"filters"`
InstanceIds []*string `json:"instanceIds"`
} `json:"parameters"`
}{}
json.Unmarshal(req.Body, reqParam)
params := &ec2.DescribeInstancesInput{}
if len(reqParam.Parameters.Filters) > 0 {
params.Filters = reqParam.Parameters.Filters
}
if len(reqParam.Parameters.InstanceIds) > 0 {
params.InstanceIds = reqParam.Parameters.InstanceIds
}
var resp ec2.DescribeInstancesOutput
err := svc.DescribeInstancesPages(params,
func(page *ec2.DescribeInstancesOutput, lastPage bool) bool {
reservations, _ := awsutil.ValuesAtPath(page, "Reservations")
for _, reservation := range reservations {
resp.Reservations = append(resp.Reservations, reservation.(*ec2.Reservation))
}
return !lastPage
})
if err != nil {
c.JsonApiErr(500, "Unable to call AWS API", err)
return
}
c.JSON(200, resp)
}
开发者ID:vkroz,项目名称:grafana,代码行数:48,代码来源:cloudwatch.go
示例20: getCredentials
func getCredentials(profile string) *credentials.Credentials {
if _, ok := awsCredentials[profile]; ok {
return awsCredentials[profile]
}
sess := session.New()
creds := credentials.NewChainCredentials(
[]credentials.Provider{
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{Filename: "", Profile: profile},
&ec2rolecreds.EC2RoleProvider{Client: ec2metadata.New(sess), ExpiryWindow: 5 * time.Minute},
})
awsCredentials[profile] = creds
return creds
}
开发者ID:keis,项目名称:grafana,代码行数:16,代码来源:cloudwatch.go
注:本文中的github.com/aws/aws-sdk-go/aws/credentials.NewChainCredentials函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论