From ab795a569c9f084f0f56b42c9ef0113bf4b14101 Mon Sep 17 00:00:00 2001 From: Lucas Pinheiro Date: Thu, 3 Nov 2022 11:03:05 -0300 Subject: [PATCH] feat: add SEMAPHORE_CACHE_USE_EC2_INSTANCE_PROFILE (#375) --- cache-cli/pkg/storage/s3.go | 39 ++++++++++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/cache-cli/pkg/storage/s3.go b/cache-cli/pkg/storage/s3.go index c51efe4a..47adf797 100644 --- a/cache-cli/pkg/storage/s3.go +++ b/cache-cli/pkg/storage/s3.go @@ -7,6 +7,7 @@ import ( "github.com/aws/aws-sdk-go-v2/aws" awsConfig "github.com/aws/aws-sdk-go-v2/config" "github.com/aws/aws-sdk-go-v2/credentials" + "github.com/aws/aws-sdk-go-v2/credentials/ec2rolecreds" "github.com/aws/aws-sdk-go-v2/service/s3" log "github.com/sirupsen/logrus" ) @@ -37,14 +38,46 @@ func createDefaultS3Storage(s3Bucket, project string, storageConfig StorageConfi var config aws.Config var err error + // Using EC2 metadata service to retrieve credentials for the instance profile + if os.Getenv("SEMAPHORE_CACHE_USE_EC2_INSTANCE_PROFILE") == "true" { + log.Infof("Using EC2 instance profile.") + config, err = awsConfig.LoadDefaultConfig( + context.TODO(), + awsConfig.WithCredentialsProvider(ec2rolecreds.New()), + awsConfig.WithEC2IMDSRegion(), + ) + + if err != nil { + return nil, err + } + + return &S3Storage{ + Client: s3.NewFromConfig(config), + Bucket: s3Bucket, + Project: project, + StorageConfig: storageConfig, + }, nil + } + + // Using an existing profile configured in one of the default configuration files. profile := os.Getenv("SEMAPHORE_CACHE_AWS_PROFILE") - if profile == "" { - config, err = awsConfig.LoadDefaultConfig(context.TODO()) - } else { + if profile != "" { log.Infof("Using '%s' AWS profile.", profile) config, err = awsConfig.LoadDefaultConfig(context.TODO(), awsConfig.WithSharedConfigProfile(profile)) + if err != nil { + return nil, err + } + + return &S3Storage{ + Client: s3.NewFromConfig(config), + Bucket: s3Bucket, + Project: project, + StorageConfig: storageConfig, + }, nil } + // No special configuration, just follow the default chain + config, err = awsConfig.LoadDefaultConfig(context.TODO()) if err != nil { return nil, err }