Chapter 2. Terraform Basics

It’s an understatement to say that there are many ways in which folks can use Terraform. From standing up GitHub organizations, provisioning their cluster management solution, to even curating the perfect Spotify playlist, Terraform is an excellent, declarative way to manage many things, even though it’s not always apparent what the best practices are for writing Terraform or how to construct your code. We’ll dig into the basics of Terraform in this chapter.

2.1 Formatting and Validating Terraform Code

Problem

You have written some Terraform code, which is hard to read and understand. It needs to be formatted consistently, and you want to ensure the code is valid before applying it.

Solution

The first step in the solution is to run the terraform fmt command, which allows for real-time evaluation of Terraform expressions:

# Step 1: Run the Terraform format command
terraform fmt

# Step 2: Run the Terraform validate command
terraform init
terraform validate

Discussion

The terraform fmt command automatically formats your Terraform code to follow the recommended style guidelines, making it easier to read and maintain. This command should be run in the same directory as your Terraform configuration files.

The terraform validate command checks the syntax and semantics of your Terraform code to ensure that it’s valid before applying it. It checks for syntax errors, missing required arguments, and incorrect references. However, it does not check if the ...

Get Terraform Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.