Search code examples
amazon-web-servicesgoamazon-iamaws-sdk-go

How to run AWS SDK version 2 with credentials from variables?


My question is the same as this other question: How to run AWS SDK with credentials from variables? but I am using SDK version 2 which no longer uses Session (if I understand correctly).

So, I am creating a new client, and I have the credentials as variables. I need to use the IAM service. Here is the function:

func getIAMClient(ctx context.Context) (*iam.Client, error) {
    cfg, err := config.LoadDefaultConfig(ctx, config.WithRegion("no-region"))
    if err != nil {
        return nil, errors.Wrap(err)
    }

    cfg.HTTPClient, err = getHTTPClient(ctx)
    if err != nil {
        return nil, err
    }

    return iam.NewFromConfig(cfg), nil
}

Different users will use the app at the same time, so I can't just use ENV files, but I haven't been able to find a documentation page explaining how to pass these credentials to my Client. Any support will be appreciated!


Solution

  • This can be achieved with the StaticCredentialsProvider as described in section "Static Credentials" of the AWS SDK for Go V2 documentation:

    cfg, err := config.LoadDefaultConfig(ctx, config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider("AKID", "SECRET_KEY", "TOKEN")))