From 8c5e9caa6b11974d804920b83d8a69a58135e2cd Mon Sep 17 00:00:00 2001 From: David Schmitt Date: Mon, 18 Nov 2024 21:26:33 +0100 Subject: [PATCH] Ensure that only valid args get passed to `terraform apply` Native `terraform apply` does not accept `-var` or `-var-file` args when applying a preplanned plan to avoid conflicts with the values stored in said plan. As this is the main way we are running it internally, we also make sure not to upset terraform in this case. To do so, this change introduces a `applyArgsFromApplyArgs` method to strip that stuff out before passing it into `RunApply`. --- cmd/terraform.go | 25 ++++++++++++++++++++++++- cmd/terraform_apply.go | 4 +++- 2 files changed, 27 insertions(+), 2 deletions(-) diff --git a/cmd/terraform.go b/cmd/terraform.go index 137687e8..e66444a7 100644 --- a/cmd/terraform.go +++ b/cmd/terraform.go @@ -10,7 +10,7 @@ import ( var terraformCmd = &cobra.Command{ Use: "terraform", GroupID: "iac", - Short: "Run Terrafrom with Overmind's risk analysis and change tracking", + Short: "Run Terraform with Overmind's risk analysis and change tracking", Long: `By using 'overmind terraform plan/apply' in place of your normal 'terraform plan/apply' commands, you can get a risk analysis and change tracking for your Terraform changes with no extra effort. @@ -36,6 +36,11 @@ var applyOnlyArgs = []string{ "auto-approve", } +var planOnlyArgs = []string{ + "var", + "var-file", +} + // planArgsFromApplyArgs filters out all apply-specific arguments from arguments // to `terraform apply`, so that we can run the corresponding `terraform plan` // command @@ -55,3 +60,21 @@ append: } return planArgs } + +// applyArgsFromApplyArgs filters out all plan-specific arguments from arguments to `terraform apply`, so that we can run the corresponding `terraform apply` command +func applyArgsFromApplyArgs(args []string) []string { + applyArgs := []string{} +append: + for _, arg := range args { + for _, planOnlyArg := range planOnlyArgs { + if strings.HasPrefix(arg, "-"+planOnlyArg) { + continue append + } + if strings.HasPrefix(arg, "--"+planOnlyArg) { + continue append + } + } + applyArgs = append(applyArgs, arg) + } + return applyArgs +} diff --git a/cmd/terraform_apply.go b/cmd/terraform_apply.go index a4bc1471..8a50251c 100644 --- a/cmd/terraform_apply.go +++ b/cmd/terraform_apply.go @@ -186,7 +186,9 @@ func TerraformApplyImpl(ctx context.Context, cmd *cobra.Command, oi sdp.Overmind return err } - err = RunApply(ctx, args) + // apply the args filtering here, after providers have been configured above + // (which might still need --var and --var-file information) + err = RunApply(ctx, applyArgsFromApplyArgs(args)) if err != nil { return err }