Home >Backend Development >Golang >How to Use AWS SDK Version 2 with Dynamic Credentials in Go?
Accessing AWS with SDK Version 2 and Dynamic Credentials
Similar to a previous inquiry, this question seeks guidance on using AWS SDK version 2 with credentials stored in variables. Unlike its predecessor, SDK version 2 no longer employs the Session class.
Consider the following function used to instantiate a new client and connect to the IAM service:
<code class="go">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 }</code>
To accommodate multiple users utilizing the application simultaneously, the use of environment variables is impractical. This necessitates an alternative method of passing credentials to the client.
Solution: Utilizing StaticCredentialsProvider
The AWS SDK for Go V2 documentation elucidates the use of StaticCredentialsProvider to achieve this objective, as outlined in the "Static Credentials" section:
<code class="go">cfg, err := config.LoadDefaultConfig(ctx, config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider("AKID", "SECRET_KEY", "TOKEN")))</code>
The above is the detailed content of How to Use AWS SDK Version 2 with Dynamic Credentials in Go?. For more information, please follow other related articles on the PHP Chinese website!