Terraform HCL Cheat Sheet

Quick reference guide for Terraform: HCL syntax, resource blocks, state manipulation, and CLI commands.

Containers & Cloud
terraform
hcl
devops

Terraform is an open-source Infrastructure as Code (IaC) tool created by HashiCorp that allows developers to define and provision cloud infrastructure using HCL.

HCL Syntax Blocks Reference

Table
Block TypePurposeExample Syntax
terraformConfigure required providers & version constraintsterraform { required_version = ">= 1.5.0" }
providerConfigure target cloud provider API credentialsprovider "aws" { region = var.aws_region }
variableDefine input variables with defaults & typesvariable "instance_type" { type = string }
resourceDefine infrastructure component to manageresource "aws_s3_bucket" "b" { bucket = "my-bucket" }
dataFetch external existing infrastructure statedata "aws_ami" "ubuntu" { most_recent = true }
outputExpose infrastructure values after applyoutput "ip" { value = aws_instance.web.public_ip }

HCL Config Example

hcl
variable "environment" {
  type    = string
  default = "production"
}

resource "aws_s3_bucket" "assets" {
  bucket = "app-assets-${var.environment}"

  tags = {
    Environment = var.environment
    ManagedBy   = "Terraform"
  }
}

output "bucket_arn" {
  description = "ARN of the provisioned S3 bucket"
  value       = aws_s3_bucket.assets.arn
}

Essential Terraform CLI Commands

Table
CommandPurpose / Action
terraform initInitialize backend, working directory, and download provider plugins
terraform planCreate and display an execution plan showing pending changes
terraform applyCreate or update infrastructure according to configuration
terraform destroyDestroy all infrastructure managed by current configuration
terraform fmtAuto-format HCL files according to standard formatting rules
terraform validateValidate HCL syntax and internal consistency of configuration files
terraform state listList all resources currently tracked in state file

Common Pitfalls & Tips

[!WARNING] Never commit terraform.tfstate or .tfvars files containing secret keys to public Git repositories! Use remote backends (e.g., AWS S3 with DynamoDB locking).

[!TIP] Always review terraform plan output carefully before running terraform apply to prevent accidental resource deletion or recreation.