From 615724367dde22e4602876d2e236b2fc039ddf0a Mon Sep 17 00:00:00 2001 From: John Houston Date: Sat, 28 Aug 2021 16:57:36 -0400 Subject: [PATCH] Escape shell vars in HCL output --- CHANGELOG.md | 4 ++++ Makefile | 2 +- tfk8s.go | 7 +++++++ tfk8s_test.go | 34 ++++++++++++++++++++++++++++++++++ 4 files changed, 46 insertions(+), 1 deletion(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b406635..8ed7552 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +# 0.1.7 + +- Escape shell vars in HCL output + # 0.1.6 - Fix crash when trying to use List resources diff --git a/Makefile b/Makefile index b693d63..1a58893 100644 --- a/Makefile +++ b/Makefile @@ -1,6 +1,6 @@ .PHONY: build docker docker-push release install test clean -VERSION := 0.1.6 +VERSION := 0.1.7 DOCKER_IMAGE_NAME := jrhouston/tfk8s build: diff --git a/tfk8s.go b/tfk8s.go index 6b90112..1366d16 100644 --- a/tfk8s.go +++ b/tfk8s.go @@ -88,6 +88,12 @@ func snakify(s string) string { return strings.ToLower(re.ReplaceAllString(s, "_")) } +// escape incidences of ${} with $${} to prevent Terraform trying to interpolate them +func escapeShellVars(s string) string { + r := regexp.MustCompile(`(\${.*?})`) + return r.ReplaceAllString(s, `$$$1`) +} + // yamlToHCL converts a single YAML document Terraform HCL func yamlToHCL(doc cty.Value, providerAlias string, stripServerSide bool, mapOnly bool) (string, error) { m := doc.AsValueMap() @@ -118,6 +124,7 @@ func yamlToHCL(doc cty.Value, providerAlias string, stripServerSide bool, mapOnl doc = stripServerSideFields(doc) } s := terraform.FormatValue(doc, 0) + s = escapeShellVars(s) if mapOnly { hcl += fmt.Sprintf("%v\n", s) diff --git a/tfk8s_test.go b/tfk8s_test.go index abdaaa6..ce496fe 100644 --- a/tfk8s_test.go +++ b/tfk8s_test.go @@ -40,6 +40,40 @@ resource "kubernetes_manifest" "configmap_test" { assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(output)) } +func TestYAMLToTerraformResourcesEscapeShell(t *testing.T) { + yaml := `--- +apiVersion: v1 +kind: ConfigMap +metadata: + name: test +data: + SCRIPT: | + echo Hello, ${USER} your homedir is ${HOME}` + + r := strings.NewReader(yaml) + output, err := YAMLToTerraformResources(r, "", false, false) + + if err != nil { + t.Fatal("Converting to HCL failed:", err) + } + + expected := ` +resource "kubernetes_manifest" "configmap_test" { + manifest = { + "apiVersion" = "v1" + "data" = { + "SCRIPT" = "echo Hello, $${USER} your homedir is $${HOME}" + } + "kind" = "ConfigMap" + "metadata" = { + "name" = "test" + } + } +}` + + assert.Equal(t, strings.TrimSpace(expected), strings.TrimSpace(output)) +} + func TestYAMLToTerraformResourcesMultiple(t *testing.T) { yaml := `--- apiVersion: v1