github.com/tilotech/tilores-cli@v0.28.0/cmd/destroy.go (about)

     1  package cmd
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	"github.com/tilotech/tilores-cli/internal/pkg/step"
     8  
     9  	"github.com/spf13/cobra"
    10  )
    11  
    12  // destroyCmd represents the destroy command
    13  var destroyCmd = &cobra.Command{
    14  	Use:   "destroy",
    15  	Short: "Removes " + applicationName + " from your AWS account.",
    16  	Long:  "Removes " + applicationName + " from your AWS account.",
    17  	Run: func(_ *cobra.Command, _ []string) {
    18  		err := destroyTiloRes()
    19  		cobra.CheckErr(err)
    20  	},
    21  }
    22  
    23  func init() {
    24  	rootCmd.AddCommand(destroyCmd)
    25  
    26  	destroyCmd.PersistentFlags().StringVar(&region, "region", "", "The deployments AWS region.")
    27  	_ = destroyCmd.MarkPersistentFlagRequired("region")
    28  
    29  	destroyCmd.PersistentFlags().StringVar(&profile, "profile", "", "The AWS credentials profile.")
    30  
    31  	destroyCmd.PersistentFlags().StringVar(&workspace, "workspace", "default", "The deployments workspace/environment e.g. dev, prod.")
    32  
    33  	destroyCmd.PersistentFlags().StringVar(&varFile, "var-file", "", "The path to the file that holds the values for terraform variables")
    34  }
    35  
    36  func destroyTiloRes() error {
    37  	f, err := os.CreateTemp("", "")
    38  	if err != nil {
    39  		return err
    40  	}
    41  	err = f.Close()
    42  	if err != nil {
    43  		return err
    44  	}
    45  
    46  	destroyArgs := []string{
    47  		"-var", fmt.Sprintf("profile=%s", profile),
    48  		"-var", fmt.Sprintf("region=%v", region),
    49  		"-var", fmt.Sprintf("api_file=%v", f.Name()),
    50  		"-var", fmt.Sprintf("rule_config_file=%v", f.Name()),
    51  	}
    52  	if varFile != "" {
    53  		destroyArgs = append(destroyArgs, fmt.Sprintf("-var-file=%s", varFile))
    54  	}
    55  
    56  	steps := []step.Step{
    57  		step.TerraformRequire,
    58  		step.Chdir("deployment/tilores"),
    59  		step.TerraformInitFast,
    60  		step.TerraformNewWorkspace(workspace),
    61  
    62  		// For some reason Terraform requires the variables being set during destroy.
    63  		// See: https://github.com/hashicorp/terraform/issues/23552
    64  		//
    65  		// Additionally the lambda module checks also on destroy if the files exists.
    66  		// Therefore we must provide an empty file as input.
    67  		step.TerraformDestroy(workspace, destroyArgs...),
    68  	}
    69  
    70  	return step.Execute(steps)
    71  }