Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use terraform for plan analyzing #107

Merged
merged 2 commits into from
Apr 23, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 11 additions & 0 deletions pkg/commands/executor_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,11 @@ package commands

import (
"encoding/json"
"errors"
"fmt"
"github.com/conplementag/cops-hq/v2/internal/testing_utils"
"github.com/conplementag/cops-hq/v2/pkg/logging"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/suite"
"io"
"os"
Expand Down Expand Up @@ -87,6 +89,15 @@ func (s *ExecutorTestSuite) Test_CollectsBothStdErrAndStdOutOnError() {
s.Contains(err.Error(), "This is standard error")
}

func (s *ExecutorTestSuite) Test_ErrorHasExitErrorWrapped() {
_, err := s.exec.Execute("bash -c \"exit 5\"")

var exitErr *exec.ExitError
errors.As(err, &exitErr)

assert.Equal(s.T(), 5, exitErr.ExitCode())
}

func (s *ExecutorTestSuite) Test_Integration_ParsingComplexTypeFromCommandsIsPossible() {
// the two methods here can be further optimized in the future if we have more integrations tests, for example
// by having a list of conditions passed to a single CheckIntegrationTestPrerequisites method?
Expand Down
10 changes: 1 addition & 9 deletions pkg/recipes/terraform/additional_files.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package terraform

import (
"github.com/conplementag/cops-hq/v2/pkg/recipes/terraform/plan_analyzer"
"os"
"path/filepath"
)
Expand Down Expand Up @@ -47,19 +46,12 @@ func (tf *terraformWrapper) persistPlanInAdditionalFormatsOnDisk(planAsPlaintext
}

// persistAnalysisResultOnDisk - we also run the plan analyzer and persist the result as a file, in case plan contains no changes.
func (tf *terraformWrapper) persistAnalysisResultOnDisk(terraformRelativePlanFilePath string, isDestroy bool) error {
func (tf *terraformWrapper) persistAnalysisResultOnDisk(terraformRelativePlanFilePath string, isDestroy bool, isPlanDirty bool) error {
if isDestroy {
// we do not create analyze files for destroy - there are always changes expected
return nil
}

analyzer := plan_analyzer.New(tf.projectName, tf.terraformDirectory)

isPlanDirty, err := analyzer.IsDeployPlanDirty()
if err != nil {
return err
}

if !isPlanDirty {
// we need to convert the terraformRelativePlanFilePath to a path resolvable from where we are running at the
//moment (e.g. cmd/example-cli).
Expand Down
79 changes: 0 additions & 79 deletions pkg/recipes/terraform/plan_analyzer/plan_analyzer.go

This file was deleted.

34 changes: 31 additions & 3 deletions pkg/recipes/terraform/terraform.go
Original file line number Diff line number Diff line change
Expand Up @@ -406,7 +406,8 @@ func (tf *terraformWrapper) plan(isDestroy bool) (string, error) {
tfCommand := "terraform" +
" -chdir=" + tf.terraformDirectory +
" plan -input=false " +
" -var-file=" + tf.GetVariablesFileName()
" -var-file=" + tf.GetVariablesFileName() +
" -detailed-exitcode"

var localTerraformRelativePlanFilePath string

Expand Down Expand Up @@ -436,16 +437,30 @@ func (tf *terraformWrapper) plan(isDestroy bool) (string, error) {
}

plaintextPlanOutput, err := tf.executor.Execute(tfCommand)
if err != nil {
// terraform plan with -detailed-exitcode results in the following exit codes
// 0 = Succeeded with empty diff (no changes)
// 1 = Error
// 2 = Succeeded with non-empty diff (changes present)
var planIsDirty bool
switch exitCode := getExitCode(err); exitCode {
case 0:
planIsDirty = false
break
case 1:
return "", internal.ReturnErrorOrPanic(err)
case 2:
planIsDirty = true
break
default:
return "", internal.ReturnErrorOrPanic(fmt.Errorf("unexpected exit code %d in terraform plan command %w", exitCode, err))
}

err = tf.persistPlanInAdditionalFormatsOnDisk(plaintextPlanOutput, localTerraformRelativePlanFilePath)
if err != nil {
return "", internal.ReturnErrorOrPanic(err)
}

err = tf.persistAnalysisResultOnDisk(localTerraformRelativePlanFilePath, isDestroy)
err = tf.persistAnalysisResultOnDisk(localTerraformRelativePlanFilePath, isDestroy, planIsDirty)
if err != nil {
return "", internal.ReturnErrorOrPanic(err)
}
Expand Down Expand Up @@ -567,3 +582,16 @@ func (tf *terraformWrapper) forceApply(isDestroy bool) error {
func trimLinebreakSuffixes(storageAccountKey string) string {
return strings.TrimRight(storageAccountKey, "\r\n")
}

func getExitCode(err error) int {
if err == nil {
return 0
}

var exitErr *exec.ExitError
if errors.As(err, &exitErr) {
return exitErr.ExitCode()
}

return 1
}
5 changes: 3 additions & 2 deletions pkg/recipes/terraform/terraform_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
"os"
"os/exec"
"path/filepath"
"strings"
"testing"
Expand Down Expand Up @@ -263,9 +264,9 @@ func (e *executorMock) Execute(command string) (string, error) {
e.Called(command)
}

if strings.Contains(command, "plan") {
if strings.Contains(command, " plan ") {
if e.planHasChanges {
return "Terraform will perform the following actions ... To perform exactly these actions, run the following command to apply", nil
return "Terraform will perform the following actions ... To perform exactly these actions, run the following command to apply", exec.Command("bash", "-c", "exit 2").Run()
} else {
return "Your infrastructure matches the configuration. ... found no differences, so no changes are needed", nil
}
Expand Down
Loading