How to write interpolated string
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.
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("\""),
},
})
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"},
})