Getting Started
4 snippetsBasic Terraform configuration
Provider Configuration
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-east-1"
}Comments
# Single line comment
/*
Multi-line
comment
*/Initialize Terraform
terraform initCommon Commands
terraform plan # Preview changes
terraform apply # Apply changes
terraform destroy # Destroy resources
terraform validate # Validate config
terraform fmt # Format filesVariables
5 snippetsInput and output variables
Variable Declaration
variable "instance_type" {
description = "EC2 instance type"
type = string
default = "t2.micro"
}Variable Types
variable "count" {
type = number
}
variable "enabled" {
type = bool
}
variable "tags" {
type = map(string)
}
variable "subnets" {
type = list(string)
}Variable Usage
resource "aws_instance" "web" {
instance_type = var.instance_type
ami = var.ami_id
}Output Values
output "instance_ip" {
description = "Public IP of EC2 instance"
value = aws_instance.web.public_ip
}
output "vpc_id" {
value = aws_vpc.main.id
}Local Values
locals {
common_tags = {
Environment = "production"
ManagedBy = "Terraform"
}
name_prefix = "${var.project}-${var.environment}"
}Resources
5 snippetsDefining infrastructure resources
Basic Resource
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "WebServer"
}
}Resource Dependencies
resource "aws_eip" "ip" {
vpc = true
instance = aws_instance.web.id
depends_on = [aws_internet_gateway.gw]
}Count Meta-Argument
resource "aws_instance" "server" {
count = 3
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
tags = {
Name = "Server-${count.index}"
}
}For_Each Meta-Argument
resource "aws_s3_bucket" "buckets" {
for_each = toset(["logs", "data", "backups"])
bucket = "${var.prefix}-${each.key}"
}Lifecycle Rules
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t2.micro"
lifecycle {
create_before_destroy = true
prevent_destroy = true
ignore_changes = [tags]
}
}Tired of looking up syntax?
DocuWriter.ai generates documentation and explains code using AI.
Data Sources
3 snippetsReading existing resources
Data Source
data "aws_ami" "ubuntu" {
most_recent = true
filter {
name = "name"
values = ["ubuntu/images/hvm-ssd/ubuntu-*"]
}
owners = ["099720109477"] # Canonical
}Use Data Source
resource "aws_instance" "web" {
ami = data.aws_ami.ubuntu.id
instance_type = "t2.micro"
}VPC Data Source
data "aws_vpc" "default" {
default = true
}
data "aws_subnets" "default" {
filter {
name = "vpc-id"
values = [data.aws_vpc.default.id]
}
}Modules
4 snippetsReusable configuration components
Module Definition
# modules/vpc/main.tf
variable "cidr_block" {
type = string
}
resource "aws_vpc" "main" {
cidr_block = var.cidr_block
}
output "vpc_id" {
value = aws_vpc.main.id
}Module Usage
module "vpc" {
source = "./modules/vpc"
cidr_block = "10.0.0.0/16"
}Access Module Output
resource "aws_subnet" "public" {
vpc_id = module.vpc.vpc_id
cidr_block = "10.0.1.0/24"
}Remote Module
module "s3_bucket" {
source = "terraform-aws-modules/s3-bucket/aws"
version = "3.15.0"
bucket = "my-bucket"
acl = "private"
}Built-in Functions
5 snippetsCommon Terraform functions
String Functions
upper("hello") # HELLO
lower("WORLD") # world
format("server-%03d", 1) # server-001
join("-", ["a", "b"]) # a-b
split("-", "a-b-c") # ["a", "b", "c"]Collection Functions
length([1, 2, 3]) # 3
concat([1, 2], [3, 4]) # [1, 2, 3, 4]
contains(["a"], "a") # true
merge({a=1}, {b=2}) # {a=1, b=2}Type Conversions
tostring(42) # "42"
tonumber("42") # 42
tolist(["a", "b"]) # Convert to list
toset(["a", "a", "b"]) # ["a", "b"] (unique)File Functions
file("path/to/file.txt") # Read file
filebase64("path/to/file.bin") # Base64 encode
jsonencode({key = "value"}) # JSON encode
jsondecode(file("data.json")) # Parse JSONIP Functions
cidrsubnet("10.0.0.0/16", 8, 1) # 10.0.1.0/24
cidrhost("10.0.0.0/24", 5) # 10.0.0.5Expressions
5 snippetsConditional and iteration expressions
Conditional Expression
variable "environment" {}
resource "aws_instance" "web" {
instance_type = var.environment == "prod" ? "t2.large" : "t2.micro"
}For Expression (List)
variable "users" {
type = list(string)
}
locals {
user_emails = [for user in var.users : "${user}@example.com"]
}For Expression (Map)
variable "tags" {
type = map(string)
}
locals {
uppercase_tags = {
for key, value in var.tags :
upper(key) => upper(value)
}
}For with If
locals {
even_numbers = [for n in [1, 2, 3, 4, 5] : n if n % 2 == 0]
# Result: [2, 4]
}Dynamic Blocks
resource "aws_security_group" "example" {
name = "example"
dynamic "ingress" {
for_each = var.ingress_rules
content {
from_port = ingress.value.port
to_port = ingress.value.port
protocol = "tcp"
cidr_blocks = ingress.value.cidr_blocks
}
}
}State Management
4 snippetsManaging Terraform state
S3 Backend
terraform {
backend "s3" {
bucket = "my-terraform-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
encrypt = true
dynamodb_table = "terraform-locks"
}
}State Commands
terraform state list # List resources
terraform state show aws_instance.web # Show resource
terraform state mv SOURCE DEST # Move resource
terraform state rm aws_instance.web # Remove from stateImport Existing Resource
# First, add resource to config
resource "aws_instance" "imported" {
# ... configuration
}
# Then import
terraform import aws_instance.imported i-1234567890abcdef0Workspace Commands
terraform workspace list # List workspaces
terraform workspace new dev # Create workspace
terraform workspace select prod # Switch workspace
terraform workspace show # Current workspace