Skip to content

Commit

Permalink
Escape shell vars in HCL output
Browse files Browse the repository at this point in the history
  • Loading branch information
jrhouston committed Aug 28, 2021
1 parent 314c799 commit 6157243
Show file tree
Hide file tree
Showing 4 changed files with 46 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
# 0.1.7

- Escape shell vars in HCL output

# 0.1.6

- Fix crash when trying to use List resources
Expand Down
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
@@ -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:
Expand Down
7 changes: 7 additions & 0 deletions tfk8s.go
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand Down Expand Up @@ -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)
Expand Down
34 changes: 34 additions & 0 deletions tfk8s_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 6157243

Please sign in to comment.