Terraform Cheat Sheet
Complete reference guide for Terraform with interactive examples and live playground links
Basic Commands
Initialization and Setup
Terraform initialization commands
Terraform
# Initialize Terraform
terraform init
# Initialize with specific backend
terraform init -backend-config="bucket=my-terraform-state"
# Initialize with plugin directory
terraform init -plugin-dir=/path/to/plugins
# Initialize with backend configuration
terraform init -backend-config="path/to/backend.hcl"
Plan and Apply
Plan and apply commands
Terraform
# Create execution plan
terraform plan -out=tfplan
# Apply changes
terraform apply tfplan
# Apply with auto-approve
terraform apply -auto-approve
# Apply with specific variables
terraform apply -var="instance_type=t3.micro" -var="region=us-west-2"
# Apply with variable file
terraform apply -var-file="prod.tfvars"
State Management
State management commands
Terraform
# List resources in state
terraform state list
# Show state details
terraform state show aws_instance.web
# Move resource in state
terraform state mv aws_instance.old aws_instance.new
# Remove resource from state
terraform state rm aws_instance.web
# Import existing resource
terraform import aws_instance.web i-1234567890abcdef0
Resource Management
Resource Configuration
Resource configuration examples
Terraform
# Basic resource
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "web-server"
}
}
# Resource with lifecycle
resource "aws_instance" "web" {
# ... basic configuration ...
lifecycle {
create_before_destroy = true
prevent_destroy = false
ignore_changes = [tags]
}
}
# Resource with depends_on
resource "aws_instance" "web" {
# ... basic configuration ...
depends_on = [
aws_security_group.web,
aws_iam_role.web
]
}
Data Sources
Data source configuration
Terraform
# Basic data source
data "aws_ami" "ubuntu" {
most_recent = true
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*"]
}
owners = ["099720109477"]
}
# Data source with dynamic blocks
data "aws_instances" "web" {
filter {
name = "tag:Environment"
values = ["production"]
}
dynamic "filter" {
for_each = var.additional_filters
content {
name = filter.value.name
values = filter.value.values
}
}
}
Variables and Outputs
Variables and outputs configuration
Terraform
# Variable definitions
variable "environment" {
description = "Environment name"
type = string
default = "dev"
}
variable "instance_count" {
description = "Number of instances"
type = number
validation {
condition = var.instance_count > 0
error_message = "Instance count must be greater than 0."
}
}
# Output definitions
output "instance_ip" {
description = "Public IP of the instance"
value = aws_instance.web.public_ip
sensitive = false
}
output "database_password" {
description = "Database password"
value = aws_db_instance.database.password
sensitive = true
}
Modules and Workspaces
Module Configuration
Module configuration examples
Terraform
# Basic module
module "vpc" {
source = "./modules/vpc"
vpc_cidr = "10.0.0.0/16"
environment = var.environment
}
# Module with version
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "3.0.0"
name = "my-vpc"
cidr = "10.0.0.0/16"
}
# Module with providers
module "vpc" {
source = "./modules/vpc"
providers = {
aws = aws.us-west-2
}
}
Workspace Management
Workspace management commands
Terraform
# List workspaces
terraform workspace list
# Create new workspace
terraform workspace new dev
# Select workspace
terraform workspace select prod
# Show current workspace
terraform workspace show
# Delete workspace
terraform workspace delete dev
Remote State
Remote state configuration
Terraform
# S3 backend configuration
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "path/to/state/file"
region = "us-west-2"
dynamodb_table = "terraform-locks"
encrypt = true
}
}
# Azure backend configuration
terraform {
backend "azurerm" {
resource_group_name = "terraform-state"
storage_account_name = "tfstate"
container_name = "tfstate"
key = "prod.terraform.tfstate"
}
}
Security and Best Practices
State Security
State security configuration
Terraform
# Enable state encryption
terraform {
backend "s3" {
# ... other config ...
encrypt = true
kms_key_id = "arn:aws:kms:region:account:key/key-id"
}
}
# Use sensitive variables
variable "db_password" {
description = "Database password"
type = string
sensitive = true
}
# Secure state access
resource "aws_s3_bucket_policy" "state" {
bucket = aws_s3_bucket.state.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Deny"
Principal = "*"
Action = "s3:*"
Resource = [
aws_s3_bucket.state.arn,
"${aws_s3_bucket.state.arn}/*"
]
Condition = {
Bool = {
"aws:SecureTransport": "false"
}
}
}
]
})
}
Provider Configuration
Provider security configuration
Terraform
# AWS provider with assume role
provider "aws" {
region = "us-west-2"
assume_role {
role_arn = "arn:aws:iam::ACCOUNT_ID:role/ROLE_NAME"
session_name = "terraform-session"
}
}
# Azure provider with managed identity
provider "azurerm" {
features {}
use_managed_identity = true
}
# GCP provider with service account
provider "google" {
project = "my-project"
region = "us-central1"
credentials = file("path/to/service-account.json")
}
Resource Security
Resource security configuration
Terraform
# Secure S3 bucket
resource "aws_s3_bucket" "secure" {
bucket = "my-secure-bucket"
versioning {
enabled = true
}
server_side_encryption_configuration {
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "AES256"
}
}
}
lifecycle_rule {
enabled = true
expiration {
days = 90
}
}
}
# Secure security group
resource "aws_security_group" "web" {
name = "web-sg"
description = "Web server security group"
vpc_id = aws_vpc.main.id
ingress {
from_port = 80
to_port = 80
protocol = "tcp"
cidr_blocks = ["0.0.0.0/0"]
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Name = "web-sg"
}
}
Advanced Features
Dynamic Blocks
Dynamic blocks configuration
Terraform
# Dynamic security group rules
resource "aws_security_group" "web" {
# ... basic configuration ...
dynamic "ingress" {
for_each = var.ingress_rules
content {
from_port = ingress.value.from_port
to_port = ingress.value.to_port
protocol = ingress.value.protocol
cidr_blocks = ingress.value.cidr_blocks
}
}
}
# Dynamic IAM policy
resource "aws_iam_policy" "dynamic" {
name = "dynamic-policy"
dynamic "statement" {
for_each = var.policy_statements
content {
effect = statement.value.effect
actions = statement.value.actions
resources = statement.value.resources
}
}
}
Local Values
Local values configuration
Terraform
# Local values
locals {
common_tags = {
Environment = var.environment
Project = var.project
ManagedBy = "Terraform"
}
instance_count = var.environment == "prod" ? 3 : 1
subnet_cidrs = {
public = cidrsubnet(var.vpc_cidr, 8, 0)
private = cidrsubnet(var.vpc_cidr, 8, 1)
}
}
# Using locals
resource "aws_instance" "web" {
# ... basic configuration ...
tags = local.common_tags
}
resource "aws_subnet" "public" {
cidr_block = local.subnet_cidrs.public
# ... other configuration ...
}
Terraform Functions
Terraform functions usage
Terraform
# String functions
locals {
name = "my-resource"
formatted_name = format("%s-%s", var.environment, local.name)
upper_name = upper(local.name)
}
# Numeric functions
locals {
instance_count = max(1, var.desired_count)
port_number = tonumber(var.port)
}
# Collection functions
locals {
first_subnet = element(var.subnets, 0)
all_tags = merge(var.tags, local.common_tags)
unique_ports = distinct(var.ports)
}
# Type conversion
locals {
string_list = tolist(var.string_set)
number_map = tomap(var.number_object)
}
Terraform - Interactive Developer Reference
Hover over code blocks to copy or run in live playground