Skip to content

Instantly share code, notes, and snippets.

@stormcat24
Last active June 8, 2023 15:06
Show Gist options
  • Save stormcat24/e8172b4130776e486f2758508eb4f3aa to your computer and use it in GitHub Desktop.
Save stormcat24/e8172b4130776e486f2758508eb4f3aa to your computer and use it in GitHub Desktop.
How to build a configuration to enable IAM roles for service accounts (IRSA)
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
"github.com/aws/aws-sdk-go/aws/session"
)
func buildConfig() {
sess := session.Must(session.NewSession())
aws.NewConfig().
WithCredentialsChainVerboseErrors(true).
WithCredentials(credentials.NewChainCredentials([]credentials.Provider{
&credentials.EnvProvider{},
&credentials.SharedCredentialsProvider{},
// Required for IRSA
stscreds.NewWebIdentityRoleProvider(
sts.New(sess),
os.Getenv("AWS_ROLE_ARN"),
"",
os.Getenv("AWS_WEB_IDENTITY_TOKEN_FILE"),
),
&ec2rolecreds.EC2RoleProvider{
Client: ec2metadata.New(sess),
},
}))
@carnei-ro
Copy link

thanks, very useful!

Updating newer version, it would be:

aws.NewConfig().
WithCredentialsChainVerboseErrors(true).
WithCredentials(credentials.NewChainCredentials([]credentials.Provider{
    &credentials.EnvProvider{},
    &credentials.SharedCredentialsProvider{},
    // Required for IRSA
    stscreds.NewWebIdentityRoleProviderWithOptions(
        sts.New(sess),
        os.Getenv("AWS_ROLE_ARN"),
        "",
        stscreds.FetchTokenPath(os.Getenv("AWS_WEB_IDENTITY_TOKEN_FILE")),
    ),
    &ec2rolecreds.EC2RoleProvider{
        Client: ec2metadata.New(sess),
    },
}))

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment