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

add terraform clean --everything and terraform clean --force to delete terraform.tfstate.d folder #727

Merged
merged 86 commits into from
Dec 5, 2024
Merged
Show file tree
Hide file tree
Changes from 84 commits
Commits
Show all changes
86 commits
Select commit Hold shift + click to select a range
10f8570
add terraform clean delete terraform.tfstate.d folder if the `--ever…
haitham911 Oct 15, 2024
594be52
add comment
haitham911 Oct 15, 2024
aaf17de
Merge branch 'main' into DEV-346
aknysh Oct 16, 2024
61136f4
Refactor processArgsAndFlags function to handle additional options wi…
haitham911 Oct 17, 2024
447105b
Refactor path_utils.go and add new functions for finding folders with…
haitham911 Oct 17, 2024
014dd09
add --everything provide additional options for the 'atmos terraform …
haitham911 Oct 17, 2024
ff42d22
Refactor path_utils.go to improve folder search and deletion function…
haitham911 Oct 17, 2024
23b320a
add comment to function
haitham911 Oct 17, 2024
36e946d
Merge branch 'main' into DEV-346
haitham911 Oct 17, 2024
e290655
Refactor processArgsAndFlags function to handle options and component…
haitham911 Oct 17, 2024
5713f90
Refactor help.go to improve 'atmos terraform clean' command documenta…
haitham911 Oct 17, 2024
5749a47
use filepath ensure cross-platform compatibility
haitham911 Oct 17, 2024
5985dcb
findFoldersNamesWithPrefix function to clarify search levels
haitham911 Oct 17, 2024
10a097c
Refactor ExecuteTerraform function to use descriptive variable names …
haitham911 Oct 17, 2024
9dda130
Refactor ExecuteTerraform function to use descriptive variable names …
haitham911 Oct 17, 2024
fd16997
Refactor processArgsAndFlags function to handle additional arguments …
haitham911 Oct 17, 2024
34e7b6f
Merge branch 'main' into DEV-346
osterman Oct 20, 2024
bcdbbc5
Refactor help.go to clarify Terraform state file deletion and add for…
haitham911 Oct 23, 2024
2fd446b
Refactor deleteFilesAndFoldersRecursive function to improve error han…
haitham911 Oct 23, 2024
c08a46a
rename file bubble_msg.go
haitham911 Oct 23, 2024
0610b30
use log package for deletion logging
haitham911 Oct 23, 2024
57953db
Refactor deleteFilesAndFoldersRecursive function to improve error han…
haitham911 Oct 24, 2024
33a6a07
Refactor bubble_msg.go to improve confirmation dialog state handling
haitham911 Oct 24, 2024
2843529
Refactor Confirm function to handle confirmation dialog state and mod…
haitham911 Oct 24, 2024
47ca61c
Refactor bubble_msg.go to improve confirmation dialog state handling …
haitham911 Oct 24, 2024
b14b1e9
command with --everything or --force flags
haitham911 Oct 24, 2024
4944db7
remove comment
haitham911 Oct 24, 2024
760c725
Refactor error handling in ExecuteTerraform function
haitham911 Oct 24, 2024
5a67dee
Refactor error handling in findFoldersNamesWithPrefix function
haitham911 Oct 24, 2024
f56b15d
Refactor help.go to improve 'atmos terraform clean' command documenta…
haitham911 Oct 24, 2024
beee637
Refactor error handling in findFoldersNamesWithPrefix and ExecuteTerr…
haitham911 Oct 24, 2024
76943f1
Refactor confirm delete msg
haitham911 Oct 24, 2024
9a3eca0
log waring with no confirm msg
haitham911 Oct 24, 2024
a7b57c2
Refactor error handling in findFoldersNamesWithPrefix function
haitham911 Oct 24, 2024
893b725
Refactor clean command to improve Terraform state file deletion
haitham911 Oct 24, 2024
0fc70e1
Refactor clean command to improve Terraform state file deletion
haitham911 Oct 24, 2024
3d57f25
confirm msg color
haitham911 Oct 25, 2024
2045cce
add log clean all components
haitham911 Oct 25, 2024
4ff0fa9
check file exist before delete
haitham911 Oct 25, 2024
3d0fd44
use filepath pkg
haitham911 Oct 25, 2024
b5042eb
modify log
haitham911 Oct 25, 2024
2c30fd3
use DeletePathTerraform utility
haitham911 Oct 25, 2024
5378abd
Refactor clean subcommand to handle terraform component cleanup
haitham911 Oct 27, 2024
c24eac9
Refactor clean subcommand to use filepath package for path manipulation
haitham911 Oct 27, 2024
1c8a4b9
Refactor clean empty dir
haitham911 Oct 27, 2024
483c19e
remove print line for debug
haitham911 Oct 27, 2024
fa94d4f
Refactor clean subcommand to handle relative path correctly
haitham911 Oct 27, 2024
32d01f6
Refactor clean subcommand to handle relative path correctly
haitham911 Oct 27, 2024
21e92d8
Refactor help message for 'atmos terraform clean' command
haitham911 Oct 28, 2024
130560b
Refactor clean subcommand
haitham911 Oct 28, 2024
0350c8a
Refactor clean subcommand to use u.PrintMessage instead of u.LogInfo …
haitham911 Oct 28, 2024
5b54e15
Refactor clean TF_DATA_DIR with everything
haitham911 Oct 28, 2024
a87b585
Refactor handleTFDataDir to handle relative path correctly
haitham911 Oct 28, 2024
bb688a3
Merge branch 'main' into DEV-346
aknysh Oct 29, 2024
be055a8
Refactor error messages for invalid TF_DATA_DIR and missing stack
haitham911 Oct 30, 2024
3e65888
Update internal/exec/terraform_clean.go
osterman Oct 30, 2024
3274fbc
Refactor handleCleanSubCommand to improve deletion messaging and stre…
haitham911 Oct 31, 2024
ee133a6
Calculate total objects to delete by counting files in folders
haitham911 Oct 31, 2024
5153cea
Merge branch 'main' into DEV-346
haitham911 Oct 31, 2024
bb63396
Update dependencies in go.mod and go.sum to include new packages
haitham911 Oct 31, 2024
dc5934b
Merge branch 'main' into DEV-346
haitham911 Nov 2, 2024
fbaa62a
update dependencies: upgrade lipgloss to v1.0.0 and x/ansi to v0.4.2;
haitham911 Nov 2, 2024
9155801
Merge branch 'main' into DEV-346
aknysh Nov 6, 2024
9390f77
Merge branch 'main' into DEV-346
haitham911 Nov 13, 2024
55b89c5
chore: update charmbracelet/x dependencies in go.mod
haitham911 Nov 13, 2024
30e8b05
fix: remove duplicate help message for clean operation in help.go
haitham911 Nov 14, 2024
1fcf12d
Merge branch 'main' into DEV-346
osterman Nov 14, 2024
d5cdb29
feat: enhance terraform clean command with --everything and --force o…
haitham911 Nov 14, 2024
f774bfe
Update website/docs/cli/commands/terraform/terraform-clean.mdx
osterman Nov 14, 2024
e2b4e96
Update website/docs/cli/commands/terraform/terraform-clean.mdx
osterman Nov 14, 2024
4759e13
Update website/docs/cli/commands/terraform/usage.mdx
osterman Nov 14, 2024
345fb38
Update website/docs/cli/commands/terraform/usage.mdx
osterman Nov 14, 2024
9d9ee69
Update website/docs/cli/commands/terraform/usage.mdx
osterman Nov 14, 2024
1ad31a6
Update website/docs/cli/commands/terraform/usage.mdx
osterman Nov 14, 2024
fad5e6d
Refactor error handling in handleCleanSubCommand for TF_DATA_DIR vali…
haitham911 Nov 15, 2024
191c444
Merge branch 'main' into DEV-346
osterman Nov 17, 2024
cee4ffc
fix: correct typo in documentation
haitham911 Nov 17, 2024
59940ce
fix html doc
haitham911 Nov 17, 2024
870ce20
fix: validate that the base path exists in CollectDirectoryObjects
haitham911 Nov 18, 2024
cbecdcf
fix: pass cliConfig to findFoldersNamesWithPrefix and getStackTerrafo…
haitham911 Nov 19, 2024
813e9eb
fix: enhance DeletePathTerraform to handle symbolic links and improve…
haitham911 Nov 21, 2024
f452447
fix: improve error handling in deleteFolders function for better dele…
haitham911 Nov 24, 2024
149f4c9
Merge branch 'main' into DEV-346
haitham911 Nov 24, 2024
5e0c92f
fix: streamline error handling in deleteFolders function for improved…
haitham911 Nov 24, 2024
5564dc0
Merge branch 'main' into DEV-346
osterman Dec 4, 2024
d7cfbbf
Merge branch 'main' into DEV-346
aknysh Dec 5, 2024
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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.3
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
osterman marked this conversation as resolved.
Show resolved Hide resolved
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.3 h1:d9MdMsANIYZB5pE1KkRqaUV6GfsiWm+/9z4
github.com/charmbracelet/bubbletea v1.2.3/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" +
haitham911 marked this conversation as resolved.
Show resolved Hide resolved
"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")

haitham911 marked this conversation as resolved.
Show resolved Hide resolved
} 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
haitham911 marked this conversation as resolved.
Show resolved Hide resolved
// Skip stack processing when cleaning with --everything or --force flags to allow
// cleaning without requiring stack configuration
haitham911 marked this conversation as resolved.
Show resolved Hide resolved
if info.SubCommand == "clean" &&
(u.SliceContainsString(info.AdditionalArgsAndFlags, everythingFlag) ||
u.SliceContainsString(info.AdditionalArgsAndFlags, forceFlag)) {
if info.ComponentFromArg == "" {
shouldProcessStacks = false
}

shouldCheckStack = info.Stack != ""

haitham911 marked this conversation as resolved.
Show resolved Hide resolved
}

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
aknysh marked this conversation as resolved.
Show resolved Hide resolved
}

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