[英]How to Assume Cross-Account Role?
AWS' Golang SDK says that I should use stscreds.AssumeRoleProvider
to assume a cross-account role (in this case, for querying another account's DynamoDb table from a web server). AWS 的 Golang SDK 说我应该使用stscreds.AssumeRoleProvider
来承担跨账户角色(在这种情况下,用于从 Web 服务器查询另一个账户的 DynamoDb 表)。 This code works:此代码有效:
var sess *session.Session
func init() {
sess = session.Must(session.NewSession(&aws.Config{
Region: aws.String("us-west-2"),
}))
}
func getDynamoDbClient() *dynamodb.DynamoDB {
crossAccountRoleArn := "arn:...:my-cross-account-role-ARN"
creds := stscreds.NewCredentials(sess, crossAccountRoleArn, func(arp *stscreds.AssumeRoleProvider) {
arp.RoleSessionName = "my-role-session-name"
arp.Duration = 60 * time.Minute
arp.ExpiryWindow = 30 * time.Second
})
dynamoDbClient := dynamodb.New(sess, aws.NewConfig().WithCredentials(creds))
return dynamoDbClient
}
According to the documentation, the returned client is thread-safe:根据文档,返回的客户端是线程安全的:
DynamoDB methods are safe to use concurrently. DynamoDB 方法可以安全地同时使用。
The question is, since the credential are auto-renewed via stscreds.AssumeRoleProvider
, do I问题是,由于凭证是通过stscreds.AssumeRoleProvider
自动更新的,我是否
Need to new up a new client on each request (to ensure that I've got unexpired credentials), or需要针对每个请求新建一个新客户端(以确保我有未过期的凭据),或
Can I new up a DynamoDb client when the web server starts up, and reuse it for the life of the web server?我可以在 Web 服务器启动时新建一个 DynamoDb 客户端,并在 Web 服务器的整个生命周期中重复使用它吗?
I dug into the source code for the Golang AWS SDK, and it looks like the credentials returned by stscreds.NewCredentials()
are nothing more than a wrapper around a reference to the stscreds.AssumeRoleProvider
.我深入研究了 Golang AWS SDK 的源代码,看起来stscreds.NewCredentials()
返回的凭证只不过是对stscreds.AssumeRoleProvider
的引用的包装器。 So it seems likely to me that the client will magically get auto-renewed credentials.因此,在我看来,客户端很可能会神奇地获得自动更新的凭据。
AWS' documentation leaves something to be desired. AWS 的文档留下了一些不足之处。
roleArn := "arn:aws:iam::1234567890:role/my-role"
awsSession, _ := session.NewSession(&aws.Config{
Region: aws.String("us-west-2"),
})
stsClient := sts.New(awsSession)
stsRequest := sts.AssumeRoleInput{
RoleArn: aws.String(roleArn),
RoleSessionName: aws.String("my-role-test"),
DurationSeconds: aws.Int64(900), //min allowed
}
stsResponse, err := stsClient.AssumeRole(&stsRequest)
if err != nil {
log.Fatal("an exception occurred when attempting to assume the my role. error=" + err.Error())
}
os.Setenv("AWS_ACCESS_KEY_ID", *stsResponse.Credentials.AccessKeyId)
os.Setenv("AWS_SECRET_ACCESS_KEY", *stsResponse.Credentials.SecretAccessKey)
os.Setenv("AWS_SESSION_TOKEN", *stsResponse.Credentials.SessionToken)
os.Setenv("AWS_SECURITY_TOKEN", *stsResponse.Credentials.SessionToken)
os.Setenv("ASSUMED_ROLE", roleArn)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.