diff --git a/internal/exec/shell_utils.go b/internal/exec/shell_utils.go index e585e6a08..0e73da870 100644 --- a/internal/exec/shell_utils.go +++ b/internal/exec/shell_utils.go @@ -9,6 +9,7 @@ import ( "os/exec" "path/filepath" "runtime" + "strconv" "strings" "text/template" @@ -150,6 +151,40 @@ func execTerraformShellCommand( workspaceName string, componentPath string) error { + atmosShellLvl := os.Getenv("ATMOS_SHLVL") + atmosShellVal := 1 + if atmosShellLvl != "" { + val, err := strconv.Atoi(atmosShellLvl) + if err != nil { + return err + } + atmosShellVal = val + 1 + } + if err := os.Setenv("ATMOS_SHLVL", fmt.Sprintf("%d", atmosShellVal)); err != nil { + return err + } + + // decrement the value after exiting the shell + defer func() { + atmosShellLvl := os.Getenv("ATMOS_SHLVL") + if atmosShellLvl == "" { + return + } + val, err := strconv.Atoi(atmosShellLvl) + if err != nil { + u.LogWarning(cliConfig, fmt.Sprintf("Failed to parse ATMOS_SHLVL: %v", err)) + return + } + // Prevent negative values + newVal := val - 1 + if newVal < 0 { + newVal = 0 + } + if err := os.Setenv("ATMOS_SHLVL", fmt.Sprintf("%d", newVal)); err != nil { + u.LogWarning(cliConfig, fmt.Sprintf("Failed to update ATMOS_SHLVL: %v", err)) + } + }() + componentEnvList = append(componentEnvList, fmt.Sprintf("TF_CLI_ARGS_plan=-var-file=%s", varFile)) componentEnvList = append(componentEnvList, fmt.Sprintf("TF_CLI_ARGS_apply=-var-file=%s", varFile)) componentEnvList = append(componentEnvList, fmt.Sprintf("TF_CLI_ARGS_refresh=-var-file=%s", varFile)) diff --git a/website/docs/cli/commands/terraform/terraform-shell.mdx b/website/docs/cli/commands/terraform/terraform-shell.mdx index 7fe8d7609..3d8c0a646 100644 --- a/website/docs/cli/commands/terraform/terraform-shell.mdx +++ b/website/docs/cli/commands/terraform/terraform-shell.mdx @@ -39,6 +39,10 @@ The command does the following: - Inside the shell, the user can execute all `terraform` commands using the native syntax +- Atmos sets the `ATMOS_SHLVL` environment variable to track the nesting level of shells: + - If `ATMOS_SHLVL` is not already set, Atmos initializes it to `1`. + - If `ATMOS_SHLVL` is already set, Atmos increments its value by `1` for each new nested shell. + :::tip Run `atmos terraform shell --help` to see all the available options :::