Cheat Sheet 2: Terraform Fundamentals
terraform block
terraform {
required_version = "~> 1.12.0" # CLI version
required_providers {
random = { source = "hashicorp/random", version = "~> 3.7" } # provider version
}
}Constraint operators: = (or none) exact · != exclude · > >= < <= compare · , AND
~>: only the rightmost given component may increase.
~> 3.7→ ≥ 3.7, < 4.0~> 3.7.0→ ≥ 3.7.0, < 3.8.0
Pre-releases match only exact constraints. The root module uses upper bounds; reusable modules use >= minimums.
Source address: [hostname/]namespace/type. The hostname defaults to registry.terraform.io.
Registry tiers: Official (HashiCorp) · Partner · Community
Lock file (.terraform.lock.hcl)
- Records selected provider version, constraints, and hashes. Providers only, no modules.
- Written by
terraform init. Commit it. Ignore.terraform/. - A constraint excludes the locked version → init fails → run
terraform init -upgrade. -upgradepicks the newest version allowed (possibly a downgrade) and also upgrades modules.terraform providers lock -platform=...adds hashes for other operating systems and architectures.
Provider configurations
- A
providerblock with no alias is the default. Only one default per provider per module. alias = "west"creates another configuration, referenced asaws.west(not a string).- Choose a configuration per resource with
provider = aws.west. - Child modules inherit default configurations only. Pass aliases with
providers = { aws = aws.west }, and declareconfiguration_aliases = [aws.x]in the child.
State (terraform.tfstate)
- Purpose: mapping, metadata (dependencies, provider configuration), performance, collaboration.
- Contains every attribute and output in plaintext JSON, plus serial and lineage.
sensitive = truehides values in output, but they are still in state.- Refreshed by default on plan and apply. Never hand-edit it.
- Deleting state doesn't delete infrastructure.
Commands: terraform init · init -upgrade · terraform providers · terraform providers lock · terraform version · terraform state show <addr>
Errors to recognize:
Unsupported Terraform Core version→required_versionisn't met- "locked provider … does not match configured version constraint" → run
init -upgrade - Duplicate provider configuration → two un-aliased blocks for the same provider
Module 2 self-check
Module 2 self-check.
- Objectives 2a (lessons 2.2–2.3, Q1–Q6), 2b (lesson 2.1, Q7), 2c (lesson 2.4, Q8–Q9), and 2d (lesson 2.5, Q10, lab steps 8–9) are all covered.
- The HCL uses valid arguments.
alias-only provider blocks andconfiguration_aliasesare valid syntax, andfmtalignment was applied. - Lab error messages are described rather than quoted verbatim where exact wording can vary between patch releases.
- All answers are rechecked against documented constraint, lock-file, and provider-inheritance behavior.