Understanding Terraform Escape Sequences
In this blog post share with you another fascinating aspect of Terraform - escape sequences. I remember when I first learned about escape sequences, and the moment it all clicked was magical. So, let's get ready to dive in!
Just like in any language, escape sequences in Terraform are our way of communicating non-graphic characters or characters with special meanings. We often find them in string literals, surrounded by a backslash ().
Today, I will take you through various Terraform escape sequences, and we'll see them in action together.
Table of Content
- Newline (\n): Escape Sequences
- Tab (\t): Escape Sequences
- Double Quote ("): Escape Sequences
- Backslash (): Escape Sequences
- Dollar Sign ($): Escape Sequences
- Percent Sign (%): Escape Sequences
- Using Escape Sequences in Interpolations
- Escape Sequences in Heredoc Strings
- Conclusion
1. Newline (\n): Escape Sequences
Do you know the good old enter key that we often hit to break our paragraphs? \n does precisely that in our terraform output text. Here's an example:
1output "example" {
2
3 # Add a line break between Line 1 and Line 2
4
5 value = "Line1\nLine2"
6}
Output:
1# Line 1 and Line 2 are printed in separate line
2
3Line1
4Line2
2. Tab (\t): Escape Sequences
Remember when we were writing essays, and we needed a tab space? \t is our go-to escape sequence for that. Let's try it out:
1output "example" {
2
3 # Putting tab between Column1 and tColumn2
4 value = "Column1\tColumn2"
5}
Output:
1# There is tab in between tab1 and tab2
2Column1 Column2
3. Double Quote ("): Escape Sequences
Want to include a double quote character inside a string that's also surrounded by double quotes? We've got an escape sequence for that!
1output "example" {
2 value = "This is an \"example\" string."
3}
Output:
1# The word example is with double quoted
2
3This is an "example" string.
4. Backslash (\): Escape Sequences
And of course, if we need to include a literal backslash, we have the escape sequence \:
1# Insert black slash in a string
2
3output "example" {
4 value = "This is a \\ backslash."
5}
Output:
1# Here is the string containing the backslash
2
3This is a \ backslash.
5. Dollar Sign ($): Escape Sequences
The dollar sign $ is a bit special. It introduces the interpolation syntax in Terraform. So, when we need to have a literal dollar sign in our strings, we double it like so $$:
1# We need to $$ two times to escape the dollar sign
2
3output "example" {
4 value = "This item costs $$10."
5}
Output:
1# Here is the string with dollar sign after did the escape sequence on $
2
3This item costs $10.
4
6. Percent Sign (%): Escape Sequences
And last but not least, the percent sign %. Terraform did not require us to escape it within strings. However, when using printf style formatting within strings, we may need to escape percent signs by doubling them (%%):
1# Here is a string with % sign printed in the string
2
3output "example" {
4 value = "This operation completed 100%% successfully."
5}
6
Output:
1# Output of the string with % percent sign
2
3This operation completed 100% successfully.
7. Using Escape Sequences in Interpolations
Interpolation is a crucial concept in Terraform. It involves inserting expressions within string literals to create dynamic outputs.
Let's consider an example where we have a user variable, and we want to interpolate it with a string, using a newline (\n) escape sequence for formatting:
1variable "user" {
2 default = "John Doe"
3}
4
5output "message" {
6 value = "Hello, ${var.user}\nWelcome to Terraform."
7}
8
When you run this configuration, the output would be:
1Hello, John Doe
2Welcome to Terraform.
As show in the above example the other escape sequences such as (Tab (\t), Double Quote ("), Dollar Sign ($), Percent Sign (%)) can also be used within string literal.
8. Escape Sequences in Heredoc Strings
Heredoc strings in Terraform allow you to create multi-line strings, which is particularly useful when scripting or whenever a string includes several lines. The good news is that heredoc strings in Terraform also support the escape sequences.
1# Adding \n escape character in Heredoc string
2
3output "example" {
4 value = <<EOF
5 Line1\nLine2
6 EOF
7}
8
But wait! The \n in the heredoc string won't work as an escape sequence, because the default behavior of heredoc strings is to interpret escape sequences literally.
To make escape sequences work in a heredoc string, you should use the <<-EOF indicator instead:
1output "example" {
2 value = <<-EOF
3 Line1\nLine2
4 EOF
5}
6
Now, when you run this configuration, you'll get:
1Line1
2Line2
Conclusion
We've now journeyed through using escape sequences in Terraform as well as using those escape sequences in interpolations and heredoc strings.
As always, remember to practice using these in your own Terraform scripts to get the hang of it. Understanding these finer details can significantly enhance the clarity and readability of your Terraform code. Enjoy coding!
Posts in this Series
- Securing Sensitive Data in Terraform
- Boost Your AWS Security with Terraform : A Step-by-Step Guide
- How to Load Input Data from a File in Terraform?
- Can Terraform be used to provision on-premises infrastructure?
- Fixing the Terraform Error creating IAM Role. MalformedPolicyDocument Has prohibited field Resource
- In terraform how to handle null value with default value?
- Terraform use module output variables as inputs for another module?
- How to Reference a Resource Created by a Terraform Module?
- Understanding Terraform Escape Sequences
- How to fix private-dns-enabled cannot be set because there is already a conflicting DNS domain?
- Use Terraform to manage AWS IAM Policies, Roles and Users
- How to split Your Terraform main.tf File into Multiple Files
- How to use Terraform variable within variable
- Mastering the Terraform Lookup Function for Dynamic Keys
- Copy files to EC2 and S3 bucket using Terraform
- Troubleshooting Error creating EC2 Subnet InvalidSubnet Range The CIDR is Invalid
- Troubleshooting InvalidParameter Security group and subnet belong to different networks
- Managing strings in Terraform: A comprehensive guide
- How to use terraform depends_on meta argument?
- What is user_data in Terraform?
- Why you should not store terraform state file(.tfstate) inside Git Repository?
- How to import existing resource using terraform import comand?
- Terraform - A detailed guide on setting up ALB(Application Load Balancer) and SSL?
- Testing Infrastructure as Code with Terraform?
- How to remove a resource from Terraform state?
- What is Terraform null Resource?
- In terraform how to skip creation of resource if the resource already exist?
- How to setup Virtual machine on Google Cloud Platform
- How to use Terraform locals?
- Terraform Guide - Docker Containers & AWS ECR(elastic container registry)?
- How to generate SSH key in Terraform using tls_private_key?
- How to fix-Terraform Error acquiring the state lock ConditionalCheckFiledException?
- Terraform Template - A complete guide?
- How to use Terragrunt?
- Terraform and AWS Multi account Setup?
- Terraform and AWS credentials handling?
- How to fix-error configuring S3 Backend no valid credential sources for S3 Backend found?
- Terraform state locking using DynamoDB (aws_dynamodb_table)?
- Managing Terraform states?
- Securing AWS secrets using HashiCorp Vault with Terraform?
- How to use Workspaces in Terraform?
- How to run specific terraform resource, module, target?
- How Terraform modules works?
- Secure AWS EC2s & GCP VMs with Terraform SSH Keys!
- What is terraform provisioner?
- Is terraform destroy needed before terraform apply?
- How to fix terraform error Your query returned no results. Please change your search criteria and try again?
- How to use Terraform Data sources?
- How to use Terraform resource meta arguments?
- How to use Terraform Dynamic blocks?
- Terraform - How to nuke AWS resources and save additional AWS infrastructure cost?
- Understanding terraform count, for_each and for loop?
- How to use Terraform output values?
- How to fix error configuring Terraform AWS Provider error validating provider credentials error calling sts GetCallerIdentity SignatureDoesNotMatch?
- How to fix Invalid function argument on line in provider credentials file google Invalid value for path parameter no file exists
- How to fix error value for undeclared variable a variable named was assigned on the command line?
- What is variable.tf and terraform.tfvars?
- How to use Terraform Variables - Locals,Input,Output
- Terraform create EC2 Instance on AWS
- How to fix Error creating service account googleapi Error 403 Identity and Access Management (IAM) API has not been used in project before or it is disabled
- Install terraform on Ubuntu 20.04, CentOS 8, MacOS, Windows 10, Fedora 33, Red hat 8 and Solaris 11