Skip to content

Commit 55dfea4

Browse files
feat: Add the ability to assume role
1 parent c605578 commit 55dfea4

File tree

1 file changed

+28
-11
lines changed

1 file changed

+28
-11
lines changed

cmd/ctrlc/root/sync/aws/common/regions.go

Lines changed: 28 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,11 @@ package common
33
import (
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) {
7981
func 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

Comments
 (0)