Terraform syntax
Terraform syntax
1. Basic Commands
• Initialize Terraform
terraform init
• Format and validate files
• terraform fmt # Format code
terraform validate # Validate syntax
• Plan the infrastructure
terraform plan
• Apply changes
terraform apply -auto-approve
• Destroy resources
terraform destroy -auto-approve
• Show current state
terraform show
• List all resources
terraform state list
• Remove a specific resource
terraform state rm <resource>
2. Terraform Configuration Files
a. Providers
provider "aws" {
region = "us-east-1"
}
b. Variables
variable "instance_type" {
type = string
default = "t2.micro"
}
c. Resources
resource "aws_instance" "web" {
ami = "ami-12345678"
instance_type = var.instance_type
}
d. Outputs
output "instance_ip" {
value = aws_instance.web.public_ip
}
e. Data Sources
data "aws_vpc" "default" {
default = true
}
f. Modules
module "network" {
source = "./modules/network"
vpc_cidr = "10.0.0.0/16"
}
5 . Loops
a. count
resource "aws_instance" "web" {
count =3
instance_type = "t2.micro"
}
b. for_each
variable "servers" {
type = list(string)
default = ["web1", "web2"]
}
resource "aws_instance" "web" {
for_each = toset(var.servers)
instance_type = "t2.micro"
}
6 . Functions
locals {
upper_name = upper("terraform")
}
7 . Lifecycle Management
resource "aws_instance" "web" {
lifecycle {
prevent_destroy = true
}
}
8 . Terraform Workspaces
terraform workspace new dev
terraform workspace select dev
terraform workspace list
This cheat sheet provides a quick reference to Terraform's essential
commands and syntax.