terraform cheat sheet

Terraform Cheat Sheet: CLI Commands with Examples

March 19th, 2026
2606
07:00 Minutes

Imagine deploying entire cloud environments with just a few lines of code, no clicking through dashboards, no manual setup, no missed configurations. That’s the power of Terraform. It is one of the most widely used Infrastructure as Code (IaC) tools in the DevOps world today.

Whether you build on AWS, Azure, GCP, or a hybrid setup, Terraform lets you automate infrastructure with speed, reliability, and version control. This Terraform Cheat Sheet is your quick, practical guide to commands, syntax, workflows, and best practices. It is perfect for beginners getting started and professionals who need a fast reference while working on real deployments.

What is Terraform?

Terraform is a powerful Infrastructure as Code tool used to automate the creation, modification, and deletion of cloud resources using declarative configuration files. It automates the lifecycle of servers, networks, storage, and security components while maintaining state for consistency. It supports multi-cloud provisioning, environment management, and large-scale automation pipelines.

Terraform works across multiple providers and environments, which makes it ideal for DevOps automation, scalable deployments, production readiness, and multi-region orchestration of infrastructure systems. It supports various cloud providers, including AWS, Azure, GCP, Kubernetes, Oracle, VMware, DigitalOcean, GitHub, and 100+ more.

How Terraform Works?

Terraform follows a simple workflow where infrastructure is written as code, initialized, planned, applied to production, and destroyed when no longer needed. It compares the desired state with the actual state and ensures consistent, repeatable deployments through execution planning and idempotency.


Terraform Core Concepts Cheat Sheet

Terraform revolves around providers, resources, data sources, variables, locals, outputs, modules, and state. These pieces connect together to define, structure, and execute infrastructure operations. Understanding them enables scalable, repeatable deployments across development, staging, and production.

1. Providers

Providers are plugins that allow Terraform to communicate with cloud APIs. You only have to select a provider, authenticate, and then Terraform provisions supported resources for you.

provider "aws" { region = "us-east-1" }

2. Resources

Resources are the infrastructure components created by Terraform such as servers, networks, or storage. These form the core of your deployment.

resource "aws_instance" "web" { ami = "ami-xyz" instance_type = "t2.micro" }

3. Data Sources

Data sources retrieve details of already existing cloud assets so you can reference or reuse them without deploying new ones.

data "aws_ami" "latest" { most_recent = true }

4. Input Variables

Input variables allow dynamic configuration without editing code repeatedly. You can override values through CLI flags or .tfvars files.

variable "env" { default = "dev" }

5. Output Values

Output values return useful results after deployment like IP addresses or ARNs, which can be consumed by other modules or tools.

output "server_ip" { value = aws_instance.web.public_ip }

6. Local Values

Local values store computed or repetitive values for cleaner, shorter Terraform code.

locals { prefix = "prod-app" }

7. Modules

Modules are reusable Terraform building blocks used to standardize deployments across multiple environments.

module "vpc" { source = "./modules/vpc" }

8. State

Terraform tracks infrastructure details inside state files to detect changes and build incremental updates. Remote state is often used for teams and CI/CD.

Terraform File Structure & Naming

Terraform projects are usually split into logical files for resources, variables, and outputs. Clear file separation improves readability, scalability, and environment management.

Common Project Files

File Purpose
main.tfCore resources and configuration
variables.tfInput variable definitions
outputs.tfOutput values
providers.tfProvider configuration & authentication
terraform.tfvarsInput values for variables
backend.tfRemote state configuration
Path Purpose
/modulesReusable Terraform modules
/env/devDevelopment environment configuration
/env/prodProduction environment configuration
Root .tf filesMain execution entry and shared config

HCL Syntax Basics

Terraform uses HashiCorp Configuration Language (HCL), a declarative, readable syntax supporting expressions, functions, maps, lists, and dynamic values. It forms the foundation of Terraform configurations.

Element Meaning
BlocksDefine things like resource, provider, variable
ArgumentsKey-value pairs inside blocks
Data typesstring, number, bool, list, map
ExpressionsReferences like var.name, module.vpc.id
Comments# or // for single line, /* ... */ for multi-line

Essential Terraform Commands

Terraform commands manage initialization, validation, planning, application, destruction, formatting, state review, variable output, tainting, and resource import. Mastering these commands is essential for real deployment workflows and environment management.

Command What It Does?
terraform initInitializes working directory, downloads providers & modules
terraform planShows execution preview before applying changes
terraform applyCreates or updates infrastructure as per configuration
terraform destroyDestroys all managed infrastructure resources
terraform refreshSyncs real infrastructure state (older versions)
terraform showDisplays the current state or plan output
terraform validateChecks configuration syntax & structure correctness
terraform fmtFormats .tf files to standard style
terraform graphGenerates dependency graph of resources
terraform providersLists provider requirements and configurations
terraform providers mirrorDownloads providers locally for offline use
terraform outputPrints output values after apply
terraform consoleInteractive shell for evaluating expressions
terraform getDownloads or updates module source code
terraform importBrings existing infrastructure under Terraform control
terraform taintMarks a resource for forced recreation
terraform untaintRemoves taint to avoid forced replacement
terraform stateMain command for state management operations
terraform state listLists tracked resources in the state file
terraform state showDisplays details of a specific resource from state
terraform state pullDownloads the state file locally
terraform state pushUploads or replaces remote state file
terraform state rmRemoves resource from state without destroying infra
terraform state mvMoves items between modules or renames resources
terraform state replace-providerReplaces one provider with another in state
terraform unlockUnlocks a previously locked state
terraform force-unlockForces unlock when normal unlock fails
terraform workspaceCreates & manages multiple workspaces/environments
terraform loginAuthenticates to Terraform Cloud or Enterprise
terraform logoutClears stored Terraform Cloud credentials
terraform versionShows installed Terraform version
terraform cloudTerraform Cloud operations (runs, config, state etc.)
terraform update (varies)Updates providers or modules where supported

Variables, Locals & Output Reference

Variables pass input, locals store reusable logic, and outputs expose results after provisioning. When used together, they build modular and scalable infrastructure across multiple cloud deployments.

Type Purpose
variableDefines input configuration values
.tfvarsOverrides variable values per environment
Sensitive variableHides secrets and prevents them from printing
localsStores shortcuts or computed values
outputsReturns values after apply (IPs, IDs, ARNs)

Resources & Data Sources

Resources and data sources are core to cloud platforms. Resources create infrastructure such as compute, networks, and load balancers. Data sources fetch existing ones for reuse. Using them together helps integrate legacy and active deployments without rewriting code.

Types of Resources in Terraform

Resource Type Example
Instanceaws_instance
VPCaws_vpc
Storageaws_s3_bucket
Databaseaws_rds_instance

Types of Data Sources in Terraform

Data Source Usage Example
aws_amiFetch latest AMI
aws_vpcReference an existing VPC
aws_subnetUse an existing subnet

Modules Cheat Sheet

Modules are behind code reusability in Terraform. They group resources into reusable packages, reduce repetition, enforce standards, and simplify multi-environment deployments. You can import modules from registries or write local modules for enterprise-grade structure.

Registry Example

module "vpc" { source = "terraform-aws-modules/vpc/aws" }

Local Module Example

module "ec2" { source = "./modules/ec2" }

Expressions, Functions & Conditionals

Terraform supports string templating, arithmetic, logical operators, built-in functions, conditional evaluation, and for-expressions to generate dynamic resources. These enable smarter automation and configuration flexibility.

Feature Example
Interpolation"app-${var.env}"
Conditionalsvar.env == "prod" ? 2 : 1
Built-in functionsjoin(), merge(), lookup()
for_eachLoop over maps or sets to create many resources

Terraform + Git & CI/CD

The integration of Terraform with Git and CI/CD pipelines is a common and highly effective practice in IaC management. This combination enables automation, version control, and consistent deployments of infrastructure. CI/CD can integrate with GitHub Actions, GitLab CI, Terraform Cloud, Azure DevOps, or Jenkins for automated provisioning pipelines.

Quick Copy-Paste Snippets

1. Minimal EC2 Example

This snippet provisions a lightweight EC2 instance on AWS. The provider block configures Terraform to use AWS and sets the region. The aws_instance resource deploys a virtual machine using a chosen AMI and instance type, ideal for testing or creating a basic server quickly.

provider "aws" { region = "us-east-1" }

resource "aws_instance" "demo" {
ami = "ami-x"
instance_type = "t2.micro"
}

2. Remote Backend

This configuration stores Terraform state in an S3 bucket instead of locally. The bucket holds your state file, and the DynamoDB table enables state locking to prevent two users or pipelines from modifying infrastructure simultaneously. It is mostly required for team environments, CI/CD usage, and production setups.

backend "s3" { bucket = "terraform-backend" dynamodb_table = "lock-table" }

Wrapping Up Terraform Cheat Sheet

Terraform enables predictable, scalable, and reusable infrastructure without manual provisioning. This Terraform cheat sheet covers concepts, syntax, commands, modules, state, CI/CD usage, and snippets you can apply instantly. As you continue practicing, try modules for environment separation, remote backends for team collaboration, and automation pipelines for enterprise workflows. The more you experiment, the faster you master real-world deployment workflows, giving you strong control over infrastructure at cloud scale.

FAQs

1. Is Terraform suitable for beginners?

Yes. Terraform is easy to learn because configuration is written in simple HCL syntax. Beginners can start with variables, resources, and apply/destroy commands, then gradually move toward modules, remote backend, and CI/CD automation.

2. What are the most commonly used Terraform commands?

The most frequently used commands are terraform init, terraform plan, terraform apply, terraform destroy, terraform validate, and terraform fmt. These handle setup, provisioning, formatting, cleanup, and planning. This makes them essential for everyday usage.

3. Why is Terraform state important?

Terraform state tracks deployed infrastructure so Terraform knows what exists and what needs to change. Without a state file, Terraform wouldn't detect drift, update resources correctly, or safely manage environments across teams.

Articles You Can Also Read:

Course Schedule

Course NameBatch TypeDetails
Terraform Training
Every WeekdayView Details
Terraform TrainingEvery WeekendView Details
About the Author
Sanjay Prajapat
About the Author

Sanjay Prajapat is a Data Engineer and technology writer with expertise in Python, SQL, data visualization, and machine learning. He simplifies complex concepts into engaging content, helping beginners and professionals learn effectively while exploring emerging fields like AI, ML, and cybersecurity in today’s evolving tech landscape.

Drop Us a Query
Fields marked * are mandatory
×

Your Shopping Cart


Your shopping cart is empty.