Last active
July 22, 2022 08:30
-
-
Save tchen/c9b213e960debb7b287130387edb5c1e to your computer and use it in GitHub Desktop.
aws-sdk-go-v2 credentials
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// How to set up a AWS SDK client using credentials coming from other than the regular AWS_ACCESS_KEY_ID | |
// e.g. if you have multiple sets of credentials for doing cross-account stuff | |
import ( | |
"os" | |
"github.com/aws/aws-sdk-go-v2/aws" | |
"github.com/aws/aws-sdk-go-v2/service/s3" | |
) | |
type MyProvider struct {} | |
// Implements the CredentialsProvider interface | |
// https://pkg.go.dev/github.com/aws/aws-sdk-go-v2/aws#CredentialsProvider | |
func (m MyProvider) Retrieve(ctx context.Context) (aws.Credentials, error) { | |
accessKey, ok := os.LookupEnv("OTHER_AWS_ACCESS_KEY_ID") | |
if !ok { | |
panic("Missing OTHER_AWS_ACCESS_KEY_ID") | |
} | |
secretKey, ok := os.LookupEnv("OTHER_AWS_SECRET_ACCESS_KEY") | |
if !ok { | |
panic("Missing OTHER_AWS_ACCESS_KEY_ID") | |
} | |
return aws.Credentials { | |
AccessKeyID: accessKey, | |
SecretAccessKey: secretKey, | |
SessionToken: "", | |
CanExpire: false, | |
}, nil | |
} | |
// Creates a S3 client, but this could be client for other services | |
func S3Client() (*s3.Client, error) { | |
provider := MyProvider{} | |
options := s3.Options { | |
Credentials: provider, | |
Region: "us-east-1", | |
} | |
client := s3.New(options) | |
return client, nil | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// A Second way of doing it, using a built-in StaticCredentialsProvider | |
import ( | |
"context" | |
"os" | |
"github.com/aws/aws-sdk-go-v2/config" | |
"github.com/aws/aws-sdk-go-v2/credentials" | |
"github.com/aws/aws-sdk-go-v2/service/s3" | |
) | |
func S3Client() (*s3.Client, error) { | |
accessKey, ok := os.LookupEnv("OTHER_AWS_ACCESS_KEY_ID") | |
if !ok { | |
panic("Missing OTHER_AWS_ACCESS_KEY_ID") | |
} | |
secretKey, ok := os.LookupEnv("OTHER_AWS_SECRET_ACCESS_KEY") | |
if !ok { | |
panic("Missing OTHER_AWS_ACCESS_KEY_ID") | |
} | |
config, err := config.LoadDefaultConfig(context.TODO(), | |
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKey, secretKey, "")), | |
config.WithRegion("us-east-1"), | |
) | |
if err != nil { | |
return nil, err | |
} | |
client := s3.NewFromConfig(config) | |
return client, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment