Skip to content

Commit

Permalink
taint command, simplify error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
digitalkaoz committed Nov 6, 2023
1 parent 7f931a7 commit db91920
Show file tree
Hide file tree
Showing 12 changed files with 110 additions and 50 deletions.
8 changes: 5 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ download the binary matching your OS from [here](https://github.com/terrarium-tf
## Command

```
$ ./terrarium
$ terrarium
Builds Terraform Commands, easing these steps:
* collects defined var-files
* switches to the given workspace (can create new one)
Expand All @@ -55,7 +55,7 @@ Usage:
terrarium [command]
Examples:
terrarium [command] workspace path/to/stack -v -t echo
terrarium plan production path/to/stack -v
Available Commands:
apply Apply a given Terraform Stack
Expand All @@ -66,6 +66,8 @@ Available Commands:
init initializes a stack with optional remote state
plan Creates a diff between remote and local state and prints the upcoming changes
remove Removes a remote resource from the terraform state
taint Taints a given Terraform Resource from a State
untaint Untaints a given Terraform Resource from a State
Flags:
-h, --help help for terrarium
Expand Down Expand Up @@ -244,7 +246,7 @@ $ go run main.go
To build and distribute the binary:

```shell script
$ goreleaser build --snapshot --rm-dist
$ goreleaser build --snapshot --clean
$ cp ./dist/terrarium_xxx/terrarium /usr/local/bin/terrarium
$ chmod a+x /usr/local/bin/terrarium
```
14 changes: 9 additions & 5 deletions cmd/apply.go
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ func NewApplyCommand(root *cobra.Command) {
Long: `Creates a plan file (which might be uploaded to CI-Artifacts for auditing) and applies this exact plan file.`,
Args: lib.ArgsValidator,

Run: func(cmd *cobra.Command, args []string) {
RunE: func(cmd *cobra.Command, args []string) error {
tf, ctx, files, _ := lib.Executor(*cmd, args[0], args[1], true)

planFile := fmt.Sprintf("%s-%s.tfplan", strings.Replace(time.Now().Format(time.RFC3339), ":", "-", -1), args[0])
Expand All @@ -51,17 +51,21 @@ func NewApplyCommand(root *cobra.Command) {
_, err := tf.Plan(ctx, buildPlanOptions(files, args, planFile)...)

if err != nil {
os.Exit(1)
return err
}

//apply
err = tf.Apply(ctx, tfexec.DirOrPlan(planFile))
if err != nil {
os.Exit(1)
return err
}

if os.Getenv("TF_IN_AUTOMATION") == "" {
_ = os.Remove(planFile)
// if we are not in automation remove the maybe existing planfile
if _, err := os.Stat(planFile); err == nil && os.Getenv("TF_IN_AUTOMATION") == "" {
return os.Remove(planFile)
}

return nil
},
}

Expand Down
8 changes: 2 additions & 6 deletions cmd/destroy.go
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import (
"github.com/hashicorp/terraform-exec/tfexec"
"github.com/spf13/cobra"
"github.com/terrarium-tf/cli/lib"
"os"
)

func NewDestroyCommand(root *cobra.Command) {
Expand All @@ -36,13 +35,10 @@ func NewDestroyCommand(root *cobra.Command) {
Short: "Destroy a given Terraform stack",
Args: lib.ArgsValidator,

Run: func(cmd *cobra.Command, args []string) {
RunE: func(cmd *cobra.Command, args []string) error {
tf, ctx, files, _ := lib.Executor(*cmd, args[0], args[1], true)

err := tf.Destroy(ctx, buildDestroyOptions(files, args)...)
if err != nil {
os.Exit(1)
}
return tf.Destroy(ctx, buildDestroyOptions(files, args)...)
},
}

Expand Down
8 changes: 2 additions & 6 deletions cmd/import.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import (
"github.com/hashicorp/terraform-exec/tfexec"
"github.com/spf13/cobra"
"github.com/terrarium-tf/cli/lib"
"os"
)

func NewImportCommand(root *cobra.Command) {
Expand All @@ -37,13 +36,10 @@ func NewImportCommand(root *cobra.Command) {
Short: "Import a remote resource into a local terraform resource",
Example: "import prod path/to/stack aws_s3_bucket.example some_aws_bucket_name",
Args: importArgsValidator,
Run: func(cmd *cobra.Command, args []string) {
RunE: func(cmd *cobra.Command, args []string) error {
tf, ctx, files, _ := lib.Executor(*cmd, args[0], args[1], true)

err := tf.Import(ctx, args[2], args[3], buildImportOptions(files, args)...)
if err != nil {
os.Exit(1)
}
return tf.Import(ctx, args[2], args[3], buildImportOptions(files, args)...)
},
}

Expand Down
8 changes: 2 additions & 6 deletions cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,14 +57,10 @@ These variables can be defined by your *.tfvars.json or through command options
`,
Example: "init workspace path/to/stack --state-bucket=my_own_bucket_id --state-dynamo=my_dynamo_table --state-region=us-east-1 --state-account=4711 --state-name=my_state_entry_name",
Args: lib.ArgsValidator,
Run: func(cmd *cobra.Command, args []string) {
RunE: func(cmd *cobra.Command, args []string) error {
tf, ctx, _, mergedVars := lib.Executor(*cmd, args[0], args[1], false)

//init
err := tf.Init(ctx, buildInitOptions(*cmd, mergedVars, args)...)
if err != nil {
os.Exit(1)
}
return tf.Init(ctx, buildInitOptions(*cmd, mergedVars, args)...)
},
}

Expand Down
9 changes: 4 additions & 5 deletions cmd/plan.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ func NewPlanCommand(root *cobra.Command) {
Short: "Creates a diff between remote and local state and prints the upcoming changes",
Args: lib.ArgsValidator,

Run: func(cmd *cobra.Command, args []string) {
RunE: func(cmd *cobra.Command, args []string) error {
tf, ctx, files, _ := lib.Executor(*cmd, args[0], args[1], true)

//plan
Expand All @@ -47,19 +47,18 @@ func NewPlanCommand(root *cobra.Command) {
}

diff, err := tf.Plan(ctx, buildPlanOptions(files, args, planFile)...)

// behave exactly like terraform:
/*
0 = Succeeded with empty diff (no changes)
1 = Error
2 = Succeeded with non-empty diff (changes present)
*/
if err != nil {
os.Exit(1)
}

if diff {
os.Exit(2)
}

return err
},
}

Expand Down
8 changes: 2 additions & 6 deletions cmd/remove.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import (
"errors"
"github.com/spf13/cobra"
"github.com/terrarium-tf/cli/lib"
"os"
)

func NewRemoveCommand(root *cobra.Command) {
Expand All @@ -35,13 +34,10 @@ func NewRemoveCommand(root *cobra.Command) {
Short: "Removes a remote resource from the terraform state",
Example: "remove prod path/to/stack aws_s3_bucket.example",
Args: removeArgsValidator,
Run: func(cmd *cobra.Command, args []string) {
RunE: func(cmd *cobra.Command, args []string) error {
tf, ctx, _, _ := lib.Executor(*cmd, args[0], args[1], true)

err := tf.StateRm(ctx, args[2])
if err != nil {
os.Exit(1)
}
return tf.StateRm(ctx, args[2])
},
}

Expand Down
1 change: 1 addition & 0 deletions cmd/root.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,4 +67,5 @@ func AddChildCommands(rootCmd *cobra.Command) {
NewPlanCommand(rootCmd)
NewRemoveCommand(rootCmd)
NewUntaintCommand(rootCmd)
NewTaintCommand(rootCmd)
}
15 changes: 13 additions & 2 deletions cmd/root_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,17 @@ func TestInitCommandAzure(t *testing.T) {
}
}

func TestTaintCommand(t *testing.T) {
t.Skip("test not yet fully working due to terrafrom version checks")
args := []string{"taint", "dev", "../example/stack", "-t", "echo", "aws_s3_bucket.test"}
out := runCommand(t, args)
t.Log(out)

if !strings.Contains(out, "taint aws_s3_bucket.test") {
t.Errorf("invalid taint command")
}
}

func TestApplyCommand(t *testing.T) {
args := []string{"apply", "dev", "../example/stack", "-t", "echo"}
now := strings.Replace(time.Now().Format(time.RFC3339), ":", "-", -1)
Expand All @@ -124,7 +135,7 @@ func TestApplyCommand(t *testing.T) {
t.Errorf("invalid plan command")
}
if !strings.Contains(out, fmt.Sprintf("apply -auto-approve -input=false -lock=true -parallelism=10 -refresh=true %s/%s-dev.tfplan", root, now)) {
t.Errorf("invalid apply command")
t.Errorf("invalid apply command: %s", out)
}
}

Expand Down Expand Up @@ -215,7 +226,7 @@ func TestRemoveCommandWithVerbose(t *testing.T) {
}

func TestUntaintCommand(t *testing.T) {
t.Skip("test not yet fully working")
t.Skip("test not yet fully working due to terrafrom version checks")
args := []string{"untaint", "dev", "../example/stack", "-t", "echo", "aws_s3_bucket.test"}
out := runCommand(t, args)
t.Log(out)
Expand Down
53 changes: 53 additions & 0 deletions cmd/taint.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
// Package cmd
/*
Copyright © 2022 Robert Schönthal <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package cmd

import (
"errors"
"github.com/spf13/cobra"
"github.com/terrarium-tf/cli/lib"
)

func NewTaintCommand(root *cobra.Command) {
var untaintCmd = &cobra.Command{
Use: "taint workspace path/to/stack tf_resource",
Short: "Taints a given Terraform Resource from a State",
Args: taintArgsValidator,

RunE: func(cmd *cobra.Command, args []string) error {
tf, ctx, _, _ := lib.Executor(*cmd, args[0], args[1], true)

return tf.Taint(ctx, args[2])
},
}

root.AddCommand(untaintCmd)
}

func taintArgsValidator(cmd *cobra.Command, args []string) error {
if len(args) < 3 {
return errors.New("requires a workspace,a stack path and a tf resource")
}

return lib.ArgsValidator(cmd, args)
}
8 changes: 2 additions & 6 deletions cmd/untaint.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import (
"errors"
"github.com/spf13/cobra"
"github.com/terrarium-tf/cli/lib"
"os"
)

func NewUntaintCommand(root *cobra.Command) {
Expand All @@ -35,13 +34,10 @@ func NewUntaintCommand(root *cobra.Command) {
Short: "Untaints a given Terraform Resource from a State",
Args: untaintArgsValidator,

Run: func(cmd *cobra.Command, args []string) {
RunE: func(cmd *cobra.Command, args []string) error {
tf, ctx, _, _ := lib.Executor(*cmd, args[0], args[1], true)

err := tf.Untaint(ctx, args[2])
if err != nil {
os.Exit(1)
}
return tf.Untaint(ctx, args[2])
},
}

Expand Down
20 changes: 15 additions & 5 deletions lib/terraform.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,14 @@ func Executor(cmd cobra.Command, workspace string, path string, switchWorkspace
binary, err := cmd.Parent().PersistentFlags().GetString("terraform")

if err != nil {
log.Fatal("cant find terraform flag", err)
cmd.PrintErr("cant find terraform flag", err)
}

tf, err := tfexec.NewTerraform(path, binary)
tf.SetColor(true)

if err != nil {
log.Fatal("cant create terraform instance", err)
cmd.PrintErr(err.Error())
}

tf.SetStdout(cmd.OutOrStdout())
Expand All @@ -55,20 +55,30 @@ func Executor(cmd cobra.Command, workspace string, path string, switchWorkspace

func Workspace(tf *tfexec.Terraform, ctx context.Context, cmd cobra.Command, name string) {
tf.SetStdout(nil)
workspaces, current, _ := tf.WorkspaceList(ctx)
workspaces, current, err := tf.WorkspaceList(ctx)
tf.SetStdout(cmd.OutOrStdout())

if err != nil {
cmd.PrintErr(err.Error())
}

exists := false
for _, ws := range workspaces {
if ws == name {
exists = true
}
}
if !exists {
_ = tf.WorkspaceNew(ctx, name)
err := tf.WorkspaceNew(ctx, name)
if err != nil {
cmd.PrintErr(err.Error())
}
}

if current != name {
_ = tf.WorkspaceSelect(ctx, name)
err := tf.WorkspaceSelect(ctx, name)
if err != nil {
cmd.PrintErr(err.Error())
}
}
}

0 comments on commit db91920

Please sign in to comment.