Skip to content

fix: restore AWS_PROFILE env var correctly when it was previously unset#1046

Merged
yxxhero merged 1 commit into
helmfile:mainfrom
jimmyR:fix/aws-profile-env-bug
Mar 11, 2026
Merged

fix: restore AWS_PROFILE env var correctly when it was previously unset#1046
yxxhero merged 1 commit into
helmfile:mainfrom
jimmyR:fix/aws-profile-env-bug

Conversation

@jimmyR

@jimmyR jimmyR commented Mar 6, 2026

Copy link
Copy Markdown
Contributor

Fix: correctly restore AWS_PROFILE when it was not previously set

Problem

When using ref+tfstates3 with aws_profile in a helmfile values file, the ReadTFState function temporarily sets AWS_PROFILE to the specified profile, then attempts to restore the previous value on exit.

The bug is in the restore logic:

v := os.Getenv("AWS_PROFILE")  // returns "" if not set
// ...
defer func() {
    _ = os.Setenv("AWS_PROFILE", v)  // sets AWS_PROFILE="" instead of unsetting it
}()

os.Getenv returns "" for both an unset variable and a variable explicitly set to an empty string. The defer always calls os.Setenv, which means after the tfstate lookup completes, AWS_PROFILE is left set to an empty string rather than being unset.

Impact

This affects environments that rely on the AWS default credential chain — such as EC2 instance profiles or Kubernetes pods with IAM roles — where AWS_PROFILE is intentionally not set. After the tfstate lookup, any subsequent AWS calls (e.g. aws eks get-token in a kubeconfig exec credential plugin) fail with:

The config profile () could not be found

Fix

Use os.LookupEnv instead of os.Getenv to distinguish between "not set" and "set to empty string", and call os.Unsetenv when the variable was not originally set:

v, wasSet := os.LookupEnv("AWS_PROFILE")
// ...
defer func() {
    if wasSet {
        _ = os.Setenv("AWS_PROFILE", v)
    } else {
        _ = os.Unsetenv("AWS_PROFILE")
    }
}()

@jimmyR jimmyR force-pushed the fix/aws-profile-env-bug branch 3 times, most recently from 606be7b to f8c1102 Compare March 6, 2026 16:28
@jimmyR jimmyR force-pushed the fix/aws-profile-env-bug branch from f8c1102 to 95b571e Compare March 6, 2026 16:29
@yxxhero yxxhero merged commit 3312699 into helmfile:main Mar 11, 2026
5 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants