2020-12-09 15:31:34 +00:00
|
|
|
package acceptance
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
2021-02-04 21:06:09 +00:00
|
|
|
"context"
|
2020-12-09 15:31:34 +00:00
|
|
|
"encoding/json"
|
|
|
|
"fmt"
|
|
|
|
"io"
|
2021-04-09 16:37:27 +00:00
|
|
|
"io/fs"
|
2020-12-09 15:31:34 +00:00
|
|
|
"io/ioutil"
|
|
|
|
"os"
|
2021-01-05 15:40:45 +00:00
|
|
|
"path"
|
2021-01-25 17:43:05 +00:00
|
|
|
"strings"
|
2020-12-09 15:31:34 +00:00
|
|
|
"testing"
|
2021-02-04 21:06:09 +00:00
|
|
|
"time"
|
2020-12-09 15:31:34 +00:00
|
|
|
|
|
|
|
"github.com/cloudskiff/driftctl/pkg/analyser"
|
2021-01-27 18:12:25 +00:00
|
|
|
cmderrors "github.com/cloudskiff/driftctl/pkg/cmd/errors"
|
2020-12-14 09:49:12 +00:00
|
|
|
"github.com/pkg/errors"
|
2020-12-09 15:31:34 +00:00
|
|
|
|
|
|
|
"github.com/sirupsen/logrus"
|
|
|
|
|
|
|
|
"github.com/cloudskiff/driftctl/test"
|
|
|
|
|
|
|
|
"github.com/spf13/cobra"
|
|
|
|
|
|
|
|
"github.com/cloudskiff/driftctl/logger"
|
|
|
|
"github.com/cloudskiff/driftctl/pkg/cmd"
|
2021-02-05 12:19:10 +00:00
|
|
|
|
|
|
|
"github.com/hashicorp/terraform-exec/tfexec"
|
|
|
|
"github.com/hashicorp/terraform-exec/tfinstall"
|
2020-12-09 15:31:34 +00:00
|
|
|
)
|
|
|
|
|
|
|
|
type AccCheck struct {
|
|
|
|
PreExec func()
|
|
|
|
PostExec func()
|
2021-01-07 16:53:17 +00:00
|
|
|
Env map[string]string
|
2021-03-30 15:50:13 +00:00
|
|
|
Args func() []string
|
2021-03-31 14:33:25 +00:00
|
|
|
Check func(result *test.ScanResult, stdout string, err error)
|
2020-12-09 15:31:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
type AccTestCase struct {
|
2021-04-09 16:37:27 +00:00
|
|
|
TerraformVersion string
|
2021-02-23 12:44:48 +00:00
|
|
|
Paths []string
|
2021-02-17 14:33:08 +00:00
|
|
|
Args []string
|
|
|
|
OnStart func()
|
|
|
|
OnEnd func()
|
|
|
|
Checks []AccCheck
|
|
|
|
tmpResultFilePath string
|
|
|
|
originalEnv []string
|
2021-02-23 12:44:48 +00:00
|
|
|
tf map[string]*tfexec.Terraform
|
2021-02-17 14:33:08 +00:00
|
|
|
ShouldRefreshBeforeDestroy bool
|
2021-02-05 12:19:10 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *AccTestCase) initTerraformExecutor() error {
|
2021-04-09 16:37:27 +00:00
|
|
|
installPath := path.Join(os.TempDir(), "terraform-bin", c.TerraformVersion)
|
|
|
|
binPath := path.Join(installPath, "terraform")
|
|
|
|
execPathFinderOptions := make([]tfinstall.ExecPathFinder, 0)
|
|
|
|
|
|
|
|
err := os.MkdirAll(installPath, fs.ModePerm)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
_, err = os.Stat(binPath)
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
execPathFinderOptions = append(execPathFinderOptions, tfinstall.ExactVersion(c.TerraformVersion, installPath))
|
|
|
|
} else {
|
|
|
|
execPathFinderOptions = append(execPathFinderOptions, tfinstall.ExactPath(binPath))
|
|
|
|
}
|
|
|
|
|
|
|
|
execPath, err := tfinstall.Find(context.Background(), execPathFinderOptions...)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
2021-02-23 12:44:48 +00:00
|
|
|
c.tf = make(map[string]*tfexec.Terraform, 1)
|
2021-04-09 16:37:27 +00:00
|
|
|
for _, p := range c.Paths {
|
|
|
|
c.tf[p], err = tfexec.NewTerraform(p, execPath)
|
2021-02-23 12:44:48 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
env := c.resolveTerraformEnv()
|
2021-04-09 16:37:27 +00:00
|
|
|
if err := c.tf[p].SetEnv(env); err != nil {
|
2021-02-23 12:44:48 +00:00
|
|
|
return err
|
|
|
|
}
|
2021-02-05 12:19:10 +00:00
|
|
|
}
|
|
|
|
return nil
|
2020-12-09 15:31:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *AccTestCase) createResultFile(t *testing.T) error {
|
|
|
|
tmpDir := t.TempDir()
|
|
|
|
file, err := ioutil.TempFile(tmpDir, "result")
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
defer file.Close()
|
|
|
|
c.tmpResultFilePath = file.Name()
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *AccTestCase) validate() error {
|
|
|
|
if c.Checks == nil || len(c.Checks) == 0 {
|
|
|
|
return fmt.Errorf("checks attribute must be defined")
|
|
|
|
}
|
|
|
|
|
2021-02-23 12:44:48 +00:00
|
|
|
if len(c.Paths) < 1 {
|
|
|
|
return fmt.Errorf("Paths attribute must be defined")
|
2020-12-09 15:31:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, arg := range c.Args {
|
|
|
|
if arg == "--output" || arg == "-o" {
|
|
|
|
return fmt.Errorf("--output flag should not be defined in test case, it is automatically tested")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *AccTestCase) getResultFilePath() string {
|
|
|
|
return c.tmpResultFilePath
|
|
|
|
}
|
|
|
|
|
2021-03-31 14:33:25 +00:00
|
|
|
func (c *AccTestCase) getResult(t *testing.T) *test.ScanResult {
|
|
|
|
analysis := &analyser.Analysis{}
|
2020-12-09 15:31:34 +00:00
|
|
|
result, err := ioutil.ReadFile(c.getResultFilePath())
|
|
|
|
if err != nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-03-31 14:33:25 +00:00
|
|
|
if err := json.Unmarshal(result, analysis); err != nil {
|
2020-12-09 15:31:34 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-03-31 14:33:25 +00:00
|
|
|
return test.NewScanResult(t, analysis)
|
2020-12-09 15:31:34 +00:00
|
|
|
}
|
|
|
|
|
2021-01-25 17:43:05 +00:00
|
|
|
/**
|
|
|
|
* Retrieve env from os.Environ() but override every variable prefixed with ACC_
|
|
|
|
* e.g. ACC_AWS_PROFILE will override AWS_PROFILE
|
|
|
|
*/
|
2021-02-05 12:19:10 +00:00
|
|
|
func (c *AccTestCase) resolveTerraformEnv() map[string]string {
|
2021-01-25 17:43:05 +00:00
|
|
|
|
|
|
|
environMap := make(map[string]string, len(os.Environ()))
|
|
|
|
|
|
|
|
const PREFIX string = "ACC_"
|
|
|
|
|
|
|
|
for _, e := range os.Environ() {
|
|
|
|
envKeyValue := strings.SplitN(e, "=", 2)
|
|
|
|
if strings.HasPrefix(envKeyValue[0], PREFIX) {
|
|
|
|
varName := strings.TrimPrefix(envKeyValue[0], PREFIX)
|
|
|
|
environMap[varName] = envKeyValue[1]
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if _, exist := environMap[envKeyValue[0]]; !exist {
|
|
|
|
environMap[envKeyValue[0]] = envKeyValue[1]
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-05 12:19:10 +00:00
|
|
|
return environMap
|
2021-01-25 17:43:05 +00:00
|
|
|
}
|
|
|
|
|
2021-01-05 15:40:45 +00:00
|
|
|
func (c *AccTestCase) terraformInit() error {
|
2021-02-05 12:19:10 +00:00
|
|
|
if err := c.initTerraformExecutor(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2021-02-23 12:44:48 +00:00
|
|
|
for _, p := range c.Paths {
|
|
|
|
_, err := os.Stat(path.Join(p, ".terraform"))
|
|
|
|
if os.IsNotExist(err) {
|
|
|
|
logrus.WithFields(logrus.Fields{
|
|
|
|
"path": p,
|
|
|
|
}).Debug("Running terraform init ...")
|
|
|
|
stderr := new(bytes.Buffer)
|
|
|
|
c.tf[p].SetStderr(stderr)
|
|
|
|
if err := c.tf[p].Init(context.Background()); err != nil {
|
|
|
|
return errors.Wrap(err, stderr.String())
|
|
|
|
}
|
|
|
|
logrus.WithFields(logrus.Fields{
|
|
|
|
"path": p,
|
|
|
|
}).Debug("Terraform init done")
|
2021-01-05 15:40:45 +00:00
|
|
|
}
|
2020-12-09 15:31:34 +00:00
|
|
|
}
|
|
|
|
|
2021-01-05 15:40:45 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *AccTestCase) terraformApply() error {
|
2021-02-23 12:44:48 +00:00
|
|
|
for _, p := range c.Paths {
|
|
|
|
logrus.WithFields(logrus.Fields{
|
|
|
|
"p": p,
|
|
|
|
}).Debug("Running terraform apply ...")
|
|
|
|
stderr := new(bytes.Buffer)
|
|
|
|
c.tf[p].SetStderr(stderr)
|
|
|
|
if err := c.tf[p].Apply(context.Background()); err != nil {
|
|
|
|
return errors.Wrap(err, stderr.String())
|
|
|
|
}
|
|
|
|
logrus.WithFields(logrus.Fields{
|
|
|
|
"p": p,
|
|
|
|
}).Debug("Terraform apply done")
|
2020-12-09 15:31:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2021-01-05 15:40:45 +00:00
|
|
|
func (c *AccTestCase) terraformDestroy() error {
|
2021-02-17 14:33:08 +00:00
|
|
|
if c.ShouldRefreshBeforeDestroy {
|
|
|
|
if err := c.terraformRefresh(); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-23 12:44:48 +00:00
|
|
|
for _, p := range c.Paths {
|
|
|
|
logrus.WithFields(logrus.Fields{
|
|
|
|
"p": p,
|
|
|
|
}).Debug("Running terraform destroy ...")
|
|
|
|
stderr := new(bytes.Buffer)
|
|
|
|
c.tf[p].SetStderr(stderr)
|
|
|
|
if err := c.tf[p].Destroy(context.Background()); err != nil {
|
|
|
|
return errors.Wrap(err, stderr.String())
|
|
|
|
}
|
|
|
|
logrus.WithFields(logrus.Fields{
|
|
|
|
"p": p,
|
|
|
|
}).Debug("Terraform destroy done")
|
2021-01-05 15:40:45 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
2020-12-09 15:31:34 +00:00
|
|
|
}
|
|
|
|
|
2021-02-17 14:33:08 +00:00
|
|
|
func (c *AccTestCase) terraformRefresh() error {
|
2021-02-23 12:44:48 +00:00
|
|
|
for _, p := range c.Paths {
|
|
|
|
logrus.WithFields(logrus.Fields{
|
|
|
|
"p": p,
|
|
|
|
}).Debug("Running terraform refresh ...")
|
|
|
|
stderr := new(bytes.Buffer)
|
|
|
|
c.tf[p].SetStderr(stderr)
|
|
|
|
if err := c.tf[p].Refresh(context.Background()); err != nil {
|
|
|
|
return errors.Wrap(err, stderr.String())
|
|
|
|
}
|
|
|
|
logrus.WithFields(logrus.Fields{
|
|
|
|
"p": p,
|
|
|
|
}).Debug("Terraform refresh done")
|
2021-02-17 14:33:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
2020-12-09 15:31:34 +00:00
|
|
|
func runDriftCtlCmd(driftctlCmd *cmd.DriftctlCmd) (*cobra.Command, string, error) {
|
|
|
|
old := os.Stdout // keep backup of the real stdout
|
|
|
|
r, w, _ := os.Pipe()
|
|
|
|
os.Stdout = w
|
|
|
|
cmd, cmdErr := driftctlCmd.ExecuteC()
|
2021-01-27 18:12:25 +00:00
|
|
|
// Ignore not in sync errors in acceptance test context
|
|
|
|
if _, isNotInSyncErr := cmdErr.(cmderrors.InfrastructureNotInSync); isNotInSyncErr {
|
|
|
|
cmdErr = nil
|
|
|
|
}
|
2020-12-09 15:31:34 +00:00
|
|
|
outC := make(chan string)
|
|
|
|
// copy the output in a separate goroutine so printing can't block indefinitely
|
|
|
|
go func() {
|
|
|
|
var buf bytes.Buffer
|
|
|
|
_, _ = io.Copy(&buf, r)
|
|
|
|
outC <- buf.String()
|
|
|
|
}()
|
|
|
|
|
|
|
|
// back to normal state
|
|
|
|
w.Close()
|
|
|
|
os.Stdout = old // restoring the real stdout
|
|
|
|
out := <-outC
|
|
|
|
return cmd, out, cmdErr
|
|
|
|
}
|
|
|
|
|
2021-01-28 18:57:04 +00:00
|
|
|
func (c *AccTestCase) useTerraformEnv() {
|
|
|
|
c.originalEnv = os.Environ()
|
2021-02-05 12:19:10 +00:00
|
|
|
environMap := c.resolveTerraformEnv()
|
|
|
|
env := make([]string, 0, len(environMap))
|
|
|
|
for k, v := range environMap {
|
|
|
|
env = append(env, fmt.Sprintf("%s=%s", k, v))
|
|
|
|
}
|
|
|
|
c.setEnv(env)
|
2021-01-28 18:57:04 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func (c *AccTestCase) restoreEnv() {
|
|
|
|
if c.originalEnv != nil {
|
|
|
|
logrus.Debug("Restoring original environment ...")
|
|
|
|
os.Clearenv()
|
|
|
|
c.setEnv(c.originalEnv)
|
|
|
|
c.originalEnv = nil
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (c *AccTestCase) setEnv(env []string) {
|
|
|
|
os.Clearenv()
|
|
|
|
for _, e := range env {
|
|
|
|
envKeyValue := strings.SplitN(e, "=", 2)
|
|
|
|
os.Setenv(envKeyValue[0], envKeyValue[1])
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-12-09 15:31:34 +00:00
|
|
|
func Run(t *testing.T, c AccTestCase) {
|
|
|
|
|
|
|
|
if os.Getenv("DRIFTCTL_ACC") == "" {
|
|
|
|
t.Skip()
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := c.validate(); err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
if c.OnStart != nil {
|
2021-02-23 12:44:48 +00:00
|
|
|
c.useTerraformEnv()
|
2020-12-09 15:31:34 +00:00
|
|
|
c.OnStart()
|
2021-02-23 12:44:48 +00:00
|
|
|
if c.OnEnd != nil {
|
|
|
|
defer func() {
|
|
|
|
c.useTerraformEnv()
|
|
|
|
c.OnEnd()
|
|
|
|
c.restoreEnv()
|
|
|
|
}()
|
|
|
|
}
|
|
|
|
c.restoreEnv()
|
2020-12-09 15:31:34 +00:00
|
|
|
}
|
2021-01-05 15:40:45 +00:00
|
|
|
|
|
|
|
// Disable terraform version checks
|
|
|
|
// @link https://www.terraform.io/docs/commands/index.html#upgrade-and-security-bulletin-checks
|
|
|
|
checkpoint := os.Getenv("CHECKPOINT_DISABLE")
|
|
|
|
os.Setenv("CHECKPOINT_DISABLE", "true")
|
|
|
|
|
|
|
|
// Execute terraform init if .terraform folder is not found in test folder
|
|
|
|
err := c.terraformInit()
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
|
|
|
defer func() {
|
2021-01-28 18:57:04 +00:00
|
|
|
c.restoreEnv()
|
2021-01-05 15:40:45 +00:00
|
|
|
err := c.terraformDestroy()
|
|
|
|
os.Setenv("CHECKPOINT_DISABLE", checkpoint)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
}()
|
2020-12-09 15:31:34 +00:00
|
|
|
|
2021-05-21 13:31:47 +00:00
|
|
|
err = c.terraformApply()
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
|
2021-02-10 13:25:07 +00:00
|
|
|
logger.Init()
|
2020-12-09 15:31:34 +00:00
|
|
|
|
|
|
|
err = c.createResultFile(t)
|
|
|
|
if err != nil {
|
|
|
|
t.Fatal(err)
|
|
|
|
}
|
|
|
|
if c.Args != nil {
|
|
|
|
c.Args = append([]string{""}, c.Args...)
|
2021-02-23 12:44:48 +00:00
|
|
|
isFromSet := false
|
|
|
|
for _, arg := range c.Args {
|
|
|
|
if arg == "--from" || arg == "-f" {
|
|
|
|
isFromSet = true
|
|
|
|
break
|
|
|
|
}
|
|
|
|
}
|
|
|
|
if !isFromSet {
|
|
|
|
for _, p := range c.Paths {
|
|
|
|
c.Args = append(c.Args,
|
|
|
|
"--from", fmt.Sprintf("tfstate://%s", path.Join(p, "terraform.tfstate")),
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
2021-01-05 15:40:45 +00:00
|
|
|
c.Args = append(c.Args,
|
|
|
|
"--output", fmt.Sprintf("json://%s", c.getResultFilePath()),
|
|
|
|
)
|
2021-05-11 08:23:19 +00:00
|
|
|
c.Args = append(c.Args, "--disable-telemetry")
|
2020-12-09 15:31:34 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
for _, check := range c.Checks {
|
2021-02-03 18:20:21 +00:00
|
|
|
driftctlCmd := cmd.NewDriftctlCmd(test.Build{})
|
2020-12-09 15:31:34 +00:00
|
|
|
if check.Check == nil {
|
|
|
|
t.Fatal("Check attribute must be defined")
|
|
|
|
}
|
2021-01-07 16:53:17 +00:00
|
|
|
if len(check.Env) > 0 {
|
|
|
|
for key, value := range check.Env {
|
|
|
|
os.Setenv(key, value)
|
|
|
|
}
|
|
|
|
}
|
2021-02-01 09:45:10 +00:00
|
|
|
if check.PreExec != nil {
|
|
|
|
c.useTerraformEnv()
|
|
|
|
check.PreExec()
|
|
|
|
c.restoreEnv()
|
|
|
|
}
|
2021-03-30 15:50:13 +00:00
|
|
|
os.Args = c.Args
|
|
|
|
if check.Args != nil {
|
|
|
|
os.Args = append(os.Args, check.Args()...)
|
|
|
|
}
|
2020-12-09 15:31:34 +00:00
|
|
|
_, out, cmdErr := runDriftCtlCmd(driftctlCmd)
|
2021-01-07 16:53:17 +00:00
|
|
|
if len(check.Env) > 0 {
|
|
|
|
for key := range check.Env {
|
|
|
|
_ = os.Unsetenv(key)
|
|
|
|
}
|
|
|
|
}
|
2020-12-09 15:31:34 +00:00
|
|
|
check.Check(c.getResult(t), out, cmdErr)
|
|
|
|
if check.PostExec != nil {
|
|
|
|
check.PostExec()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2021-02-04 21:06:09 +00:00
|
|
|
|
|
|
|
func RetryFor(timeout time.Duration, f func(c chan struct{}) error) error {
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
|
|
|
defer cancel()
|
|
|
|
|
|
|
|
doneCh := make(chan struct{}, 1)
|
|
|
|
errCh := make(chan error, 1)
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
default:
|
|
|
|
if err := f(doneCh); err != nil {
|
|
|
|
errCh <- err
|
|
|
|
return
|
|
|
|
}
|
|
|
|
time.Sleep(1 * time.Second)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
select {
|
|
|
|
case <-doneCh:
|
|
|
|
return nil
|
|
|
|
case err := <-errCh:
|
|
|
|
return err
|
|
|
|
case <-ctx.Done():
|
|
|
|
return ctx.Err()
|
|
|
|
}
|
|
|
|
}
|