Terraform Professional cheat sheet
Terraform Professional · Keep the key ideas within reach.
Author and refactor Terraform configuration
forexpressions build lists with[for s in var.list : upper(s)]and maps with{for k, v in var.map : k => upper(v)}; anifclause filters elements.Splat expressions
[*]project a list attribute across all instances;one()safely returns a single element or null from a zero/one-element collection.A
dynamicblock usesfor_eachto generate repeated nested blocks;iteratorrenames the temporary variable andcontentdefines each block body.Variable
validationrequires aconditionthat evaluates to bool pluserror_message; in current Terraform the condition may reference only that variable.Lifecycle settings include
create_before_destroy,prevent_destroy,ignore_changes,replace_triggered_by, andprecondition/postcondition.Use
movedblocks to change a resource or module address without destroy/create; useimportblocks plus-generate-config-outto adopt existing objects.try()returns the first argument that evaluates without error;can()returns bool for whether an expression succeeds;coalesce()returns the first non-null/non-empty argument.depends_oncreates explicit whole-object dependencies for resources or modules; it does not accept arbitrary value expressions.
Manage Terraform state, backends, and state operations
State maps declared resources to real remote objects and stores attribute values; it may contain sensitive values in plaintext even when variables are marked sensitive.
The S3 backend supports state locking through
dynamodb_tableor newer lockfile support, plusencrypt,bucket,key, andregionsettings.terraform state listlists addresses,state showprints one object,state mvchanges addresses, andstate rmremoves an object from state without destroying it.terraform importandimportblocks adopt existing infrastructure; importing populates state but does not author configuration unless-generate-config-outis used.terraform apply -refresh-onlyorplan -refresh-onlyreconciles state with remote objects without applying configuration changes.Partial backend configuration uses
terraform init -backend-config=...;-reconfigureignores prior backend state, while-migrate-stateattempts to copy it.terraform_remote_statereads only declared outputs from another state; it requires access to that backend and should not be used to fetch resource attributes.terraform workspacemanages named state instances; in thelocalbackend workspaces are directories, while remote backends use workspace-specific state keys.terraform force-unlock <LOCK_ID>clears a stuck lock only after confirming no operation is still running.
Design, publish, and consume reusable modules
A
moduleblock requiressource; registry sources accept aversionconstraint, andcountorfor_eachinstantiate multiple module instances.Module
for_eachkeys must be known at plan time; addresses appear asmodule.name["key"], whilecountaddresses use integer indexes.required_providersdeclares provider source addresses and version constraints;configuration_aliasesdeclares additional provider configurations a module expects.Callers pass provider configurations through the module block's
providersmap; reusable child modules should not contain their ownproviderblocks.terraform initdownloads modules into.terraform/modules;terraform get -updaterefreshes installed modules without a full init.Registry modules use the address form
namespace/name/provider; publishing requires semantic version tags such asv1.2.3.Module outputs are the only values callers can reference; mark outputs
sensitivewhen they expose secrets.Prefer small composable modules with explicit variables and outputs; avoid hidden dependencies on root-level resources.
Collaborate using HCP Terraform / Terraform Enterprise
The
cloudblock configures HCP Terraform or Terraform Enterprise integration withorganizationand eitherworkspaces.nameorworkspaces.tags.Workspace run modes include CLI-driven, VCS-driven, and API-driven; remote runs execute plan and apply in HCP Terraform's environment.
A VCS-driven run queues when the connected repository changes; workspace settings control auto-apply versus manual confirmation.
Variable sets are reusable collections of Terraform and environment variables applied to projects or workspaces; workspace-specific variables can override values.
Run triggers queue a dependent workspace's run after a source workspace applies successfully, chaining infrastructure layers.
Policy checks evaluate Sentinel policies between plan and apply; failed policies can block the run depending on policy enforcement level.
Run tasks call external systems before or after plan/apply to perform custom validation or approval checks.
Authenticate the CLI with
terraform loginor aTF_TOKEN_<hostname>environment variable for remote workspaces and private registries.
Manage providers, dependency locking, and Terraform version constraints
.terraform.lock.hclrecords selected provider versions and checksums; commit it to version control so installs are reproducible across machines and CI.terraform providers lock -platform=...adds checksums for additional operating systems and architectures to the lock file.The
~>pessimistic constraint allows patch updates within a minor version with two segments, or minor updates within a major version with one segment.A provider source address has the form
[hostname/]namespace/type, for exampleregistry.terraform.io/hashicorp/aws, and belongs inrequired_providers.required_versionconstrains the Terraform CLI version;required_providersconstrains each provider withsourceandversion.terraform init -upgradere-selects newer module and provider versions that still satisfy constraints and updates the lock file.terraform providersdisplays the provider dependency tree;terraform providers mirrorcopies providers into a local filesystem mirror.TF_PLUGIN_CACHE_DIRorplugin_cache_dirreuses downloaded provider packages across configurations.
Secure and test configurations
sensitive = trueon variables and outputs redacts values in CLI output; it does not encrypt state or prevent storage of the value in state.The
nonsensitive()function reveals a sensitive value intentionally;sensitive()marks an expression as sensitive.Ephemeral variables and resources in Terraform 1.10+ keep values out of state and plan files, which suits short-lived credentials.
Native testing uses
.tftest.hclfiles withrunblocks,command = plan|apply,assertconditions, variables, and provider mocks.terraform show -jsonconverts a saved plan or state to JSON for policy engines such as OPA, Conftest, or custom validators.Terraform Enterprise and HCP Terraform support Sentinel policy as code; enforcement levels determine whether violations block applies.
checkblocks evaluate assertions during plan and apply and report warnings without failing the operation.preconditionandpostconditionblocks fail an operation when conditions are false;postconditioncan referenceselfattributes.