diff --git a/modules/terraform/plan.go b/modules/terraform/plan.go index a804ab563..4dbf5c453 100644 --- a/modules/terraform/plan.go +++ b/modules/terraform/plan.go @@ -7,6 +7,7 @@ import ( "github.com/gruntwork-io/terratest/modules/logger" "github.com/gruntwork-io/terratest/modules/testing" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) @@ -144,6 +145,24 @@ func TgPlanAllExitCodeE(t testing.TestingT, options *Options) (int, error) { "--lock=true", "--detailed-exitcode")...) } +// AssertTgPlanAllExitCode asserts the succuess (or failure) of a terragrunt run-all plan. +// On success, terragrunt will exit 0 on a plan that has previously been applied (has state) +// and exit with 2 for plans that have never been applied when ran with `-detailed-exitcode`. +func AssertTgPlanAllExitCode(t testing.TestingT, exitCode int, assertTrue bool) { + + validExitCodes := map[int]bool{ + 0: true, + 2: true, + } + + _, hasKey := validExitCodes[exitCode] + if assertTrue { + assert.True(t, hasKey) + } else { + assert.False(t, hasKey) + } +} + // Custom errors var ( diff --git a/modules/terraform/plan_test.go b/modules/terraform/plan_test.go index dc838415f..33c627ea2 100644 --- a/modules/terraform/plan_test.go +++ b/modules/terraform/plan_test.go @@ -191,3 +191,52 @@ func TestTgPlanAllWithError(t *testing.T) { require.Equal(t, DefaultErrorExitCode, getExitCode) } + +func TestAssertTgPlanAllExitCodeNoError(t *testing.T) { + t.Parallel() + + testFolder, err := files.CopyTerragruntFolderToTemp("../../test/fixtures/terragrunt/terragrunt-multi-plan", t.Name()) + require.NoError(t, err) + + options := &Options{ + TerraformDir: testFolder, + TerraformBinary: "terragrunt", + } + + getExitCode, errExitCode := TgPlanAllExitCodeE(t, options) + if errExitCode != nil { + t.Fatal(errExitCode) + } + + // since there is no state file we expect `2` to be the success exit code + assert.Equal(t, 2, getExitCode) + AssertTgPlanAllExitCode(t, getExitCode, true) + + TgApplyAll(t, options) + + getExitCode, errExitCode = TgPlanAllExitCodeE(t, options) + if errExitCode != nil { + t.Fatal(errExitCode) + } + + // since there is a state file we expect `0` to be the success exit code + assert.Equal(t, 0, getExitCode) + AssertTgPlanAllExitCode(t, getExitCode, true) +} + +func TestAssertTgPlanAllExitCodeWithError(t *testing.T) { + t.Parallel() + + testFolder, err := files.CopyTerragruntFolderToTemp("../../test/fixtures/terragrunt/terragrunt-with-plan-error", t.Name()) + require.NoError(t, err) + + options := &Options{ + TerraformDir: testFolder, + TerraformBinary: "terragrunt", + } + + getExitCode, errExitCode := TgPlanAllExitCodeE(t, options) + require.NoError(t, errExitCode) + + AssertTgPlanAllExitCode(t, getExitCode, false) +}