From 0ced15e4b353bd1f765a3731362f3d0e0f7e0bb1 Mon Sep 17 00:00:00 2001 From: Yoriyasu Yano <430092+yorinasub17@users.noreply.github.com> Date: Fri, 23 Jul 2021 16:44:46 -0500 Subject: [PATCH] Add helper for extracting plan struct without logging and without specifying a plan file --- modules/terraform/plan.go | 19 +++++++++++++++++++ modules/terraform/plan_test.go | 16 ++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/modules/terraform/plan.go b/modules/terraform/plan.go index 0a1892fa0..a804ab563 100644 --- a/modules/terraform/plan.go +++ b/modules/terraform/plan.go @@ -2,7 +2,10 @@ package terraform import ( "fmt" + "io/ioutil" + "os" + "github.com/gruntwork-io/terratest/modules/logger" "github.com/gruntwork-io/terratest/modules/testing" "github.com/stretchr/testify/require" ) @@ -59,6 +62,22 @@ func InitAndPlanAndShowE(t testing.TestingT, options *Options) (string, error) { return ShowE(t, options) } +// InitAndPlanAndShowWithStructNoLog runs InitAndPlanAndShowWithStruct without logging and also by allocating a +// temporary plan file destination that is discarded before returning the struct. +func InitAndPlanAndShowWithStructNoLogTempPlanFile(t testing.TestingT, options *Options) *PlanStruct { + oldLogger := options.Logger + options.Logger = logger.Discard + defer func() { options.Logger = oldLogger }() + + tmpFile, err := ioutil.TempFile("", "terratest-plan-file-") + require.NoError(t, err) + require.NoError(t, tmpFile.Close()) + defer require.NoError(t, os.Remove(tmpFile.Name())) + + options.PlanFilePath = tmpFile.Name() + return InitAndPlanAndShowWithStruct(t, options) +} + // InitAndPlanAndShowWithStruct runs terraform init, then terraform plan, and then terraform show with the given // options, and parses the json result into a go struct. This will fail the test if there is an error in the command. func InitAndPlanAndShowWithStruct(t testing.TestingT, options *Options) *PlanStruct { diff --git a/modules/terraform/plan_test.go b/modules/terraform/plan_test.go index 54a5078e0..dc838415f 100644 --- a/modules/terraform/plan_test.go +++ b/modules/terraform/plan_test.go @@ -84,6 +84,22 @@ func TestInitAndPlanWithPlanFile(t *testing.T) { assert.FileExists(t, planFilePath, "Plan file was not saved to expected location:", planFilePath) } +func TestInitAndPlanAndShowWithStructNoLogTempPlanFile(t *testing.T) { + t.Parallel() + + testFolder, err := files.CopyTerraformFolderToTemp("../../test/fixtures/terraform-basic-configuration", t.Name()) + require.NoError(t, err) + + options := &Options{ + TerraformDir: testFolder, + Vars: map[string]interface{}{ + "cnt": 1, + }, + } + planStruct := InitAndPlanAndShowWithStructNoLogTempPlanFile(t, options) + assert.Equal(t, 1, len(planStruct.ResourceChangesMap)) +} + func TestPlanWithExitCodeWithNoChanges(t *testing.T) { t.Parallel() testFolder, err := files.CopyTerraformFolderToTemp("../../test/fixtures/terraform-no-error", t.Name())