Terraform

Terraform is an open-source Infrastructure as Code (IaC) tool that allows you to define and provide data center infrastructure using a declarative configuration language.

Project Initialization

The terraform init command is used to initialize a working directory containing Terraform configuration files. This is the first command that should be run after writing a new Terraform configuration.

terraform init

Formatting and Validation

It’s a good practice to format and validate your code before applying it.

  • terraform fmt rewrites Terraform configuration files to a canonical format and style.
  • terraform validate checks whether a configuration is syntactically valid and internally consistent.
terraform fmt
terraform validate

Plan and Apply Changes

The Terraform workflow has two main stages: planning and applying.

  • terraform plan creates an execution plan, which lets you preview the changes that Terraform plans to make to your infrastructure.
  • terraform apply executes the actions proposed in a Terraform plan.
terraform plan
terraform apply

You can also pass variables directly on the command line, though using a .tfvars file is recommended for sensitive data.

# Using -var flag
terraform apply -var="resource_group_name=myNewResourceGroupName"
 
# Auto-apply a plan without a confirmation prompt
terraform apply -auto-approve

Inspecting State

The terraform state command is used for advanced state management.

  • terraform show provides human-readable output from a state or plan file.
  • terraform state list lists resources within a Terraform state.
terraform show
terraform state list

Cleaning Up

The terraform destroy command is a convenient way to destroy all of the remote objects managed by a particular Terraform configuration.

terraform destroy

Viewing Outputs

The terraform output command is used to extract the value of an output variable from the state file.

# Display all outputs
terraform output
 
# Display a specific output
terraform output resource_group_id