Skip to content

Commit

Permalink
refactor(cli): Create cloud specific TF file (#712)
Browse files Browse the repository at this point in the history
* refactor(cli): Create cloud specific TF file

Signed-off-by: Ross <[email protected]>

* fix(tests): Update aws_generation_test to look for aws.tf rather than main.tf

Signed-off-by: Ross <[email protected]>

* refactor(cli): rename cloud string var to filename

Signed-off-by: Ross <[email protected]>
  • Loading branch information
rmoles authored Feb 23, 2022
1 parent c37afbf commit 3f9e0d8
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 19 deletions.
22 changes: 15 additions & 7 deletions cli/cmd/generate.go
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ func determineOutputDirPath(location string) (string, error) {
}

// writeHclOutputPreCheck Prompt for confirmation if main.tf already exists; return true to continue
func writeHclOutputPreCheck(outputLocation string) (bool, error) {
func writeHclOutputPreCheck(outputLocation string, filename string) (bool, error) {
// If noninteractive, continue
if !cli.InteractiveMode() {
return true, nil
Expand All @@ -207,7 +207,11 @@ func writeHclOutputPreCheck(outputLocation string) (bool, error) {
return false, err
}

hclPath := filepath.FromSlash(fmt.Sprintf("%s/main.tf", outputDir))
if filename == "" {
filename = "main"
}

hclPath := filepath.FromSlash(fmt.Sprintf("%s/%s.tf", outputDir, filename))

// If the file doesn't exist, carry on
if _, err := os.Stat(hclPath); os.IsNotExist(err) {
Expand All @@ -227,7 +231,7 @@ func writeHclOutputPreCheck(outputLocation string) (bool, error) {
}

// writeHclOutput Write HCL output
func writeHclOutput(hcl string, location string) (string, error) {
func writeHclOutput(hcl string, location string, filename string) (string, error) {
// Determine write location
dirname, err := determineOutputDirPath(location)
if err != nil {
Expand All @@ -245,8 +249,12 @@ func writeHclOutput(hcl string, location string) (string, error) {
}
}

if filename == "" {
filename = "main"
}

// Create HCL file
outputLocation := filepath.FromSlash(fmt.Sprintf("%s/main.tf", dirname))
outputLocation := filepath.FromSlash(fmt.Sprintf("%s/%s.tf", dirname, filename))
err = os.WriteFile(
filepath.FromSlash(outputLocation),
[]byte(hcl),
Expand Down Expand Up @@ -329,15 +337,15 @@ func validPathExists(val interface{}) error {
}

// writeGeneratedCodeToLocation Write-out generated code to location specified
func writeGeneratedCodeToLocation(cmd *cobra.Command, hcl string) (string, string, error) {
func writeGeneratedCodeToLocation(cmd *cobra.Command, hcl string, cloud string) (string, string, error) {
//dirname, ok, location := "", false, ""
// Write-out generated code to location specified
dirname, err := cmd.Flags().GetString("output")
if err != nil {
return dirname, "", errors.Wrap(err, "failed to parse output location")
}

ok, err := writeHclOutputPreCheck(dirname)
ok, err := writeHclOutputPreCheck(dirname, cloud)
if err != nil {
return dirname, "", errors.Wrap(err, "failed to validate output location")
}
Expand All @@ -346,7 +354,7 @@ func writeGeneratedCodeToLocation(cmd *cobra.Command, hcl string) (string, strin
return dirname, "", errors.Wrap(err, "aborting to avoid overwriting existing terraform code")
}

location, err := writeHclOutput(hcl, dirname)
location, err := writeHclOutput(hcl, dirname, cloud)
if err != nil {
return dirname, location, errors.Wrap(err, "failed to write terraform code to disk")
}
Expand Down
2 changes: 1 addition & 1 deletion cli/cmd/generate_aws.go
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ This command can also be run in noninteractive mode. See help output for more de
}

// Write-out generated code to location specified
dirname, location, err := writeGeneratedCodeToLocation(cmd, hcl)
dirname, location, err := writeGeneratedCodeToLocation(cmd, hcl, "aws")
if err != nil {
return err
}
Expand Down
8 changes: 4 additions & 4 deletions cli/cmd/generate_execute.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func newTf(workingDir string, execPath string) (*tfexec.Terraform, error) {
return tf, nil
}

// Determine if terraform is installed, if that version is new enough, and if not install a new ephemeral binary of the
// LocateOrInstallTerraform Determine if terraform is installed, if that version is new enough, and if not install a new ephemeral binary of the
// correct version into tmp location
//
// forceInstall: if set always install ephemeral binary
Expand Down Expand Up @@ -187,7 +187,7 @@ func buildHumanReadablePlannedActions(workingDir string, execPath string, data [
return outputString.String()
}

// used to display the results of a plan
// DisplayTerraformPlanChanges used to display the results of a plan
//
// returns true if apply should run, false to exit
func DisplayTerraformPlanChanges(tf *tfexec.Terraform, data TfPlanChangesSummary) (bool, error) {
Expand Down Expand Up @@ -277,7 +277,7 @@ func TerraformInit(tf *tfexec.Terraform) error {
return nil
}

// Run terraform plan using the workingDir from *tfexec.Terraform
// TerraformExecPlan Run terraform plan using the workingDir from *tfexec.Terraform
//
// - Run plan
// - Get plan file details (returned)
Expand All @@ -294,7 +294,7 @@ func TerraformExecPlan(tf *tfexec.Terraform) (*TfPlanChangesSummary, error) {
return processTfPlanChangesSummary(tf)
}

// Run terraform apply using the workingDir from *tfexec.Terraform
// TerraformExecApply Run terraform apply using the workingDir from *tfexec.Terraform
//
// - Run plan
// - Get plan file details (returned)
Expand Down
14 changes: 7 additions & 7 deletions integration/aws_generation_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ func TestGenerationCustomizedOutputLocation(t *testing.T) {
assert.Contains(t, final, "Terraform code saved in")

// Get result
result, _ := ioutil.ReadFile(filepath.FromSlash(fmt.Sprintf("%s/main.tf", dir)))
result, _ := ioutil.ReadFile(filepath.FromSlash(fmt.Sprintf("%s/aws.tf", dir)))

// Create the TF directly with lwgenerate and validate same result via CLI
buildTf, _ := aws.NewTerraform(region, true, true, aws.WithAwsProfile("default")).Generate()
Expand Down Expand Up @@ -506,7 +506,7 @@ func TestGenerationAdvancedOptsUseExistingIAM(t *testing.T) {
assert.Equal(t, buildTf, tfResult)
}

// Test existing main.tf prompt
// Test existing aws.tf prompt
func TestGenerationWithExistingTerraform(t *testing.T) {
os.Setenv("LW_NOCACHE", "true")
defer os.Setenv("LW_NOCACHE", "")
Expand All @@ -520,8 +520,8 @@ func TestGenerationWithExistingTerraform(t *testing.T) {
}
defer os.RemoveAll(dir)

// Create fake main.tf
if err := os.WriteFile(filepath.FromSlash(fmt.Sprintf("%s/main.tf", dir)), []byte{}, 0644); err != nil {
// Create fake aws.tf
if err := os.WriteFile(filepath.FromSlash(fmt.Sprintf("%s/aws.tf", dir)), []byte{}, 0644); err != nil {
panic(err)
}

Expand All @@ -543,7 +543,7 @@ func TestGenerationWithExistingTerraform(t *testing.T) {
c.SendLine(dir)
expectString(c, cmd.QuestionAwsAnotherAdvancedOpt, &runError)
c.SendLine("n")
expectString(c, fmt.Sprintf("%s/main.tf already exists, overwrite?", dir), &runError)
expectString(c, fmt.Sprintf("%s/aws.tf already exists, overwrite?", dir), &runError)
c.SendLine("n")
},
"cloud",
Expand All @@ -552,7 +552,7 @@ func TestGenerationWithExistingTerraform(t *testing.T) {
)

// Ensure CLI ran correctly
data, err := os.ReadFile(fmt.Sprintf("%s/main.tf", dir))
data, err := os.ReadFile(fmt.Sprintf("%s/aws.tf", dir))
if err != nil {
panic(err)
}
Expand All @@ -571,7 +571,7 @@ func runGenerateTest(t *testing.T, conditions func(*expect.Console), args ...str
defer os.RemoveAll(dir)

runGenerationTestFromDir(t, dir, conditions, args...)
out, err := ioutil.ReadFile(filepath.FromSlash(fmt.Sprintf("%s/lacework/main.tf", dir)))
out, err := ioutil.ReadFile(filepath.FromSlash(fmt.Sprintf("%s/lacework/aws.tf", dir)))
if err != nil {
// Assume couldn't be found
return ""
Expand Down

0 comments on commit 3f9e0d8

Please sign in to comment.