Do you hate reading ugly code? If so, you should avoid writing one yourself, too. Most computer languages follow specific style conventions, and the HashiCorp Terraform language is no exception.
A single misplaced bracket or an over-indentation can make your Terraform configuration files challenging to read, maintain, and understand — overall, a bad experience. But with the Terraform fmt
command, you can fix these code inconsistencies all at once.
Read on, and you will learn how to automatically rewrite Terraform configuration files with a single command while applying the proper code formatting. You can even preview the changes before committing them! Let’s get started enhancing your infrastructure provisioning experience!
Prerequisites
If you’d like to follow along in this tutorial, ensure you have the following in place:
- You must have an Amazon Web Service account (AWS). If you don’t have one, you can create a free-tier account.
- You’ll need a computer where to write code and run commands. This tutorial will be using Ubuntu 18.04.5 LTS, but a Windows or macOS computer will be OK, too.
- Install and configure the AWS Command Line Interface (CLI) on your computer. The latest version as of this writing is 2.3.7.
- A code editor such as Visual Studio Code (VSCode), but feel free to use your preferred editor.
Creating a Terraform Configuration File
Before going any further, you should have a Terraform configuration file(s) to use as the target for the Terraform code formatting. Follow the instructions below to create the working directories and configuration files for your project.
1. Open a new terminal window on your computer.
2. Create a folder named terraform-s3-demo on your home directory. This folder is where your Terraform files will reside. Run the command below to create the working folder.
# Create the parent folder for your Terraform files
mkdir ~/terraform-s3-demo
# Change the current working directory to the new folder
cd ~/terraform-s3-demo
3. Next, create an empty file with the name main.tf. This file will contain your Terraform configuration code.
# Create a blank configuration file on the current directory
touch main.tf
4. Now, open the main.tf file in your code editor. Suppose your code editor is VSCode, type code .
to open the current working directory in VSCode.
5. Copy the configuration below that defines the creation of an AWS S3 bucket, paste it into the main.tf, and save the file. Refer to the inline comments for each code block.
Note: The Bucket name must be unique across the AWS infrastructure. Make sure to change the bucket name
terraform-demo-bucket-8972376
in the code to something else to make it unique; for example –terraform-demo-bucket-68574321
.
Note: The configuration code below is deliberately malformed to demonstrate how to apply the correct formatting later in the later sections.
# Declaring the Provider Requirements
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 3.0"
}
}
}
# Configuring the AWS Provider (aws) with region set to 'us-east-2'
provider "aws" {
region = "us-east-2"
}
# Creating the encryption key which will encrypt the bucket objects
resource "aws_kms_key" "mykey" {
deletion_window_in_days = "20"
}
# Granting the Bucket Access
resource "aws_s3_bucket_public_access_block" "publicaccess" {
bucket = aws_s3_bucket.demobucket.id
block_public_acls = false
block_public_policy = false
}
# Creating the S3 Bucket and apply encryption
resource "aws_s3_bucket" "demobucket" {
## Change the "bucket" name into a unique value before provisioning.
bucket = "terraform-demo-bucket-8972376"
force_destroy = false
server_side_encryption_configuration {
rule {
apply_server_side_encryption_by_default {
kms_master_key_id = aws_kms_key.mykey.arn
sse_algorithm = "aws:kms"
}
}
}
# Keeping multiple versions of an object in the same bucket
versioning {
enabled = true
}
}
Enhancing Code Readability with Terraform fmt Command
So far, you’ve created the boilerplate configuration file necessary to create an AWS S3 bucket. Terraform fmt
command have several flags to help determine whether the file follows the canonical format or style.
Checking Files for Formatting Inconsistencies
To check which files on the current working directory contain formatting inconsistencies, follow these steps.
Open a terminal and navigate to the ~/*terraform-s3-demo*
directory if you haven’t already.
Next, run the command below. The -check
flag will return the filenames that need formatting correction.
terraform fmt -check
As you can see below, the command returned the filename main.tf, indicating that this file contains malformed code.
To check a file under sub-directories (if any), append the
-recursive
flag to theterraform fmt
command to process the files under those sub-directories such as:terraform fmt -check -recursive
Previewing Formatting Changes
So you were able to check the files and determine which ones need format correcting. But wouldn’t it be nice if you knew which parts of the file have inconsistent formatting?
Luckily, the terraform fmt
command allows you to preview the changes by running the terraform fmt
command with the -diff
flag. Copy the command below and run it in the terminal.
terraform fmt -check -diff
After running the command, you should see a similar output to the image below. The result shows you the filename at the top and which lines do not conform with the correct formatting.
For clarity, the lines that start with “-
” with the red arrow are the original (current configuration) code. The lines beginning with “+
” with the green arrow show the proposed changes to the code.
Rewriting Configuration Files with Proper Formatting
You now understand how to determine which files contain inconsistent code and how to preview the changes. How do you now apply the proper Terraform configuration format? To rewrite the configuration files, run the command below without any flags.
terraform fmt
After running the command, view your main.tf code in the editor again and confirm the changes. The image below shows the before and after formatting of the configuration file.
Provisioning Resources using the Terraform fmt Formatted Configuration
You’ve now formatted your configuration file using the Terraform fmt
command. But how do you know if the new configurations still work? Why not use it to provision a new AWS S3 bucket?
To provision a Terraform configuration, Terraform typically uses a three-command approach in sequential order:
- terraform init – initializes the working directory, which includes installing the provider inside the directory.
- terraform plan – create an execution plan based on your Terraform configurations.
- terraform apply – execute the execution plan that the
terraform plan
command proposed.
Follow these steps to start provisioning.
1. Open a terminal and navigate to the ~/terraform-s3-demo directory.
cd ~/terraform-s3-demo
2. Next, initialize (init
) the working directory by running the command below. The initialization includes installing the plugins and providers necessary to work with resources.
terraform init
If all goes well, you should see the message Terraform has been successfully initialized
in the output, as shown below.
3. Now, run the command below to create an execution plan
. This step is not mandatory but highly recommended to ensure your configuration files are error-free. Additionally, performing this step gives you the blueprint of resources that Terraform will provision in your infrastructure.
terraform plan
If successful, you should see a message saying Plan: {X} to add, {Y} to change, {Z} to destroy
in the output.
4. Lastly, apply
the execution plan by running the below command. This command reads each configuration (*.tf files) on the working directory to compile a terraform state file and sends that state to AWS, which in turn provisions the AWS S3 bucket.
The
-auto-approve
suppresses the confirmation prompt and automatically approves the plan execution.
terraform apply -auto-approve
As you can see, Terraform has successfully created the AWS bucket in the AWS account.
5. You should now have an AWS S3 bucket created in the us-east-2 region. But to make sure, verify that the bucket exists using the AWS Management Console.
Open your favorite web browser, navigate to the AWS S3 Management Console at https://console.aws.amazon.com/s3/home, and log in to your account.
As you can see below, the S3 bucket you created using Terraform is now present on the AWS S3 buckets in the us-east-2 region.
Conclusion
In this tutorial, you’ve learned how to use Terraform fmt
command to apply consistent formatting to your configuration files.
Creating Terraform configuration files that follow a consistent style or format is essential. You and every other developer who would eventually work on your Terraform files will benefit from your code’s enhanced readability.
So if you’re tired of ugly code, make them pretty using the Terraform fmt
command.