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 Type | Purpose | Example Syntax |
|---|---|---|
terraform | Configure required providers & version constraints | terraform { required_version = ">= 1.5.0" } |
provider | Configure target cloud provider API credentials | provider "aws" { region = var.aws_region } |
variable | Define input variables with defaults & types | variable "instance_type" { type = string } |
resource | Define infrastructure component to manage | resource "aws_s3_bucket" "b" { bucket = "my-bucket" } |
data | Fetch external existing infrastructure state | data "aws_ami" "ubuntu" { most_recent = true } |
output | Expose infrastructure values after apply | output "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
| Command | Purpose / Action |
|---|---|
terraform init | Initialize backend, working directory, and download provider plugins |
terraform plan | Create and display an execution plan showing pending changes |
terraform apply | Create or update infrastructure according to configuration |
terraform destroy | Destroy all infrastructure managed by current configuration |
terraform fmt | Auto-format HCL files according to standard formatting rules |
terraform validate | Validate HCL syntax and internal consistency of configuration files |
terraform state list | List all resources currently tracked in state file |
Common Pitfalls & Tips
[!WARNING] Never commit
terraform.tfstateor.tfvarsfiles containing secret keys to public Git repositories! Use remote backends (e.g., AWS S3 with DynamoDB locking).
[!TIP] Always review
terraform planoutput carefully before runningterraform applyto prevent accidental resource deletion or recreation.