Skip to content

Commit

Permalink
fix: load AWS config and assume role
Browse files Browse the repository at this point in the history
Signed-off-by: Luis Davim <dluis@vmware.com>
  • Loading branch information
luisdavim committed Aug 3, 2023
1 parent 06628cf commit a272382
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 13 deletions.
1 change: 1 addition & 0 deletions changelogs/unreleased/6598-aws_creds
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix how the AWS credentials are obtained from configuration
31 changes: 18 additions & 13 deletions pkg/repository/config/aws.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,9 @@ import (

goerr "errors"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/credentials/stscreds"
"github.com/aws/aws-sdk-go/aws/endpoints"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/s3/s3manager"
Expand All @@ -33,6 +35,7 @@ import (
const (
// AWS specific environment variable
awsProfileEnvVar = "AWS_PROFILE"
awsRoleEnvVar = "AWS_ROLE_ARN"
awsProfileKey = "profile"
awsCredentialsFileEnvVar = "AWS_SHARED_CREDENTIALS_FILE"
)
Expand All @@ -51,32 +54,34 @@ func GetS3ResticEnvVars(config map[string]string) (map[string]string, error) {
result[awsProfileEnvVar] = profile
}

if creds, err := GetS3Credentials(config); err == nil {
result["AWS_ACCESS_KEY_ID"] = creds.AccessKeyID
result["AWS_SECRET_ACCESS_KEY"] = creds.SecretAccessKey
result["AWS_SESSION_TOKEN"] = creds.SessionToken
}

return result, nil
}

// GetS3Credentials gets the S3 credential values according to the information
// of the provided config or the system's environment variables
func GetS3Credentials(config map[string]string) (*credentials.Value, error) {
if len(os.Getenv("AWS_ROLE_ARN")) > 0 {
if os.Getenv(awsRoleEnvVar) != "" && os.Getenv(awsCredentialsFileEnvVar) == "" {
return nil, nil
}

credentialsFile := config[CredentialsFileKey]
if credentialsFile == "" {
credentialsFile = os.Getenv("AWS_SHARED_CREDENTIALS_FILE")
}

if credentialsFile == "" {
return nil, errors.New("missing credential file")
}

creds := credentials.NewSharedCredentials(credentialsFile, "")
credValue, err := creds.Get()
awsConfig := aws.NewConfig().WithMaxRetries(2)
sess, err := session.NewSession(awsConfig)
if err != nil {
return nil, err
}
if os.Getenv(awsRoleEnvVar) != "" {
sess.Config.WithCredentials(stscreds.NewCredentials(sess, os.Getenv(awsRoleEnvVar)))
}

creds, err := sess.Config.Credentials.Get()

return &credValue, nil
return &creds, err
}

// GetAWSBucketRegion returns the AWS region that a bucket is in, or an error
Expand Down

0 comments on commit a272382

Please sign in to comment.