Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to write interpolated string #442

Open
AndreasBergmeier6176 opened this issue Jan 6, 2021 · 2 comments
Open

How to write interpolated string #442

AndreasBergmeier6176 opened this issue Jan 6, 2021 · 2 comments

Comments

@AndreasBergmeier6176
Copy link

AndreasBergmeier6176 commented Jan 6, 2021

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
Copy link
Author

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("\""),
		},
	})

@fabiano-amaral
Copy link

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"},
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants