How to Escape Single Quote in Terraform – Solutions and Tips

terraform

I am trying to escape a single quote in my string:

${join("\n",formatlist("%s ansible_host=%s ansible_ssh_common_args='-o ProxyCommand=\"ssh -W %%h:%%p -q cloud-user@%s\"'","${module.compute.ops_master_names}","${module.compute.ops_master_priv_ips}","${module.ips.bastion_fips[0]}"))}"

I have tried with different combinations (\' or \\' or '' or ' ), but I received an illegal char escape or it doesn't print the single quote. my need is print the line

ansible_ssh_common_args='-o ProxyCommand="ssh -W %h:%p -q cloud-user@%s"'

the double quote and percentage character are well interpreted

Best Answer

No escaping is necessary, the following works for me:

locals {
  test = ["foo", "bar"]
}

output "test" {
  value = "${formatlist("ansible_ssh_common_args='-o ProxyCommand=\"ssh -W %%h:%%p -q cloud-user@%s\"'", local.test)}"
}

Returns:

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

test = [
    ansible_ssh_common_args='-o ProxyCommand="ssh -W %h:%p -q cloud-user@foo"',
    ansible_ssh_common_args='-o ProxyCommand="ssh -W %h:%p -q cloud-user@bar"'
]

Using a template_file also works:

locals {
  test = ["foo", "bar"]
}

data "template_file" "inventory" {
  template = <<-EOT
    $${test}
  EOT

  vars {
    test = "${join("\n", formatlist("ansible_ssh_common_args='-o ProxyCommand=\"ssh -W %%h:%%p -q cloud-user@%s\"'", local.test))}"
  }
}

output "test" {
  value = "${data.template_file.inventory.rendered}"
}

Returns:

Apply complete! Resources: 0 added, 0 changed, 0 destroyed.

Outputs:

test =   ansible_ssh_common_args='-o ProxyCommand="ssh -W %h:%p -q cloud-user@foo"'
ansible_ssh_common_args='-o ProxyCommand="ssh -W %h:%p -q cloud-user@bar"'

Single quotes are still present.

This is with Terraform 0.11.6.