Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Terraform escape sequence

Tags:

terraform

I am running some commands on my ec2 using remote-exec provisioner in my terraform file. But I am stuck at escaping special characters in a command. This code portion is from my main.tf file inside remote-exec provisioner portion. The error coming in terraform is "Invalid character" and "Invalid multi-line string". I wanted correct string sequence, so that these commands can execute on my ec2.

"VAR=$(cat contents.txt | grep '"token"'),
"VAR="${VAR:11}"",
"VAR="${VAR:0:-1}"",
like image 235
Pratik das baghel Avatar asked Jun 11 '26 22:06

Pratik das baghel


1 Answers

The ${ are also interpreted by terraform (as variable substitutions). You need to escape those with $ to become $${.

A full working example:

main.tf:

resource "null_resource" "test" {
  provisioner "local-exec" {
    command = <<EOF
echo 'some11char hello "token"' > contents.txt

VAR=$(cat contents.txt | grep \"token\")
VAR=$${VAR:11}
VAR=$${VAR:0:5}

echo $VAR >log
    EOF
  }
}
$ terraform apply -input=false -auto-approve 
null_resource.test: Creating...
null_resource.test: Provisioning with 'local-exec'...
null_resource.test (local-exec): Executing: ["/bin/sh" "-c" "echo 'some11char hello \"token\"' > contents.txt\n\nVAR=$(cat contents.txt | grep \\\"token\\\")\nVAR=${VAR:11}\nVAR=${VAR:0:5}\n\necho $VAR >log\n"]
null_resource.test: Creation complete after 0s [id=3425651808766026549]

Apply complete! Resources: 1 added, 0 changed, 0 destroyed.
$ cat contents.txt 
some11char hello "token"

$ cat log     
hello

$
like image 152
smaftoul Avatar answered Jun 17 '26 10:06

smaftoul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!