hcl icon indicating copy to clipboard operation
hcl copied to clipboard

How to write interpolated string

Open AndreasBergmeier6176 opened this issue 5 years ago • 2 comments

Currently I write string values as: body.SetAttributeValue("name", cty.StringVal(name))

Now I want to support writing interpolations. So if name contains ${var.foo}, I would like attribute to bename = "${var.foo}". Sadly it seems like SetAttributeValue is always escaping the interpolation as name = "$${var.foo}". I tried

body.SetAttributeRaw("name", hclwrite.Tokens{
		&hclwrite.Token{
			Type:  hclsyntax.TokenApostrophe,
			Bytes: []byte(name),
		},
	})

but lose the quoting then. I have not yet figured out how to write a unescaped interpolated string. Maybe someone could give me a hint.

~~Looking at the source code, it seems like there is no single test case for producing $$ :(~~ Versioning threw me off. Found the tests.

AndreasBergmeier6176 avatar Jan 06 '21 08:01 AndreasBergmeier6176

Got this hacked as:

	body.SetAttributeRaw("name", hclwrite.Tokens{
		&hclwrite.Token{
			Type:  hclsyntax.TokenCQuote,
			Bytes: []byte(" \""),
		},
		&hclwrite.Token{
			Type:  hclsyntax.TokenStringLit,
			Bytes: []byte(name),
		},
		&hclwrite.Token{
			Type:  hclsyntax.TokenCQuote,
			Bytes: []byte("\""),
		},
	})

AndreasBergmeier6176 avatar Jan 06 '21 16:01 AndreasBergmeier6176

Hey @AndreasBergmeier6176 !

You can use

hclwrite.Tokens{
    {Type: hclsyntax.TokenOQuote, Bytes: []byte(`"`)},
    {Type: hclsyntax.TokenTemplateInterp, Bytes: []byte(`${`)},
    {Type: hclsyntax.TokenIdent, Bytes: []byte(`var.name`)},
    {Type: hclsyntax.TokenTemplateSeqEnd, Bytes: []byte(`}`)},
    {Type: hclsyntax.TokenCQuote, Bytes: []byte(`"`)},
}
sgBody.SetAttributeRaw("name", token)

its only a little bit less verbose than your approach

Or, I think that you can use in this way

sgBody.SetAttributeTraversal("name", hcl.Traversal{
    hcl.TraverseRoot{Name: "var"},
    hcl.TraverseAttr{Name: "name"},
})

fabiano-amaral avatar Dec 26 '21 20:12 fabiano-amaral