pkaramol
pkaramol

Reputation: 19402

Escape chars in Terraform local exec provisioner

I want to chain Terraform and Ansible using the local-exec provisioner;

However since this requires input to Ansible from Terraform I am stuck with the following complex command:

provisioner "local-exec" {
        command = 'sleep 60; ansible-playbook -i ../ansible/inventory/ ../ansible/playbooks/site.yml --extra-vars "rancher_server_rds_endpoint="${aws_db_instance.my-server-rds.endpoint}" rancher_server_elastic_ip="${aws_eip.my-server-eip.public_ip}""'
    }

which keeps returning

illegal char

error;

any suggestion about escaping correctly?

If the ansible-playbook command was to run directly in the shell it would be:

ansible-playbook -i inventory playbooks/site.yml --extra-vars "my_server_rds_endpoint=my-server-db.d30ikkj222.us-west-1.rds.amazonaws.com rancher_server_elastic_ip=88.148.17.236"

(paths differ)

Upvotes: 4

Views: 5598

Answers (2)

Tometzky
Tometzky

Reputation: 23910

The only way I know, that will work for any special characters in variables, is to use environment, for example:

provisioner "local-exec" {
  command = join(
    " ", [
      "sleep 60;",
      "ansible-playbook -i ../ansible/inventory/",
      "../ansible/playbooks/site.yml",
      "--extra-vars",
      "rancher_server_rds_endpoint=\"$RANCHER_SERVER_RDS_ENDPOINT\"",
      "rancher_server_elastic_ip=\"$RANCHER_SERVER_ELASTIC_IP\""
    ]
  )
  environment = {
    RANCHER_SERVER_RDS_ENDPOINT = aws_db_instance.my-server-rds.endpoint
    RANCHER_SERVER_ELASTIC_IP   = aws_eip.my-server-eip.public_ip
  }
}

Upvotes: 1

techraf
techraf

Reputation: 68609

Terraform syntax states that:

Strings are in double-quotes.

So you need to replace single quotes with double ones, and then escape quotes inside, for example:

provisioner "local-exec" {
  command = "sleep 60; ansible-playbook -i ../ansible/inventory/ ../ansible/playbooks/site.yml --extra-vars \"rancher_server_rds_endpoint='${aws_db_instance.my-server-rds.endpoint}' rancher_server_elastic_ip='${aws_eip.my-server-eip.public_ip}'\""
}

Upvotes: 4

Related Questions