Core Commands
- terraform initInitialize
- terraform planPreview changes
- terraform applyApply changes
- terraform destroyDestroy all
- terraform validateValidate config
- terraform fmtFormat code
State Commands
- terraform state listList resources
- terraform state showShow resource
- terraform state mvMove resource
- terraform state rmRemove from state
- terraform importImport existing
Workspace Commands
- terraform workspace listList workspaces
- terraform workspace newCreate workspace
- terraform workspace selectSwitch workspace
- terraform workspace deleteDelete workspace
Plan Options
- -out=plan.outSave plan
- -var="key=val"Set variable
- -var-file=vars.tfvarsVariables file
- -target=resourceTarget resource
- -refresh=falseSkip refresh
Resource Block
resource "aws_instance" "web" {
ami = "ami-0c55b159cbfafe1f0"
instance_type = "t3.micro"
tags = {
Name = "WebServer"
Environment = var.environment
}
lifecycle {
create_before_destroy = true
}
}
Variables
# Variable definition (variables.tf)
variable "environment" {
description = "Deployment environment"
type = string
default = "dev"
validation {
condition = contains(["dev", "staging", "prod"], var.environment)
error_message = "Must be dev, staging, or prod."
}
}
# Usage
name = "app-${var.environment}"
Variable Types
- string"hello"
- number42, 3.14
- booltrue, false
- list(type)["a", "b"]
- map(type){key = "val"}
- object({...})Structured
Outputs
output "instance_ip" {
description = "Public IP"
value = aws_instance.web.public_ip
sensitive = false
}
Module Usage
# Using a module
module "vpc" {
source = "terraform-aws-modules/vpc/aws"
version = "5.0.0"
name = "my-vpc"
cidr = "10.0.0.0/16"
azs = ["us-east-1a", "us-east-1b"]
private_subnets = ["10.0.1.0/24", "10.0.2.0/24"]
public_subnets = ["10.0.101.0/24", "10.0.102.0/24"]
}
Functions
- join(",", list)Join list
- split(",", str)Split string
- length(list)List length
- lookup(map, key)Map lookup
- file(path)Read file
- templatefile()Template
Backend Config
terraform {
backend "s3" {
bucket = "tf-state"
key = "prod/terraform.tfstate"
region = "us-east-1"
}
}