Passing Credentials from Variables to AWS SDK Version 2
This inquiry echoes a previous question regarding using AWS SDK with credentials from variables. However, in this case, SDK version 2 is utilized, which eliminates the Session feature.
To establish a new client with credentials obtained from variables for accessing the IAM service, consider the following function:
<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>
Since multiple users may employ the application simultaneously, utilizing ENV files is impractical. However, documentation explaining how to pass these credentials to a client may not be readily available.
Solution: Static Credentials Provider
To resolve this issue, the StaticCredentialsProvider can be utilized, as outlined in the "Static Credentials" section of the AWS SDK for Go V2 documentation:
<code class="go">cfg, err := config.LoadDefaultConfig(ctx, config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider("AKID", "SECRET_KEY", "TOKEN")))</code>
By incorporating this modification, credentials may be passed from variables to the SDK, enabling the retrieval and use of IAM services.
The above is the detailed content of How to Pass Credentials from Variables to AWS SDK Version 2 for IAM Service Access?. For more information, please follow other related articles on the PHP Chinese website!