Authenticating Go AWS SDK v2 using assume roles

2021-04-30

Assume · Aws · Golang · Roles · Sdk · V2

1 minute

For self reference:

To authenticate the Golang AWS SDK v2 using assume roles, refer to the following code snippets:

ctx := context.Background()
assumecnf, _ := config.LoadDefaultConfig(
ctx, config.WithRegion("{aws-region}"),
config.WithCredentialsProvider(aws.NewCredentialsCache(
credentials.NewStaticCredentialsProvider(
"{aws-assume-role-key}",
"{aws-assume-role-secret}", "",
)),
),
)
stsclient := sts.NewFromConfig(assumecnf)
cnf, _ := config.LoadDefaultConfig(
ctx, config.WithRegion("{aws-region}"),
config.WithCredentialsProvider(aws.NewCredentialsCache(
stscredsv2.NewAssumeRoleProvider(
stsclient,
"{rolearn-to-assume}",
)),
),
)
client := s3.NewFromConfig(cnf)
res, _ := client.GetObject(ctx, &s3.GetObjectInput{
Bucket: awsv2.String("{some-bucket}"),
Key: awsv2.String("{some-key}"),
})
...