Terraform is a potent tool for tech-savvy folks, allowing you to manage infrastructure as code. But, every now and then, you might run into a situation where you need to deal with special characters like $ { or % {. These little devils usually have their own meanings in Terraform – they’re used for interpolation and directives. But what if you just want them to be plain and literal? Well, good news! We’re here to walk you through the art of escaping literal characters in Terraform.
Quoted Strings: The Simple Solution
Let’s start with an easy one – quoted strings. Quoted strings are your go-to when you want to keep those special characters as they are. Wrap your text in double quotes ( ” ) and use backslashes ( \ ) to create escape sequences. For instance, if you want to use a literal $ {, simply write it as $$ {. Likewise, %% { for a literal % {. Here are some examples:
# Use $$ { for a literal $ {
variable "name" {
default = "$$ {name}"
}
# Use %% { for a literal % {
variable "age" {
default = "%% {age}"
}
# You can use other escape sequences for special characters too
variable "message" {
default = "Hello\\nWorld\\t!"
}
Heredoc Strings: For Clear and Clean Code
Another handy method is using heredoc strings. These are inspired by Unix shell languages and make multi-line strings crystal clear. They start with either << or <<- followed by a delimiter of your choice. Here’s how it works:
# Use <<EOT for heredoc string
variable "description" {
default = <<EOT
This is a multi-line
string with some literal
characters like $$ { and %% {
EOT
}
# Use <<-EOT for an indented heredoc string
resource "aws_instance" "example" {
user_data = <<-EOT
#!/bin/bash
echo Hello World > /tmp/hello.txt
echo This is an example of using $$ {var.name} and %% {var.age} in user data.
EOT
}
The difference between << and <<- is that the latter allows indentation for readability, and Terraform will trim the same number of leading spaces from all lines.
Handling Edge Cases: When Things Get Tricky
In some tricky situations, you might want to use variable names that start with $ or %. In these cases, you can’t simply write $$name or %%age. Here are some examples:
# Use quotes around variable names that start with $ or %
variable "$name" {
default = "Alice"
}
variable "%age" {
default = 25
}
output "example1" {
value = "$$ {$name}" # Alice
}
output "example2" {
value = "$$ {%age}" # 25
}
# Use quotes around template expressions that contain $ or %
data "template_file" "example3" {
template = "$${var.name} - $${var.age}"
vars = {
name = "${var.$name}"
age = "${var.%age}"
}
}
output "example3" {
value = data.template_file.example3.rendered # Alice - 25
}