Skip to content

Commit

Permalink
add terraform clean --everything and terraform clean --force to d…
Browse files Browse the repository at this point in the history
…elete `terraform.tfstate.d` folder (#727)

* add terraform clean  delete terraform.tfstate.d folder if the `--everything` flag is provided.

* add comment

* Refactor processArgsAndFlags function to handle additional options with "--"

* Refactor path_utils.go and add new functions for finding folders with a prefix and deleting files and folders recursively

* add --everything provide additional options for the 'atmos terraform clean' command

* Refactor path_utils.go to improve folder search and deletion functionality

* add comment to function

* Refactor processArgsAndFlags function to handle options and components separately

* Refactor help.go to improve 'atmos terraform clean' command documentation

* use filepath ensure cross-platform compatibility

* findFoldersNamesWithPrefix function to clarify search levels

* Refactor ExecuteTerraform function to use descriptive variable names for files to clear

* Refactor ExecuteTerraform function to use descriptive variable names for files and clarify boolean flags

* Refactor processArgsAndFlags function to handle additional arguments and flags correctly

* Refactor help.go to clarify Terraform state file deletion and add force option

* Refactor deleteFilesAndFoldersRecursive function to improve error handling and logging

* rename file bubble_msg.go

* use log package for deletion logging

* Refactor deleteFilesAndFoldersRecursive function to improve error handling and logging

* Refactor bubble_msg.go to improve confirmation dialog state handling

* Refactor Confirm function to handle confirmation dialog state and model type

* Refactor bubble_msg.go to improve confirmation dialog state handling and add navigation instructions

* command with --everything or --force flags

* remove comment

* Refactor error handling in ExecuteTerraform function

* Refactor error handling in findFoldersNamesWithPrefix function

* Refactor help.go to improve 'atmos terraform clean' command documentation

* Refactor error handling in findFoldersNamesWithPrefix and ExecuteTerraform functions

* Refactor confirm delete msg

* log waring with no confirm msg

* Refactor error handling in findFoldersNamesWithPrefix function

* Refactor clean command to improve Terraform state file deletion

* Refactor clean command to improve Terraform state file deletion

* confirm msg color

* add log clean all components

* check file exist before delete

* use filepath pkg

* modify log

* use DeletePathTerraform utility

* Refactor clean subcommand to handle terraform component cleanup

* Refactor clean subcommand to use filepath package for path manipulation

* Refactor clean empty dir

* remove print line for debug

* Refactor clean subcommand to handle relative path correctly

* Refactor clean subcommand to handle relative path correctly

* Refactor help message for 'atmos terraform clean' command

* Refactor clean subcommand

* Refactor clean subcommand to use u.PrintMessage instead of u.LogInfo for displaying messages

* Refactor clean TF_DATA_DIR with everything

* Refactor handleTFDataDir to handle relative path correctly

* Refactor error messages for invalid TF_DATA_DIR and missing stack

* Update internal/exec/terraform_clean.go

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Refactor handleCleanSubCommand to improve deletion messaging and streamline TF_DATA_DIR handling

* Calculate total objects to delete by counting files in folders

* Update dependencies in go.mod and go.sum to include new packages

* update dependencies: upgrade lipgloss to v1.0.0 and x/ansi to v0.4.2;

* chore: update charmbracelet/x dependencies in go.mod

* fix: remove duplicate help message for clean operation in help.go

* feat: enhance terraform clean command with --everything and --force options; improve argument validation

* Update website/docs/cli/commands/terraform/terraform-clean.mdx

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update website/docs/cli/commands/terraform/terraform-clean.mdx

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update website/docs/cli/commands/terraform/usage.mdx

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update website/docs/cli/commands/terraform/usage.mdx

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update website/docs/cli/commands/terraform/usage.mdx

* Update website/docs/cli/commands/terraform/usage.mdx

* Refactor error handling in handleCleanSubCommand for TF_DATA_DIR validation

* fix: correct typo in documentation

* fix html doc

* fix: validate that the base path exists in CollectDirectoryObjects

* fix: pass cliConfig to findFoldersNamesWithPrefix and getStackTerraformStateFolder functions

* fix: enhance DeletePathTerraform to handle symbolic links and improve error messages

* fix: improve error handling in deleteFolders function for better deletion feedback

* fix: streamline error handling in deleteFolders function for improved feedback

---------

Co-authored-by: Andriy Knysh <[email protected]>
Co-authored-by: Erik Osterman (CEO @ Cloud Posse) <[email protected]>
Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
  • Loading branch information
4 people authored Dec 5, 2024
1 parent 39389a2 commit 382de94
Show file tree
Hide file tree
Showing 11 changed files with 607 additions and 73 deletions.
5 changes: 5 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ require (
github.com/charmbracelet/bubbles v0.20.0
github.com/charmbracelet/bubbletea v1.2.4
github.com/charmbracelet/glamour v0.8.0
github.com/charmbracelet/huh v0.6.0
github.com/charmbracelet/lipgloss v1.0.0
github.com/elewis787/boa v0.1.2
github.com/fatih/color v1.18.0
Expand Down Expand Up @@ -92,10 +93,12 @@ require (
github.com/beorn7/perks v1.0.1 // indirect
github.com/bgentry/go-netrc v0.0.0-20140422174119-9fd32a8b3d3d // indirect
github.com/bytecodealliance/wasmtime-go/v3 v3.0.2 // indirect
github.com/catppuccin/go v0.2.0 // indirect
github.com/cenkalti/backoff/v3 v3.2.2 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/chainguard-dev/git-urls v1.0.2 // indirect
github.com/charmbracelet/x/ansi v0.4.5 // indirect
github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 // indirect
github.com/charmbracelet/x/term v0.2.1 // indirect
github.com/cloudflare/circl v1.3.7 // indirect
github.com/common-nighthawk/go-figure v0.0.0-20210622060536-734e95fb86be // indirect
Expand All @@ -111,6 +114,7 @@ require (
github.com/docker/distribution v2.8.2+incompatible // indirect
github.com/docker/docker-credential-helpers v0.7.0 // indirect
github.com/docker/libkv v0.2.2-0.20180912205406-458977154600 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/dustin/gojson v0.0.0-20160307161227-2e71ec9dd5ad // indirect
github.com/emirpasic/gods v1.18.1 // indirect
github.com/erikgeiser/coninput v0.0.0-20211004153227-1c3628e74d0f // indirect
Expand Down Expand Up @@ -176,6 +180,7 @@ require (
github.com/microcosm-cc/bluemonday v1.0.27 // indirect
github.com/mitchellh/copystructure v1.2.0 // indirect
github.com/mitchellh/go-testing-interface v1.14.1 // indirect
github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect
github.com/mitchellh/reflectwalk v1.0.2 // indirect
github.com/moby/locker v1.0.1 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
Expand Down
10 changes: 10 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -240,6 +240,8 @@ github.com/BurntSushi/toml v1.2.1/go.mod h1:CxXYINrC8qIiEnFrOxCa7Jy5BFHlXnUU2pbi
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
github.com/DataDog/datadog-go v3.2.0+incompatible/go.mod h1:LButxg5PwREeZtORoXG3tL4fMGNddJ+vMq1mwgfaqoQ=
github.com/GoogleCloudPlatform/cloudsql-proxy v1.29.0/go.mod h1:spvB9eLJH9dutlbPSRmHvSXXHOwGRyeXh1jVdquA2G8=
github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ4pzQ=
github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE=
github.com/Masterminds/goutils v1.1.1 h1:5nUrii3FMTL5diU80unEVvNevw1nH4+ZV4DSLVJLSYI=
github.com/Masterminds/goutils v1.1.1/go.mod h1:8cTjp+g8YejhMuvIA5y2vz3BpJxksy863GQaJW2MFNU=
github.com/Masterminds/semver/v3 v3.1.1/go.mod h1:VPu/7SZ7ePZ3QOrcuXROw5FAcLl4a0cBrbBpGY/8hQs=
Expand Down Expand Up @@ -379,6 +381,8 @@ github.com/bmatcuk/doublestar/v4 v4.7.1 h1:fdDeAqgT47acgwd9bd9HxJRDmc9UAmPpc+2m0
github.com/bmatcuk/doublestar/v4 v4.7.1/go.mod h1:xBQ8jztBU6kakFMg+8WGxn0c6z1fTSPVIjEY1Wr7jzc=
github.com/bytecodealliance/wasmtime-go/v3 v3.0.2 h1:3uZCA/BLTIu+DqCfguByNMJa2HVHpXvjfy0Dy7g6fuA=
github.com/bytecodealliance/wasmtime-go/v3 v3.0.2/go.mod h1:RnUjnIXxEJcL6BgCvNyzCCRzZcxCgsZCi+RNlvYor5Q=
github.com/catppuccin/go v0.2.0 h1:ktBeIrIP42b/8FGiScP9sgrWOss3lw0Z5SktRoithGA=
github.com/catppuccin/go v0.2.0/go.mod h1:8IHJuMGaUUjQM82qBrGNBv7LFq6JI3NnQCF6MOlZjpc=
github.com/cenkalti/backoff/v3 v3.0.0/go.mod h1:cIeZDE3IrqwwJl6VUwCN6trj1oXrTS4rc0ij+ULvLYs=
github.com/cenkalti/backoff/v3 v3.2.2 h1:cfUAAO3yvKMYKPrvhDuHSwQnhZNk/RMHKdZqKTxfm6M=
github.com/cenkalti/backoff/v3 v3.2.2/go.mod h1:cIeZDE3IrqwwJl6VUwCN6trj1oXrTS4rc0ij+ULvLYs=
Expand All @@ -399,12 +403,16 @@ github.com/charmbracelet/bubbletea v1.2.4 h1:KN8aCViA0eps9SCOThb2/XPIlea3ANJLUkv
github.com/charmbracelet/bubbletea v1.2.4/go.mod h1:Qr6fVQw+wX7JkWWkVyXYk/ZUQ92a6XNekLXa3rR18MM=
github.com/charmbracelet/glamour v0.8.0 h1:tPrjL3aRcQbn++7t18wOpgLyl8wrOHUEDS7IZ68QtZs=
github.com/charmbracelet/glamour v0.8.0/go.mod h1:ViRgmKkf3u5S7uakt2czJ272WSg2ZenlYEZXT2x7Bjw=
github.com/charmbracelet/huh v0.6.0 h1:mZM8VvZGuE0hoDXq6XLxRtgfWyTI3b2jZNKh0xWmax8=
github.com/charmbracelet/huh v0.6.0/go.mod h1:GGNKeWCeNzKpEOh/OJD8WBwTQjV3prFAtQPpLv+AVwU=
github.com/charmbracelet/lipgloss v1.0.0 h1:O7VkGDvqEdGi93X+DeqsQ7PKHDgtQfF8j8/O2qFMQNg=
github.com/charmbracelet/lipgloss v1.0.0/go.mod h1:U5fy9Z+C38obMs+T+tJqst9VGzlOYGj4ri9reL3qUlo=
github.com/charmbracelet/x/ansi v0.4.5 h1:LqK4vwBNaXw2AyGIICa5/29Sbdq58GbGdFngSexTdRM=
github.com/charmbracelet/x/ansi v0.4.5/go.mod h1:dk73KoMTT5AX5BsX0KrqhsTqAnhZZoCBjs7dGWp4Ktw=
github.com/charmbracelet/x/exp/golden v0.0.0-20240815200342-61de596daa2b h1:MnAMdlwSltxJyULnrYbkZpp4k58Co7Tah3ciKhSNo0Q=
github.com/charmbracelet/x/exp/golden v0.0.0-20240815200342-61de596daa2b/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=
github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0 h1:qko3AQ4gK1MTS/de7F5hPGx6/k1u0w4TeYmBFwzYVP4=
github.com/charmbracelet/x/exp/strings v0.0.0-20240722160745-212f7b056ed0/go.mod h1:pBhA0ybfXv6hDjQUZ7hk1lVxBiUbupdw5R31yPUViVQ=
github.com/charmbracelet/x/term v0.2.1 h1:AQeHeLZ1OqSXhrAWpYUtZyX1T3zVxfpZuEQMIQaGIAQ=
github.com/charmbracelet/x/term v0.2.1/go.mod h1:oQ4enTYFV7QN4m0i9mzHrViD7TQKvNEEkHUMCmsxdUg=
github.com/cheggaaa/pb v1.0.27/go.mod h1:pQciLPpbU0oxA0h+VJYYLxO+XeDQb5pZijXscXHm81s=
Expand Down Expand Up @@ -987,6 +995,8 @@ github.com/mitchellh/go-testing-interface v1.0.0/go.mod h1:kRemZodwjscx+RGhAo8eI
github.com/mitchellh/go-testing-interface v1.14.1 h1:jrgshOhYAUVNMAJiKbEu7EqAwgJJ2JqpQmpLJOu07cU=
github.com/mitchellh/go-testing-interface v1.14.1/go.mod h1:gfgS7OtZj6MA4U1UrDRp04twqAjfvlZyCfX3sDjEym8=
github.com/mitchellh/go-wordwrap v1.0.0/go.mod h1:ZXFpozHsX6DPmq2I0TCekCxypsnAUbP2oI0UX1GXzOo=
github.com/mitchellh/hashstructure/v2 v2.0.2 h1:vGKWl0YJqUNxE8d+h8f6NJLcCJrgbhC4NcD46KavDd4=
github.com/mitchellh/hashstructure/v2 v2.0.2/go.mod h1:MG3aRVU/N29oo/V/IhBX8GR/zz4kQkprJgF2EVszyDE=
github.com/mitchellh/go-wordwrap v1.0.1 h1:TLuKupo69TCn6TQSyGxwI1EblZZEsQ0vMlAFQflz0v0=
github.com/mitchellh/go-wordwrap v1.0.1/go.mod h1:R62XHJLzvMFRBbcrT7m7WgmE1eOyTSsCt+hzestvNj0=
github.com/mitchellh/mapstructure v0.0.0-20160808181253-ca63d7c062ee/go.mod h1:FVVH3fgwuzCH5S8UJGiWEs2h04kUh9fWfEaFds41c1Y=
Expand Down
20 changes: 16 additions & 4 deletions internal/exec/help.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,13 @@ func processHelp(
u.PrintMessage(" - 'atmos terraform apply' and 'atmos terraform deploy' commands commands support '--planfile' flag to specify the path " +
"to a planfile. The '--planfile' flag should be used instead of the planfile argument in the native 'terraform apply <planfile>' command")
u.PrintMessage(" - 'atmos terraform clean' command deletes the '.terraform' folder, '.terraform.lock.hcl' lock file, " +
"and the previously generated 'planfile', 'varfile' and 'backend.tf.json' file for the specified component and stack. " +
"Use --skip-lock-file flag to skip deleting the lock file.")
"and the previously generated 'planfile', 'varfile', and 'backend.tf.json' file for the specified component and stack. " +
"Use the --everything flag to also delete the Terraform state files and directories for the component. " +
"Note: State files store the local state of your infrastructure and should be handled with care, if not using a remote backend.\n\n" +
"Additional flags:\n" +
" --force Forcefully delete Terraform state files and directories without interaction\n" +
" --skip-lock-file Skip deleting the '.terraform.lock.hcl' file\n\n" +
"If no component or stack is specified, the clean operation will apply globally to all components.")
u.PrintMessage(" - 'atmos terraform workspace' command first runs 'terraform init -reconfigure', then 'terraform workspace select', " +
"and if the workspace was not created before, it then runs 'terraform workspace new'")
u.PrintMessage(" - 'atmos terraform import' command searches for 'region' in the variables for the specified component and stack, " +
Expand Down Expand Up @@ -71,10 +76,17 @@ func processHelp(
" - '.terraform.lock.hcl' file\n" +
" - generated varfile for the component in the stack\n" +
" - generated planfile for the component in the stack\n" +
" - generated 'backend.tf.json' file\n\n" +
" - generated 'backend.tf.json' file\n" +
" - 'terraform.tfstate.d' folder (if '--everything' flag is used)\n\n" +
"Usage: atmos terraform clean <component> -s <stack> <flags>\n\n" +
"Use '--skip-lock-file' flag to skip deleting the lock file.\n\n" +
"Use '--everything' flag to also delete the Terraform state files and and directories with confirm message.\n\n" +
"Use --force to forcefully delete Terraform state files and directories for the component.\n\n" +
"- If no component is specified, the command will apply to all components and stacks.\n" +
"- If no stack is specified, the command will apply to all stacks for the specified component.\n" +
"Use '--skip-lock-file' flag to skip deleting the '.terraform.lock.hcl' file.\n\n" +
"If no component or stack is specified, the clean operation will apply globally to all components.\n\n" +
"For more details refer to https://atmos.tools/cli/commands/terraform/clean\n")

} else if componentType == "terraform" && command == "deploy" {
u.PrintMessage("\n'atmos terraform deploy' command executes 'terraform apply -auto-approve' on an Atmos component in an Atmos stack.\n\n" +
"Usage: atmos terraform deploy <component> -s <stack> <flags>\n\n" +
Expand Down
12 changes: 6 additions & 6 deletions internal/exec/path_utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,14 @@ package exec

import (
"fmt"
"path"
"path/filepath"

"github.com/cloudposse/atmos/pkg/schema"
)

// constructTerraformComponentWorkingDir constructs the working dir for a terraform component in a stack
func constructTerraformComponentWorkingDir(cliConfig schema.CliConfiguration, info schema.ConfigAndStacksInfo) string {
return path.Join(
return filepath.Join(
cliConfig.BasePath,
cliConfig.Components.Terraform.BasePath,
info.ComponentFolderPrefix,
Expand Down Expand Up @@ -43,23 +43,23 @@ func constructTerraformComponentVarfileName(info schema.ConfigAndStacksInfo) str

// constructTerraformComponentVarfilePath constructs the varfile path for a terraform component in a stack
func constructTerraformComponentVarfilePath(Config schema.CliConfiguration, info schema.ConfigAndStacksInfo) string {
return path.Join(
return filepath.Join(
constructTerraformComponentWorkingDir(Config, info),
constructTerraformComponentVarfileName(info),
)
}

// constructTerraformComponentPlanfilePath constructs the planfile path for a terraform component in a stack
func constructTerraformComponentPlanfilePath(cliConfig schema.CliConfiguration, info schema.ConfigAndStacksInfo) string {
return path.Join(
return filepath.Join(
constructTerraformComponentWorkingDir(cliConfig, info),
constructTerraformComponentPlanfileName(info),
)
}

// constructHelmfileComponentWorkingDir constructs the working dir for a helmfile component in a stack
func constructHelmfileComponentWorkingDir(cliConfig schema.CliConfiguration, info schema.ConfigAndStacksInfo) string {
return path.Join(
return filepath.Join(
cliConfig.BasePath,
cliConfig.Components.Helmfile.BasePath,
info.ComponentFolderPrefix,
Expand All @@ -80,7 +80,7 @@ func constructHelmfileComponentVarfileName(info schema.ConfigAndStacksInfo) stri

// constructHelmfileComponentVarfilePath constructs the varfile path for a helmfile component in a stack
func constructHelmfileComponentVarfilePath(cliConfig schema.CliConfiguration, info schema.ConfigAndStacksInfo) string {
return path.Join(
return filepath.Join(
constructHelmfileComponentWorkingDir(cliConfig, info),
constructHelmfileComponentVarfileName(info),
)
Expand Down
93 changes: 35 additions & 58 deletions internal/exec/terraform.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"fmt"
"os"
osexec "os/exec"
"path"
"path/filepath"
"strings"

"github.com/pkg/errors"
Expand All @@ -21,6 +21,8 @@ const (
outFlag = "-out"
varFileFlag = "-var-file"
skipTerraformLockFileFlag = "--skip-lock-file"
everythingFlag = "--everything"
forceFlag = "--force"
)

// ExecuteTerraformCmd parses the provided arguments and flags and executes terraform commands
Expand All @@ -29,7 +31,6 @@ func ExecuteTerraformCmd(cmd *cobra.Command, args []string, additionalArgsAndFla
if err != nil {
return err
}

return ExecuteTerraform(info)
}

Expand Down Expand Up @@ -61,13 +62,29 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error {
return nil
}

info, err = ProcessStacks(cliConfig, info, true, true)
if err != nil {
return err
shouldProcessStacks := true
shouldCheckStack := true
// Skip stack processing when cleaning with --everything or --force flags to allow
// cleaning without requiring stack configuration
if info.SubCommand == "clean" &&
(u.SliceContainsString(info.AdditionalArgsAndFlags, everythingFlag) ||
u.SliceContainsString(info.AdditionalArgsAndFlags, forceFlag)) {
if info.ComponentFromArg == "" {
shouldProcessStacks = false
}

shouldCheckStack = info.Stack != ""

}

if len(info.Stack) < 1 {
return errors.New("stack must be specified")
if shouldProcessStacks {
info, err = ProcessStacks(cliConfig, info, shouldCheckStack, true)
if err != nil {
return err
}
if len(info.Stack) < 1 && shouldCheckStack {
return errors.New("stack must be specified when not using --everything or --force flags")
}
}

if !info.ComponentIsEnabled {
Expand All @@ -79,73 +96,33 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error {
if err != nil {
return err
}

// Check if the component (or base component) exists as Terraform component
componentPath := path.Join(cliConfig.TerraformDirAbsolutePath, info.ComponentFolderPrefix, info.FinalComponent)
componentPath := filepath.Join(cliConfig.TerraformDirAbsolutePath, info.ComponentFolderPrefix, info.FinalComponent)
componentPathExists, err := u.IsDirectory(componentPath)
if err != nil || !componentPathExists {
return fmt.Errorf("'%s' points to the Terraform component '%s', but it does not exist in '%s'",
info.ComponentFromArg,
info.FinalComponent,
path.Join(cliConfig.Components.Terraform.BasePath, info.ComponentFolderPrefix),
filepath.Join(cliConfig.Components.Terraform.BasePath, info.ComponentFolderPrefix),
)
}

// Check if the component is allowed to be provisioned (`metadata.type` attribute is not set to `abstract`)
if (info.SubCommand == "plan" || info.SubCommand == "apply" || info.SubCommand == "deploy" || info.SubCommand == "workspace") && info.ComponentIsAbstract {
return fmt.Errorf("abstract component '%s' cannot be provisioned since it's explicitly prohibited from being deployed "+
"by 'metadata.type: abstract' attribute", path.Join(info.ComponentFolderPrefix, info.Component))
"by 'metadata.type: abstract' attribute", filepath.Join(info.ComponentFolderPrefix, info.Component))
}

varFile := constructTerraformComponentVarfileName(info)
planFile := constructTerraformComponentPlanfileName(info)

if info.SubCommand == "clean" {
u.LogInfo(cliConfig, "Deleting '.terraform' folder")
err = os.RemoveAll(path.Join(componentPath, ".terraform"))
err := handleCleanSubCommand(info, componentPath, cliConfig)
if err != nil {
u.LogWarning(cliConfig, err.Error())
}

if !u.SliceContainsString(info.AdditionalArgsAndFlags, skipTerraformLockFileFlag) {
u.LogInfo(cliConfig, "Deleting '.terraform.lock.hcl' file")
_ = os.Remove(path.Join(componentPath, ".terraform.lock.hcl"))
}

u.LogInfo(cliConfig, fmt.Sprintf("Deleting terraform varfile: %s", varFile))
_ = os.Remove(path.Join(componentPath, varFile))

u.LogInfo(cliConfig, fmt.Sprintf("Deleting terraform planfile: %s", planFile))
_ = os.Remove(path.Join(componentPath, planFile))

// If `auto_generate_backend_file` is `true` (we are auto-generating backend files), remove `backend.tf.json`
if cliConfig.Components.Terraform.AutoGenerateBackendFile {
u.LogInfo(cliConfig, "Deleting 'backend.tf.json' file")
_ = os.Remove(path.Join(componentPath, "backend.tf.json"))
}

tfDataDir := os.Getenv("TF_DATA_DIR")
if len(tfDataDir) > 0 && tfDataDir != "." && tfDataDir != "/" && tfDataDir != "./" {
u.PrintMessage(fmt.Sprintf("Found ENV var TF_DATA_DIR=%s", tfDataDir))
var userAnswer string
u.PrintMessage(fmt.Sprintf("Do you want to delete the folder '%s'? (only 'yes' will be accepted to approve)\n", tfDataDir))
fmt.Print("Enter a value: ")
count, err := fmt.Scanln(&userAnswer)
if count > 0 && err != nil {
return err
}
if userAnswer == "yes" {
u.PrintMessage(fmt.Sprintf("Deleting folder '%s'\n", tfDataDir))
err = os.RemoveAll(path.Join(componentPath, tfDataDir))
if err != nil {
u.LogWarning(cliConfig, err.Error())
}
}
u.LogTrace(cliConfig, fmt.Errorf("error cleaning the terraform component: %v", err).Error())
return err
}

return nil
}

varFile := constructTerraformComponentVarfileName(info)
planFile := constructTerraformComponentPlanfileName(info)
// Print component variables and write to file
// Don't process variables when executing `terraform workspace` commands
if info.SubCommand != "workspace" {
Expand Down Expand Up @@ -209,7 +186,7 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error {

// Auto-generate backend file
if cliConfig.Components.Terraform.AutoGenerateBackendFile {
backendFileName := path.Join(workingDir, "backend.tf.json")
backendFileName := filepath.Join(workingDir, "backend.tf.json")

u.LogDebug(cliConfig, "\nWriting the backend config to file:")
u.LogDebug(cliConfig, backendFileName)
Expand All @@ -229,7 +206,7 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error {

// Generate `providers_override.tf.json` file if the `providers` section is configured
if len(info.ComponentProvidersSection) > 0 {
providerOverrideFileName := path.Join(workingDir, "providers_override.tf.json")
providerOverrideFileName := filepath.Join(workingDir, "providers_override.tf.json")

u.LogDebug(cliConfig, "\nWriting the provider overrides to file:")
u.LogDebug(cliConfig, providerOverrideFileName)
Expand Down Expand Up @@ -341,7 +318,7 @@ func ExecuteTerraform(info schema.ConfigAndStacksInfo) error {
u.LogDebug(cliConfig, "Stack: "+info.StackFromArg)
} else {
u.LogDebug(cliConfig, "Stack: "+info.StackFromArg)
u.LogDebug(cliConfig, "Stack path: "+path.Join(cliConfig.BasePath, cliConfig.Stacks.BasePath, info.Stack))
u.LogDebug(cliConfig, "Stack path: "+filepath.Join(cliConfig.BasePath, cliConfig.Stacks.BasePath, info.Stack))
}

u.LogDebug(cliConfig, fmt.Sprintf("Working dir: %s", workingDir))
Expand Down
Loading

0 comments on commit 382de94

Please sign in to comment.