Terraform
Build cloud infrastructure from code - plan it, apply it, destroy it.
15 levels · 78 lessons · about 3 hours
Terraform commands cheat sheet
Every command in the Terraform Playground, grouped by level. Practise each one above in the interactive terminal.
Show all 78 commandsHide commands
Level 1: The Core Workflow (Beginner)
init → plan → apply → destroy.
- Check the version
terraform versionTerraform is a single binary. terraform version confirms it's installed.
- Initialise
terraform initinit downloads the providers (like AWS) your code needs and sets up the state backend. Always first.
- Preview changes
terraform planplan is a dry run: it shows what would be created (+), changed (~) or destroyed (-). Nothing is touched.
- Apply
terraform applyapply makes the real changes. It shows the plan again and asks you to type yes.
- Destroy
terraform destroydestroy deletes everything this code created. Perfect for cleaning up practice environments so you don't pay.
Level 2: Clean, Valid Code (Beginner)
Format, validate and read outputs.
- Auto-format
terraform fmtfmt rewrites .tf files to the standard style. Run it before every commit.
- Validate
terraform validatevalidate checks syntax and references without calling any cloud API.
- Read outputs
terraform outputOutputs expose useful values (like an IP or URL) after apply.
- Pass a variable
terraform plan -var="env=dev"-var sets an input variable from the command line, e.g. which environment to build.
- Use a variables file
terraform plan -var-file=prod.tfvars-var-file loads many variables from a .tfvars file - one file per environment.
Level 3: Working with State (Intermediate)
Understand what Terraform is tracking.
- List tracked resources
terraform state listState is Terraform's record of what exists. state list shows every resource in it.
- Inspect one resource
terraform state show aws_instance.webstate show prints every attribute Terraform knows about one resource.
- Show everything
terraform showterraform show prints the whole current state in a readable form.
- Save a plan
terraform plan -out=tfplan-out saves a plan to a file, so apply runs exactly what was reviewed - the standard in CI pipelines.
- Apply the saved plan
terraform apply tfplanApplying a saved plan doesn't ask again - it was already reviewed.
Level 4: Pro Moves (Intermediate)
Environments, imports and fixing drift.
- Create a workspace
terraform workspace new devWorkspaces keep separate state for the same code, e.g. dev and prod.
- Switch workspace
terraform workspace select prodworkspace select moves between existing workspaces.
- Import an existing resource
terraform import aws_s3_bucket.logs legacy-logsimport brings something created by hand (in the console) under Terraform's control.
- Detect drift
terraform plan -refresh-only-refresh-only checks if real infrastructure changed outside Terraform (drift) without changing anything.
- Recreate one resource
terraform apply -replace=aws_instance.web-replace forces one resource to be destroyed and created again (the modern replacement for taint).
Level 5: Teams & Remote State (Intermediate)
Share state safely, refactor resources and fix stuck locks.
- Remote backend
terraform init -backend-config=backend.hclTeams keep state in a shared backend (like S3) instead of a local file. -backend-config passes its settings.
- Upgrade providers
terraform init -upgradeinit -upgrade fetches the newest provider versions your version constraints allow.
- List providers
terraform providersterraform providers shows which providers your code and modules need.
- Rename without recreating
terraform state mv aws_instance.web aws_instance.appRenaming a resource in code makes Terraform want to destroy and recreate it. state mv tells it it's the same thing.
- Stop managing a resource
terraform state rm aws_s3_bucket.oldstate rm makes Terraform forget a resource without deleting it in the cloud.
- Fix a stuck lock
terraform force-unlock 6f2b9c1eState is locked while someone runs apply. If a run crashed, the lock stays. force-unlock removes it by its ID.
Level 6: Modules & Expressions (Advanced)
Use modules and test expressions before you put them in code.
- Download modules
terraform getModules are reusable blocks, like a VPC module. terraform get downloads the modules your code uses (init does it too).
- List what a module created
terraform state list module.vpcResources inside a module show up with the module name in front, like module.vpc.aws_subnet.private[0].
- Plan only one part
terraform plan -target=module.vpc-target limits a plan to one resource or module. Use it rarely, for example to fix one broken piece, then run a full plan.
- Try expressions in the console
terraform consoleterraform console is a playground for expressions and functions, using your real variables. Great for testing cidrsubnet or for loops.
- Draw the dependencies
terraform graphterraform graph prints how resources depend on each other in DOT format. Paste it into a graph viewer to see the order Terraform uses.
Level 7: Quality & Cost Checks (Advanced)
Catch mistakes, security issues and surprise costs before anything is applied.
- Run the tests
terraform testterraform test runs .tftest.hcl files that plan or apply your module and check conditions, like unit tests for infrastructure.
- Lint the code
tflinttflint finds problems terraform validate misses, like an invalid instance type or unused variables.
- Scan for security issues
checkov -d .checkov checks your code against hundreds of security rules, like public S3 buckets or open security groups.
- Estimate the monthly cost
infracost breakdown --path .infracost reads your plan and estimates the monthly bill, so a reviewer sees the price of a change before it is applied.
- Detect changes in a script
terraform plan -detailed-exitcode-detailed-exitcode returns 0 when nothing changes, 2 when there are changes and 1 on error. Scheduled pipelines use it to detect drift.
Level 8: Terraform in CI (Advanced)
Run Terraform safely from a pipeline: no prompts, a saved plan and a reviewed apply.
- Init without questions
terraform init -input=falsePipelines cannot answer prompts. -input=false makes Terraform fail instead of waiting for an answer.
- Save the plan in CI
terraform plan -input=false -out=tfplanThe pipeline saves the plan to a file, a person reviews it, and the apply uses exactly that file. Nothing unexpected gets applied.
- Turn the plan into JSON
terraform show -json tfplanshow -json converts a saved plan to JSON so tools (policy checks, cost tools, PR comments) can read it.
- Apply the reviewed plan
terraform apply tfplanApplying a saved plan file does not ask for confirmation, because the plan was already reviewed.
- Outputs for the next job
terraform output -json-json prints outputs in a format the next pipeline step can read, for example the URL to run smoke tests against.
Level 9: Variables, Outputs & Secrets (Advanced)
Pass settings in safely and read results out for scripts and other tools.
- Set a variable from the environment
export TF_VAR_db_password=s3cretTerraform reads any TF_VAR_<name> environment variable. Good for secrets you don't want in files.
- Plan with a variables file
terraform plan -var-file=staging.tfvars -out=staging.tfplanKeep one .tfvars file per environment, and save the plan to a file.
- Read one output, raw
terraform output -raw db_endpoint-raw prints the value without quotes, ready to use in a shell script.
- Sensitive outputs
terraform outputOutputs marked sensitive = true are hidden in plan and apply output. Terraform still stores them in state, so protect the state file.
- Try an expression
echo 'upper(var.env)' | terraform consolePipe an expression into terraform console to test functions and variables without changing anything.
Level 10: Debugging Terraform (Advanced)
Find out why a plan or apply fails: logs, JSON validation and the state.
- Turn on debug logs
export TF_LOG=DEBUGTF_LOG=DEBUG prints every API call Terraform makes to AWS. TRACE shows even more.
- Save logs to a file
export TF_LOG_PATH=tf.logLogs are long. TF_LOG_PATH writes them to a file you can search.
- Find the failing call
grep UnauthorizedOperation tf.logSearch the log for the error from the cloud provider.
- Validate as JSON
terraform validate -json-json gives machine-readable results with the exact file and line of each error. CI tools use this.
- Download the state
terraform state pull > state.jsonstate pull prints the current state (even remote) as JSON. Look, but never edit it by hand.
- Lock providers for all platforms
terraform providers lock -platform=linux_amd64 -platform=darwin_arm64If teammates use Mac and CI uses Linux, the lock file needs hashes for each platform, or init fails in CI.
Level 11: Import & Refactor (Expert)
Bring existing cloud resources under Terraform and change code without destroying anything.
- Generate code for an import
terraform plan -generate-config-out=generated.tfWith an import block in your code, -generate-config-out writes the matching resource code for you.
- Find resources in state
terraform state list | grep aws_security_groupstate list plus grep finds resources fast in a big project.
- Apply one resource only
terraform apply -target=aws_security_group.web-target limits the apply to one resource. Use it to fix an emergency, not every day.
- Rebuild a broken resource
terraform plan -replace=aws_instance.web-replace forces Terraform to destroy and recreate one resource, e.g. a server that's misbehaving.
- Change provider source
terraform state replace-provider hashicorp/aws registry.terraform.io/hashicorp/awsWhen a provider moves to a new address, update the state to match.
Level 12: Remote State on AWS (Expert)
Store state in S3 with locking, so a whole team can work on the same infrastructure.
- Create the state bucket
aws s3 mb s3://akops-tf-stateState must live somewhere shared and safe, never on one laptop. An S3 bucket is the standard on AWS.
- Keep every version
aws s3api put-bucket-versioning --bucket akops-tf-state --versioning-configuration Status=EnabledVersioning keeps old copies of the state, so a bad apply can be undone.
- Block public access
aws s3api put-public-access-block --bucket akops-tf-state --public-access-block-configuration BlockPublicAcls=true,IgnorePublicAcls=true,BlockPublicPolicy=true,RestrictPublicBuckets=trueA public state file leaks every secret in it.
- Move your state into S3
terraform init -migrate-stateAfter adding the backend "s3" block (with use_lockfile = true for locking), -migrate-state copies your local state to S3.
- Check it worked
terraform state listThe state is now read from S3. Same resources, new home.
Level 13: Terraform with the AWS CLI (Expert)
Check who you are, find resources and confirm that Terraform built what you expected.
- Who am I?
aws sts get-caller-identityBefore any apply, confirm which AWS account and role you're using. Wrong account is a real and painful mistake.
- Which profile and region?
aws configure listconfigure list shows where your credentials and region come from.
- Find instances by tag
aws ec2 describe-instances --filters Name=tag:Env,Values=dev --query 'Reservations[].Instances[].InstanceId'--filters and --query find exactly what you need. Always tag resources with Env and Owner.
- Check the VPC
aws ec2 describe-vpcs --query 'Vpcs[].CidrBlock'Confirm the VPC Terraform made has the right CIDR.
- Apply without the prompt
terraform apply -auto-approve -var-file=dev.tfvars-auto-approve skips the yes prompt. Only use it in CI, after a reviewed plan.
- Destroy one thing
terraform destroy -target=aws_instance.web-target with destroy removes a single resource.
Level 14: Security & Policy as Code (Expert)
Scan Terraform for security mistakes and enforce company rules automatically.
- Scan the config with Trivy
trivy config .trivy config finds risky settings: public buckets, open security groups, missing encryption.
- Run Checkov on Terraform only
checkov -d . --framework terraform --compact--framework limits Checkov to Terraform checks. --compact keeps the output short.
- Plan to JSON
terraform show -json tfplan > plan.jsonPolicy tools read the plan as JSON, so they check what will really change.
- Test the plan against policy
conftest test plan.jsonconftest runs Rego policies (OPA) against the plan, e.g. 'every resource needs an Owner tag'.
- Check formatting everywhere
terraform fmt -check -recursive-check -recursive fails if any file in any folder isn't formatted. Perfect as the first CI step.
Level 15: Terraform at Scale (Expert)
Run many environments and modules cleanly, the way platform teams do.
- Run in another folder
terraform -chdir=envs/prod plan-chdir runs Terraform in a folder without cd. Each environment lives in its own folder.
- List workspaces
terraform workspace listWorkspaces keep separate states for the same code. The * marks the current one.
- Plan every environment
terragrunt run-all planTerragrunt wraps Terraform to keep backends and variables DRY and to run many modules at once.
- Write module docs
terraform-docs markdown table . > README.mdterraform-docs generates a README with every input and output of a module.
- Plan faster
terraform plan -parallelism=20-parallelism raises how many resources Terraform handles at once (default 10).