@@ -3,9 +3,11 @@ package common
33import (
44 "context"
55 "fmt"
6+ "os"
67
78 "github.com/aws/aws-sdk-go-v2/aws"
89 "github.com/aws/aws-sdk-go-v2/config"
10+ "github.com/aws/aws-sdk-go-v2/credentials/stscreds"
911 "github.com/aws/aws-sdk-go-v2/service/ec2"
1012 "github.com/aws/aws-sdk-go-v2/service/sts"
1113 "github.com/charmbracelet/log"
@@ -79,18 +81,33 @@ func GetAccountID(ctx context.Context, cfg aws.Config) (string, error) {
7981func InitAWSConfig (ctx context.Context , region string ) (aws.Config , error ) {
8082 // Try to load AWS config with explicit credentials
8183 cfg , err := config .LoadDefaultConfig (ctx , config .WithRegion (region ))
82- if err != nil {
83- log .Warn ("Failed to load AWS config with default credentials, checking environment" , "error" , err )
84-
85- // If default config fails, try to get credentials from environment or other sources
86- cfg , err = config .LoadDefaultConfig (ctx ,
87- config .WithRegion (region ),
88- config .WithSharedConfigProfile ("default" ))
84+ if err != nil {
85+ log .Warn ("LoadDefaultConfig failed, falling back to shared profile" , "error" , err )
86+ cfg , err = config .LoadDefaultConfig (ctx ,
87+ config .WithRegion (region ),
88+ config .WithSharedConfigProfile ("default" ),
89+ )
90+ if err != nil {
91+ return aws.Config {}, fmt .Errorf ("failed to load AWS config: %w" , err )
92+ }
93+ }
94+
95+ if roleArn := os .Getenv ("AWS_ROLE_ARN" ); roleArn != "" {
96+ stsClient := sts .NewFromConfig (cfg )
97+ sessName := os .Getenv ("AWS_ROLE_SESSION_NAME" )
98+ if sessName == "" {
99+ sessName = "aws-sdk-go-session"
100+ }
101+
102+ cfg .Credentials = aws .NewCredentialsCache (
103+ stscreds .NewAssumeRoleProvider (stsClient , roleArn , func (o * stscreds.AssumeRoleOptions ) {
104+ o .RoleSessionName = sessName
105+ // o.Duration can be tweaked here if you need longer-lived tokens
106+ }),
107+ )
108+ log .Info ("Configured STS AssumeRole" , "role_arn" , roleArn , "session" , sessName )
109+ }
89110
90- if err != nil {
91- return aws.Config {}, fmt .Errorf ("failed to load AWS config: %w" , err )
92- }
93- }
94111
95112 // Verify credentials are valid before proceeding
96113 credentials , err := cfg .Credentials .Retrieve (ctx )
0 commit comments