从Go程序中导出AWS凭证(SDK v2,SSO)

huangapple go评论69阅读模式
英文:

Export AWS credentials from Go program (SDK v2, SSO)

问题

我有一个使用共享SSO身份验证的Go程序。程序本身工作正常,但我需要从它启动一个嵌套程序(docker),并且这个程序需要来自主程序的AWS凭证。

我使用的是AWS SDK v2。

如何将当前凭证导出为环境变量?

我了解可以使用assumeRole,像这样:

	credentials, err := ssoClient.GetRoleCredentials(context.TODO(), &sso.GetRoleCredentialsInput{
		AccountId:   aws.String(accountID),
		RoleName:    aws.String(roleName),
	})

但这是错误的,因为我没有要扮演的角色;我只想使用当前用户。

另一个可能的解决方案是手动解析~/.aws/cli/cache/*.json,但这个解决方案看起来太低级和不可靠(但可能是唯一的解决方案,至少我没有找到更好的方法)。

英文:

I have a Go program which uses shared SSO authentication. The program itself works fine, but I need to start a nested program from it (docker), and this program needs the AWS credentials from the main program.

I use AWS SDK v2.

How can I export my current credentials as environment variables?

I understand that I can use assumeRole, like this:

	credentials, err := ssoClient.GetRoleCredentials(context.TODO(), &sso.GetRoleCredentialsInput{
		AccountId:   aws.String(accountID),
		RoleName:    aws.String(roleName),
	})

but that would be wrong, because I have no role to assume; I just want to use my current user.

Another possible solution could be parsing ~/.aws/cli/cache/*.json manually, but this solutions looks too low level and hacky (but probably it is the only one, at least I didn't manage to find anything better).

答案1

得分: 2

我找到了一个解决方案,比我预期的要简单得多。

可以直接在config结构中获取凭据:

    cfg, err := awsconfig.LoadDefaultConfig(
        context.TODO(),
        awsconfig.WithSharedConfigProfile(profile))
    if err != nil {
        log.Fatalln(err)
    }

    cred, err := cfg.Credentials.Retrieve(context.TODO())
    if err != nil {
        log.Fatalln(err)
    }

    fmt.Printf("export AWS_ACCESS_KEY_ID=\"%s\"\n", cred.AccessKeyID)
    fmt.Printf("export AWS_SECRET_ACCESS_KEY=\"%s\"\n", cred.SecretAccessKey)
    fmt.Printf("export AWS_SESSION_TOKEN=\"%s\"\n", cred.SessionToken)
英文:

I found a solution, and it is much simpler than I expected.

One can take credentials directly in the config struct:

    cfg, err := awsconfig.LoadDefaultConfig(
        context.TODO(),
        awsconfig.WithSharedConfigProfile(profile))
    if err != nil {
        log.Fatalln(err)
    }

    cred, err := cfg.Credentials.Retrieve(context.TODO())
    if err != nil {
        log.Fatalln(err)
    }

    fmt.Printf("export AWS_ACCESS_KEY_ID=\"%s\"\n", cred.AccessKeyID)
    fmt.Printf("export AWS_SECRET_ACCESS_KEY=\"%s\"\n", cred.SecretAccessKey)
    fmt.Printf("export AWS_SESSION_TOKEN=\"%s\"\n", cred.SessionToken)

huangapple
  • 本文由 发表于 2022年2月22日 21:47:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/71222433.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定