-
-
Notifications
You must be signed in to change notification settings - Fork 135
Add AWS YAML functions for identity and region retrieval #1843
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
osterman
wants to merge
3
commits into
main
Choose a base branch
from
osterman/aws-yaml-funcs
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+1,742
−20
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,163 @@ | ||
| package exec | ||
|
|
||
| import ( | ||
| "context" | ||
| "fmt" | ||
| "sync" | ||
|
|
||
| awsUtils "github.com/cloudposse/atmos/internal/aws_utils" | ||
| log "github.com/cloudposse/atmos/pkg/logger" | ||
| "github.com/cloudposse/atmos/pkg/perf" | ||
| "github.com/cloudposse/atmos/pkg/schema" | ||
| ) | ||
|
|
||
| // AWSCallerIdentity holds the information returned by AWS STS GetCallerIdentity. | ||
| type AWSCallerIdentity struct { | ||
| Account string | ||
| Arn string | ||
| UserID string | ||
| Region string // The AWS region from the loaded config. | ||
| } | ||
|
|
||
| // AWSGetter provides an interface for retrieving AWS caller identity information. | ||
| // This interface enables dependency injection and testability. | ||
| // | ||
| //go:generate go run go.uber.org/mock/mockgen@v0.6.0 -source=$GOFILE -destination=mock_aws_getter_test.go -package=exec | ||
| type AWSGetter interface { | ||
| // GetCallerIdentity retrieves the AWS caller identity for the current credentials. | ||
| // Returns the account ID, ARN, and user ID of the calling identity. | ||
| GetCallerIdentity( | ||
| ctx context.Context, | ||
| atmosConfig *schema.AtmosConfiguration, | ||
| authContext *schema.AWSAuthContext, | ||
| ) (*AWSCallerIdentity, error) | ||
| } | ||
|
|
||
| // defaultAWSGetter is the production implementation that uses real AWS SDK calls. | ||
| type defaultAWSGetter struct{} | ||
|
|
||
| // GetCallerIdentity retrieves the AWS caller identity using the STS GetCallerIdentity API. | ||
| func (d *defaultAWSGetter) GetCallerIdentity( | ||
| ctx context.Context, | ||
| atmosConfig *schema.AtmosConfiguration, | ||
| authContext *schema.AWSAuthContext, | ||
| ) (*AWSCallerIdentity, error) { | ||
| defer perf.Track(atmosConfig, "exec.AWSGetter.GetCallerIdentity")() | ||
|
|
||
| log.Debug("Getting AWS caller identity") | ||
|
|
||
| // Use the aws_utils helper to get caller identity (keeps AWS SDK imports in aws_utils). | ||
| result, err := awsUtils.GetAWSCallerIdentity(ctx, "", "", 0, authContext) | ||
| if err != nil { | ||
| return nil, err // Error already wrapped by aws_utils. | ||
| } | ||
|
|
||
| identity := &AWSCallerIdentity{ | ||
| Account: result.Account, | ||
| Arn: result.Arn, | ||
| UserID: result.UserID, | ||
| Region: result.Region, | ||
| } | ||
|
|
||
| log.Debug("Retrieved AWS caller identity", | ||
| "account", identity.Account, | ||
| "arn", identity.Arn, | ||
| "user_id", identity.UserID, | ||
| "region", identity.Region, | ||
| ) | ||
|
|
||
| return identity, nil | ||
| } | ||
|
|
||
| // awsGetter is the global instance used by YAML functions. | ||
| // This allows test code to replace it with a mock. | ||
| var awsGetter AWSGetter = &defaultAWSGetter{} | ||
|
|
||
| // SetAWSGetter allows tests to inject a mock AWSGetter. | ||
| // Returns a function to restore the original getter. | ||
| func SetAWSGetter(getter AWSGetter) func() { | ||
| defer perf.Track(nil, "exec.SetAWSGetter")() | ||
|
|
||
| original := awsGetter | ||
| awsGetter = getter | ||
| return func() { | ||
| awsGetter = original | ||
| } | ||
| } | ||
|
|
||
| // cachedAWSIdentity holds the cached AWS caller identity. | ||
| // The cache is per-CLI-invocation (stored in memory) to avoid repeated STS calls. | ||
| type cachedAWSIdentity struct { | ||
| identity *AWSCallerIdentity | ||
| err error | ||
| } | ||
|
|
||
| var ( | ||
| awsIdentityCache map[string]*cachedAWSIdentity | ||
| awsIdentityCacheMu sync.RWMutex | ||
| ) | ||
|
|
||
| func init() { | ||
| awsIdentityCache = make(map[string]*cachedAWSIdentity) | ||
| } | ||
|
|
||
| // getCacheKey generates a cache key based on the auth context. | ||
| // Different auth contexts (different credentials) get different cache entries. | ||
| func getCacheKey(authContext *schema.AWSAuthContext) string { | ||
| if authContext == nil { | ||
| return "default" | ||
| } | ||
| return fmt.Sprintf("%s:%s", authContext.Profile, authContext.CredentialsFile) | ||
| } | ||
|
|
||
| // getAWSCallerIdentityCached retrieves the AWS caller identity with caching. | ||
| // Results are cached per auth context to avoid repeated STS calls within the same CLI invocation. | ||
| func getAWSCallerIdentityCached( | ||
| ctx context.Context, | ||
| atmosConfig *schema.AtmosConfiguration, | ||
| authContext *schema.AWSAuthContext, | ||
| ) (*AWSCallerIdentity, error) { | ||
| defer perf.Track(atmosConfig, "exec.getAWSCallerIdentityCached")() | ||
|
|
||
| cacheKey := getCacheKey(authContext) | ||
|
|
||
| // Check cache first (read lock). | ||
| awsIdentityCacheMu.RLock() | ||
| if cached, ok := awsIdentityCache[cacheKey]; ok { | ||
| awsIdentityCacheMu.RUnlock() | ||
| log.Debug("Using cached AWS caller identity", "cache_key", cacheKey) | ||
| return cached.identity, cached.err | ||
| } | ||
| awsIdentityCacheMu.RUnlock() | ||
|
|
||
| // Cache miss - acquire write lock and fetch. | ||
| awsIdentityCacheMu.Lock() | ||
| defer awsIdentityCacheMu.Unlock() | ||
|
|
||
| // Double-check after acquiring write lock. | ||
| if cached, ok := awsIdentityCache[cacheKey]; ok { | ||
| log.Debug("Using cached AWS caller identity (double-check)", "cache_key", cacheKey) | ||
| return cached.identity, cached.err | ||
| } | ||
|
|
||
| // Fetch from AWS. | ||
| identity, err := awsGetter.GetCallerIdentity(ctx, atmosConfig, authContext) | ||
|
|
||
| // Cache the result (including errors to avoid repeated failed calls). | ||
| awsIdentityCache[cacheKey] = &cachedAWSIdentity{ | ||
| identity: identity, | ||
| err: err, | ||
| } | ||
|
|
||
| return identity, err | ||
| } | ||
|
|
||
| // ClearAWSIdentityCache clears the AWS identity cache. | ||
| // This is useful in tests or when credentials change during execution. | ||
| func ClearAWSIdentityCache() { | ||
| defer perf.Track(nil, "exec.ClearAWSIdentityCache")() | ||
|
|
||
| awsIdentityCacheMu.Lock() | ||
| defer awsIdentityCacheMu.Unlock() | ||
| awsIdentityCache = make(map[string]*cachedAWSIdentity) | ||
| } | ||
This file contains hidden or 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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,151 @@ | ||
| package exec | ||
|
|
||
| import ( | ||
| "context" | ||
|
|
||
| errUtils "github.com/cloudposse/atmos/errors" | ||
| log "github.com/cloudposse/atmos/pkg/logger" | ||
| "github.com/cloudposse/atmos/pkg/perf" | ||
| "github.com/cloudposse/atmos/pkg/schema" | ||
| u "github.com/cloudposse/atmos/pkg/utils" | ||
| ) | ||
|
|
||
| const ( | ||
| execAWSYAMLFunction = "Executing Atmos YAML function" | ||
| invalidYAMLFunction = "Invalid YAML function" | ||
| failedGetIdentity = "Failed to get AWS caller identity" | ||
| functionKey = "function" | ||
| ) | ||
|
|
||
| // processTagAwsValue is a shared helper for AWS YAML functions. | ||
| // It validates the input tag, retrieves AWS caller identity, and returns the requested value. | ||
| func processTagAwsValue( | ||
| atmosConfig *schema.AtmosConfiguration, | ||
| input string, | ||
| expectedTag string, | ||
| stackInfo *schema.ConfigAndStacksInfo, | ||
| extractor func(*AWSCallerIdentity) string, | ||
| ) any { | ||
| log.Debug(execAWSYAMLFunction, functionKey, input) | ||
|
|
||
| // Validate the tag matches expected. | ||
| if input != expectedTag { | ||
| log.Error(invalidYAMLFunction, functionKey, input, "expected", expectedTag) | ||
| errUtils.CheckErrorPrintAndExit(errUtils.ErrYamlFuncInvalidArguments, "", "") | ||
| return nil | ||
| } | ||
|
|
||
| // Get auth context from stack info if available. | ||
| var authContext *schema.AWSAuthContext | ||
| if stackInfo != nil && stackInfo.AuthContext != nil && stackInfo.AuthContext.AWS != nil { | ||
| authContext = stackInfo.AuthContext.AWS | ||
| } | ||
|
|
||
| // Get the AWS caller identity (cached). | ||
| ctx := context.Background() | ||
| identity, err := getAWSCallerIdentityCached(ctx, atmosConfig, authContext) | ||
| if err != nil { | ||
| log.Error(failedGetIdentity, "error", err) | ||
| errUtils.CheckErrorPrintAndExit(err, "", "") | ||
| return nil | ||
| } | ||
|
|
||
| // Extract the requested value. | ||
| return extractor(identity) | ||
| } | ||
|
|
||
| // processTagAwsAccountID processes the !aws.account_id YAML function. | ||
| // It returns the AWS account ID of the current caller identity. | ||
| // The function takes no parameters. | ||
| // | ||
| // Usage in YAML: | ||
| // | ||
| // account_id: !aws.account_id | ||
| func processTagAwsAccountID( | ||
| atmosConfig *schema.AtmosConfiguration, | ||
| input string, | ||
| stackInfo *schema.ConfigAndStacksInfo, | ||
| ) any { | ||
| defer perf.Track(atmosConfig, "exec.processTagAwsAccountID")() | ||
|
|
||
| result := processTagAwsValue(atmosConfig, input, u.AtmosYamlFuncAwsAccountID, stackInfo, func(id *AWSCallerIdentity) string { | ||
| return id.Account | ||
| }) | ||
|
|
||
| if result != nil { | ||
| log.Debug("Resolved !aws.account_id", "account_id", result) | ||
| } | ||
| return result | ||
| } | ||
|
|
||
| // processTagAwsCallerIdentityArn processes the !aws.caller_identity_arn YAML function. | ||
| // It returns the ARN of the current AWS caller identity. | ||
| // The function takes no parameters. | ||
| // | ||
| // Usage in YAML: | ||
| // | ||
| // caller_arn: !aws.caller_identity_arn | ||
| func processTagAwsCallerIdentityArn( | ||
| atmosConfig *schema.AtmosConfiguration, | ||
| input string, | ||
| stackInfo *schema.ConfigAndStacksInfo, | ||
| ) any { | ||
| defer perf.Track(atmosConfig, "exec.processTagAwsCallerIdentityArn")() | ||
|
|
||
| result := processTagAwsValue(atmosConfig, input, u.AtmosYamlFuncAwsCallerIdentityArn, stackInfo, func(id *AWSCallerIdentity) string { | ||
| return id.Arn | ||
| }) | ||
|
|
||
| if result != nil { | ||
| log.Debug("Resolved !aws.caller_identity_arn", "arn", result) | ||
| } | ||
| return result | ||
| } | ||
|
|
||
| // processTagAwsCallerIdentityUserID processes the !aws.caller_identity_user_id YAML function. | ||
| // It returns the unique user ID of the current AWS caller identity. | ||
| // The function takes no parameters. | ||
| // | ||
| // Usage in YAML: | ||
| // | ||
| // user_id: !aws.caller_identity_user_id | ||
| func processTagAwsCallerIdentityUserID( | ||
| atmosConfig *schema.AtmosConfiguration, | ||
| input string, | ||
| stackInfo *schema.ConfigAndStacksInfo, | ||
| ) any { | ||
| defer perf.Track(atmosConfig, "exec.processTagAwsCallerIdentityUserID")() | ||
|
|
||
| result := processTagAwsValue(atmosConfig, input, u.AtmosYamlFuncAwsCallerIdentityUserID, stackInfo, func(id *AWSCallerIdentity) string { | ||
| return id.UserID | ||
| }) | ||
|
|
||
| if result != nil { | ||
| log.Debug("Resolved !aws.caller_identity_user_id", "user_id", result) | ||
| } | ||
| return result | ||
| } | ||
|
|
||
| // processTagAwsRegion processes the !aws.region YAML function. | ||
| // It returns the AWS region from the current configuration. | ||
| // The function takes no parameters. | ||
| // | ||
| // Usage in YAML: | ||
| // | ||
| // region: !aws.region | ||
| func processTagAwsRegion( | ||
| atmosConfig *schema.AtmosConfiguration, | ||
| input string, | ||
| stackInfo *schema.ConfigAndStacksInfo, | ||
| ) any { | ||
| defer perf.Track(atmosConfig, "exec.processTagAwsRegion")() | ||
|
|
||
| result := processTagAwsValue(atmosConfig, input, u.AtmosYamlFuncAwsRegion, stackInfo, func(id *AWSCallerIdentity) string { | ||
| return id.Region | ||
| }) | ||
|
|
||
| if result != nil { | ||
| log.Debug("Resolved !aws.region", "region", result) | ||
| } | ||
| return result | ||
| } |
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
🧩 Analysis chain
🏁 Script executed:
Repository: cloudposse/atmos
Length of output: 1228
🏁 Script executed:
cat -n internal/exec/aws_getter.go | head -150Repository: cloudposse/atmos
Length of output: 5752
🏁 Script executed:
Repository: cloudposse/atmos
Length of output: 93
🏁 Script executed:
cat -n internal/aws_utils/aws_utils.go | head -200Repository: cloudposse/atmos
Length of output: 6823
Add ConfigFile to cache key generation.
The cache key only uses
ProfileandCredentialsFile, butConfigFileis also used during AWS credential loading (passed toconfig.WithSharedConfigFiles()). DifferentConfigFilevalues can result in different AWS configurations and may affect identity resolution. UpdategetCacheKey()to includeConfigFilein the cache key to ensure different configurations don't incorrectly share cache entries.Additionally, consider whether
Regionshould be included, as it's used during config loading when not explicitly provided (line 82-83 inaws_utils.go).🤖 Prompt for AI Agents