Home > Back-end >  Export AWS credentials from Go program (SDK v2, SSO)
Export AWS credentials from Go program (SDK v2, SSO)

Time:02-26

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).

CodePudding user response:

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)
  • Related