DevOps.Academy
CoursesCurriculumInterview prepPricing
◔My learningSign in
DevOps.Academy

Free, hands-on DevOps lessons. Made with care in India.

System status

Learn

All coursesLinux roadmapCurriculumInterview questionsCheat sheetsMy learning

Academy

PricingCertificates

Legal

PrivacyTermsContact

devops.rajeev.pro

Terraform · revision

Terraform cheat sheet

Recall first: read each stage's one-line summary and try to remember its commands. Then open the stage to check yourself.

17 stages81 commands

01IntroductionInfrastructure as code describes resources in files kept in Git. Terraform reads the .tf files, downloads providers with init, compares code, state and reality in plan, and makes the change with apply.
  • brew tap hashicorp/tap && brew install hashicorp/tap/terraform

    Install Terraform on macOS from HashiCorp's tap

  • terraform version

    Check the installed version (the course needs 1.11 or newer)

  • terraform init

    Download the providers into .terraform/

  • terraform plan

    Preview every create, change and destroy without touching anything

  • terraform apply

    Show the plan again and apply it after you type yes

Remember

  • Read the summary line of every plan first; an unexpected number in "to destroy" is how outages start.
  • Terraform provisions through APIs; Ansible, cloud-init or an image configures inside the server.
  • Once Terraform manages something, change it only through Terraform.

Watch for terraform.tfstate can hold secrets in plain text. Never commit it.

Open the lesson: Infrastructure as code, and where Terraform fits →
02HCLHCL is blocks with labels, arguments set with name = value, and expressions. References between resources build the dependency graph, so the order you write things in does not matter.
  • terraform console

    Evaluate expressions interactively with the project's variables and state

  • [for s in ["web", "api", "db"] : "${s}-prod"]

    In the console, build a list with a for expression

  • cidrsubnet("10.0.0.0/16", 8, 2)

    In the console, carve the /24 subnet number 2 (10.0.2.0/24) from a /16

  • merge({ team = "shop" }, { env = "prod" })

    In the console, combine common tags with specific ones

Remember

  • A resource address is type.name, such as local_file.inventory, unique within the module.
  • Square brackets in a for expression build a list; curly braces build a map.
  • null means leave the argument unset.

Watch for Both results of a conditional (cond ? a : b) must have the same type.

Open the lesson: HCL: the Terraform language →
03ProvidersA provider is a plugin that knows one platform's API. required_providers says which provider and which versions; the provider block says how to configure it, with an alias for a second region.
  • terraform providers

    Show which providers the configuration requires and their constraints

  • terraform init -upgrade

    Move to the newest provider versions the constraints allow

Remember

  • ~> 2.9 allows >= 2.9 and < 3.0; ~> 2.9.0 allows only 2.9.x patches.
  • Resources pick a non-default configuration with provider = aws.<alias>.
  • Pin Terraform itself with required_version.

Watch for Never put access keys in a provider block; they end up in Git history and in state.

Open the lesson: Providers and version pinning →
04Project initializationterraform init sets up the backend, downloads modules and providers, and writes .terraform.lock.hcl with the exact versions and hashes. Commit the lock file; never commit the .terraform/ cache.
  • terraform init

    First time, and after changing providers, modules or the backend

  • terraform init -upgrade

    Upgrade providers and modules within the constraints and update the lock file

  • terraform init -reconfigure

    Use changed backend settings and ignore the old ones

  • terraform init -migrate-state

    Copy existing state to a new backend, for example local to S3

  • terraform init -backend-config=prod.hcl

    Pass backend settings per environment

  • terraform providers lock -platform=linux_amd64 -platform=darwin_arm64 -platform=windows_amd64

    Add lock file hashes for teammates on other operating systems

  • du -sh .terraform

    See how big the provider cache is

Remember

  • The constraint says what is allowed; the lock file says what is actually used.
  • Ignore .terraform/, *.tfstate, *.tfstate.* and *.tfplan in .gitignore.
  • init is safe to run as often as you like.

Watch for Choosing -reconfigure when you meant -migrate-state can leave an empty state. Back up first.

Open the lesson: terraform init and the lock file →
05ResourcesEach plan compares config, state and the real object, then creates, updates in place, replaces or destroys. count makes copies by position, for_each one per key, and lifecycle protects what matters.
  • terraform plan -var='users=["ravi","meera"]' -no-color

    See how count and for_each react when the first user is removed

  • terraform destroy -auto-approve -var-file=dev.tfvars

    Watch prevent_destroy stop the whole destroy

  • terraform validate

    Catch duplicate resource names after a copy-paste

Remember

  • -/+ means replace; find the argument marked # forces replacement before approving.
  • Use count for N identical things or a 0/1 switch, for_each for anything with a name.
  • create_before_destroy avoids downtime on replace; prevent_destroy guards stateful resources.
  • depends_on is only for dependencies no reference shows.

Watch for Removing the first item from a count list replaces every later item and destroys the last index.

Open the lesson: Resources: count, for_each and lifecycle →
06Variables & outputsVariables are a configuration's inputs, locals its internal names, outputs its return values. Types and validation reject bad input early; preconditions and postconditions check assumptions.
  • terraform plan -var-file=dev.tfvars

    Plan with one environment's values

  • terraform plan -var="env=test"

    Pass one value on the command line (here, to see validation fail)

  • terraform output

    Print every output after apply

  • terraform output -json server_files

    Print one output as JSON for scripts

  • terraform output -raw url

    Print a plain string output, for example in a deploy step

Remember

  • Precedence, lowest to highest: default, TF_VAR_, terraform.tfvars, *.auto.tfvars, -var and -var-file.
  • terraform.tfvars and *.auto.tfvars load automatically; other tfvars need -var-file.
  • A check block only warns; validation, preconditions and postconditions block.

Watch for Keep secrets out of tfvars files; pass them as TF_VAR_ variables from the CI secret store.

Open the lesson: Variables, locals and outputs →
07Format & validateThree fast checks with no cloud credentials: terraform fmt for style, terraform validate for structure against the provider schemas, and TFLint for values and practice, such as a bad instance type.
  • terraform fmt

    Rewrite files in the official style and list the ones changed

  • terraform fmt -check -recursive

    Change nothing and exit non-zero if any file needs formatting (for CI)

  • terraform fmt -diff

    Show what formatting changed

  • terraform init -backend=false -input=false

    Install providers for validate without touching the real state

  • terraform validate

    Check syntax, argument names, references and types

  • tflint --init

    Download the TFLint rule plugins set in .tflint.hcl

  • tflint --format=compact

    Lint the configuration, one finding per line

Remember

  • Run them in order: fmt, then validate, then tflint.
  • validate needs init first, because argument names come from the provider schemas.
  • tflint exits 2 when it finds issues, so CI fails.

Watch for validate passes instance_type = "t3.mirco"; only TFLint's AWS ruleset knows it isn't real.

Open the lesson: fmt, validate and TFLint →
08StateState maps each address in the code to the real object it created. Teams keep it in a remote backend with locking, encryption and versioning, and change it with moved, import and removed blocks.
  • terraform state list

    List every resource address in state

  • terraform state show local_file.web

    Print what Terraform recorded for one resource

  • terraform init -migrate-state

    Copy existing local state to the new remote backend

  • terraform force-unlock 8da76c6d-c1c4-4393-d885-86b285980ed6

    Release a stale lock by its ID, only when nothing is running

  • terraform plan -generate-config-out=generated.tf

    Draft resource code for an import block

  • terraform state rm random_integer.app_port

    Make Terraform forget a resource and leave the real object running

  • terraform state pull > backup.tfstate

    Back up state before any risky change

Remember

  • S3 backend: encrypt = true and use_lockfile = true; the DynamoDB table is deprecated.
  • A moved block renames without a destroy and is reviewed in a pull request.
  • After an import, the next plan should say No changes.
  • Turn on bucket versioning before the first apply; it is your undo button.

Watch for Never use -lock=false on shared state, and never edit the JSON by hand.

Open the lesson: State: Terraform's memory →
09Plan, apply, destroyPlan refreshes, compares and prints the actions. Applying a saved plan does exactly what was reviewed. Drift is any change made outside Terraform; destroy runs in reverse dependency order.
  • terraform plan -out=tfplan

    Save the plan to a file

  • terraform show tfplan

    Print a saved plan again for review

  • terraform apply tfplan

    Apply exactly the saved plan, with no prompt

  • terraform plan -refresh-only

    Show only the drift

  • terraform apply -refresh-only

    Accept drift into state without changing anything real

  • terraform apply -auto-approve -replace=random_pet.server

    Force a fresh object even though the code didn't change

  • terraform plan -destroy

    Preview a teardown

  • terraform destroy

    Destroy everything in the configuration after you type yes

Remember

  • (known after apply) means the value doesn't exist yet.
  • A stale saved plan is refused; plan again and read the new one.
  • -replace replaced terraform taint.

Watch for -target applies a partial plan. Use it only to recover, then run a full plan straight after.

Open the lesson: Plan, apply and destroy →
10ModulesA module is a folder with inputs and outputs, like a function. The root module calls child modules with a module block; registry and Git modules are pinned so a release reaches prod only on purpose.
  • terraform init

    Install modules after adding a module block or changing its source or version

  • terraform state list

    See resource addresses that include the module name

  • terraform output

    Read the values the root module exposes from its modules

  • terraform init -upgrade

    Fetch a new module version after changing it

Remember

  • Read a module output as module.<name>.<output>.
  • version works only for registry sources; Git sources pin with ?ref= a tag.
  • Child modules declare required_providers but have no provider block.

Watch for "Module not installed" means you added a module block without re-running terraform init.

Open the lesson: Modules: reusable infrastructure →
11Data sources & templatesData sources read things Terraform doesn't manage, such as the latest Ubuntu AMI. templatefile() renders config files from .tftpl templates. Provisioners are a last resort.
  • terraform apply -auto-approve && cat out/nginx.conf

    Render the template and check the generated Nginx config

Remember

  • Reference a data source as data.<type>.<name>.<attribute>; plan shows it as <= read.
  • In templates, ${...} inserts a value, %{ for } loops and ~ strips whitespace.
  • Use user_data, Packer, Ansible or a pipeline step instead of provisioners.

Watch for Blank lines in rendered output usually mean a ~ is missing from a %{ } directive.

Open the lesson: Data sources, templates and provisioners →
12EnvironmentsEvery environment needs its own state. Workspaces give named states inside one configuration; a folder per environment gives each its own backend, credentials and visible settings.
  • terraform workspace show

    Print the current workspace

  • terraform workspace new dev

    Create a workspace and switch to it

  • terraform workspace list

    List workspaces; * marks the current one

  • terraform workspace select dev

    Switch to an existing workspace

  • terraform workspace delete prod

    Delete a workspace (refused while its state has resources)

Remember

  • A new workspace starts with an empty state.
  • Use workspaces for short-lived copies, folders for dev, staging and prod.
  • terraform.workspace holds the current name.

Watch for Workspaces share one backend and credentials, and it's easy to apply in the wrong one.

Open the lesson: Environments: workspaces or folders →
13CI/CD integrationChecks and plan run on every pull request; after merge the pipeline plans again and applies that saved plan behind an approval, with short-lived OIDC credentials instead of stored keys.
  • terraform plan -detailed-exitcode

    Exit 0 for no changes, 1 for an error, 2 for changes

  • terraform init -input=false

    Initialise without waiting for a prompt nobody will answer

  • terraform plan -input=false -no-color -out=tfplan

    Make the plan the approver reads and the apply job uses

  • terraform show -no-color tfplan > plan.txt

    Write a readable plan, with sensitive values redacted, for review

  • terraform apply -input=false tfplan

    Apply the reviewed plan, nothing else

Remember

  • Set TF_IN_AUTOMATION=1 for shorter messages in pipelines.
  • A scheduled plan that alerts on exit code 2 is a simple drift detector.
  • The plan role still writes the lock object; it must not write state or change infrastructure.

Watch for Plan files contain secrets. Keep artifact retention short and never post the binary plan publicly.

Open the lesson: Terraform in CI/CD →
14Testingterraform test runs .tftest.hcl files: run blocks plan or apply the module and check assertions. expect_failures proves validation works. Integration tests with Terratest prove real infrastructure.
  • terraform test

    Run every .tftest.hcl file and destroy what apply runs created

Remember

  • command = plan runs create nothing; command = apply runs create real resources.
  • mock_provider "aws" {} lets apply-mode tests run with no cloud account.
  • Start with a test that fails, so you know it protects something.

Watch for Integration tests cost money and time. Run them on a schedule, in a separate test account.

Open the lesson: Testing Terraform code →
15Scaling TerraformSplit a big state by how often things change and who owns them. Share values through outputs, tag lookups or published parameters; Terragrunt removes repetition and Infracost prices each plan.
  • terraform state list | wc -l

    Count the resources in a state

  • infracost breakdown --path .

    Show the monthly cost of the whole configuration

  • infracost diff --path . --compare-to base.json

    Show the cost change versus the main branch

Remember

  • Signs to split: slow plans, everyone waiting on one lock, small changes touching unrelated systems.
  • Outputs are the contract between states: add freely, remove or rename only with warning.
  • Terragrunt pays off with many small configurations across environments and accounts.

Watch for terraform_remote_state downloads the whole state, so readers can see every secret in it.

Open the lesson: Scaling Terraform: split state, Terragrunt, Infracost →
16Securitysensitive only redacts output; state and plans still hold the value. Ephemeral values and write-only arguments keep secrets out of state, Trivy or Checkov scans the code, and policy checks the plan.
  • read -rs TF_VAR_db_password && export TF_VAR_db_password

    Enter a secret without echoing it or saving it to shell history

  • terraform output -raw db_password

    Proof that a sensitive output still prints in clear

  • trivy config --quiet --severity HIGH,CRITICAL .

    Scan Terraform files for insecure settings before apply

  • checkov -d .

    Scan with Checkov instead of Trivy

  • terraform show -json tfplan > plan.json

    Export the plan as JSON for policy tools

  • conftest test plan.json

    Check the plan against OPA Rego policies

Remember

  • Never pass secrets with -var; they land in shell history and the process list.
  • Root module outputs can't be ephemeral; only child-module outputs can.
  • tfsec now lives on in trivy config.

Watch for A suppressed finding without a reason is a finding. Review suppressions like code.

Open the lesson: Terraform security: secrets, scanning and policy →
17Capstone projectFour modules (VPC, security groups, app, ALB) called by dev and prod folders with separate state. Track A proves it without AWS: fmt, TFLint, Trivy, mocked tests and offline plans.
  • terraform fmt -check -recursive

    Check formatting across the modules and environments

  • tflint --recursive --format=compact

    Lint every folder in the project

  • terraform test

    Run the module tests against a mocked AWS provider

  • terraform init -reconfigure

    Switch to the local backend from the offline override file

  • terraform plan -var-file=dev.tfvars -var="ami_id=ami-0123456789abcdef0" -out=dev.tfplan

    Plan dev offline with no data source calls

  • terraform apply dev.tfplan

    Track B only, apply the saved dev plan to AWS

  • curl "$(terraform output -raw url)"

    Check the load balancer answers

  • terraform destroy -var-file=dev.tfvars

    Tear dev down the same day, then verify nothing is left

Remember

  • Files ending in _override.tf merge over the real configuration.
  • Prod plans 3 more resources than dev: the NAT gateway, its Elastic IP and the private route.
  • Set a budget alarm before applying anything to AWS.

Watch for The ALB, NAT gateway and instances bill by the hour even when idle; a leftover Elastic IP is billed too.

Open the lesson: Capstone: AWS infrastructure with Terraform →
← Back to the Terraform course