Skip to content
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

increment ATMOS_SHLVL each time atmos terraform shell is called #803

Merged
merged 10 commits into from
Dec 5, 2024
35 changes: 35 additions & 0 deletions internal/exec/shell_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"text/template"

Expand Down Expand Up @@ -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))
Expand Down
4 changes: 4 additions & 0 deletions website/docs/cli/commands/terraform/terraform-shell.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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
:::
Expand Down
Loading