DevOps & Tools
Provision infrastructure as code with Terraform: HCL, state, modules, testing, CI/CD and security.
A path for engineers who manage cloud infrastructure with Terraform. It covers HCL, providers and resources, variables and outputs, the plan and apply workflow, state management and refactoring, modules, testing, running Terraform in CI/CD, scaling to many teams, security scanning and HCP Terraform. Each subject links the official documentation.
The subjects follow the roadmap.sh Terraform roadmap.
Terraform is HashiCorp's declarative infrastructure-as-code tool: you describe the desired resources in configuration files and Terraform works out the API calls to reach that state across clouds and SaaS providers. Since 2023 it ships under the Business Source License, and OpenTofu is the open-source fork.
Managing servers, networks and services through version-controlled definition files instead of console clicks. Changes go through review, environments become reproducible, and drift between what is running and what is written can be detected.
A single binary that reads .tf files, builds a dependency graph of resources, compares it with recorded state and real infrastructure, and applies the difference through provider plugins.
Configuration as code (Ansible, Chef, Puppet) manages what runs inside machines; infrastructure as code provisions the machines, networks and services themselves. They are often combined: Terraform creates a VM, a configuration tool sets it up.
Multi-cloud provisioning, reproducible environments per branch or team, self-service modules, managing SaaS such as DNS, monitoring or GitHub, and policy checks before changes land. One workflow covers all of them.
Install the binary from HashiCorp's package repositories, Homebrew or a zip download, then check terraform version. Teams usually pin the version with a version manager so everyone runs the same release.
Terraform configuration is written in HCL, a declarative language of blocks, arguments and expressions. Files ending in .tf in one directory form a single module, and their order inside the directory does not matter.
HashiCorp Configuration Language is shared by Terraform, Packer, Nomad and others. It is meant to be easy for humans to read and write; an equivalent JSON syntax (.tf.json) exists for generated configuration.
Blocks have a type and labels (resource "aws_s3_bucket" "logs" { ... }), arguments assign values, and expressions support references, string interpolation with ${}, conditionals, for expressions and built-in functions.
Providers are plugins that translate Terraform resources into API calls for a platform such as AWS, Azure, Kubernetes or Cloudflare. You declare which providers a module needs and their versions, then configure credentials and region.
The public index of providers and modules, with versioned docs for every resource and data source. Official, partner and community tiers tell you who maintains each one.
A provider block sets region, endpoints and auth; prefer environment variables or workload identity over hard-coded keys. Use alias to configure the same provider twice, for example two regions.
Declare sources and constraints in required_providers (for example ~> 5.0) and Terraform's own version in required_version. The .terraform.lock.hcl file records exact versions and checksums and should be committed.
terraform init prepares a working directory: it configures the backend, downloads providers into .terraform/ and installs modules. Re-run it when you change backends, providers or module sources; -upgrade picks newer versions within your constraints.
A resource block describes one infrastructure object Terraform manages, identified by type and local name, like aws_instance.web. Its arguments set desired configuration and its attributes, some known only after apply, can be referenced elsewhere.
On apply Terraform creates resources that are in config but not state, destroys those in state but not config, and updates the rest in place or replaces them when a changed argument forces a new object.
A resource moves through create, read (refresh), update and delete. Replacement is destroy-then-create by default; knowing which arguments force replacement, shown as # forces replacement in the plan, prevents surprise downtime.
Five special arguments built into Terraform itself rather than defined by a provider. They decide how many copies of a block exist, which provider configuration serves it, what it waits for, and how it is replaced.
Adds an explicit dependency when Terraform cannot infer one from references, such as an IAM policy that must exist before an app uses it. Overusing it makes plans more conservative and slower.
Creates N copies of a resource addressed by index (aws_instance.web[0]). Removing an item from the middle shifts indexes and recreates later instances, so use it mainly for on/off toggles like count = var.enabled ? 1 : 0.
Creates one instance per key of a map or set of strings, addressed by key (aws_iam_user.this["alice"]). Stable keys make adding and removing items safe; keys must be known at plan time.
Selects a non-default provider configuration for a resource, such as provider = aws.us_east_1 for a certificate that must live in a particular region. Modules receive aliased providers through the providers map.
Tunes replacement and updates: create_before_destroy avoids downtime, prevent_destroy guards critical data, ignore_changes tolerates drift from other tools, and replace_triggered_by ties replacement to another change.
Output values expose data from a module: to the CLI after apply, to a parent module, or to other configurations through remote state. They are the public interface of a module alongside its variables.
output "url" { value = aws_lb.main.dns_name, description = "..." }. Read them with terraform output, or terraform output -json and -raw for scripts.
Marking an output sensitive = true hides it from plan and apply logs, but the value is still stored in plain text in state and printed by terraform output -raw. It is redaction, not encryption.
precondition and postcondition blocks inside lifecycle or outputs assert assumptions, such as an AMI being for the right architecture, and fail the plan or apply with a clear message when they do not hold.
Input variables parameterise a module so the same code serves several environments, and local values name intermediate expressions. Give variables types, descriptions and validation so mistakes surface at plan time.
Declared with variable "name" {} and referenced as var.name. Values come, in rising precedence, from defaults, environment variables, terraform.tfvars, *.auto.tfvars, -var-file and -var flags.
Primitive types (string, number, bool) and structural ones like list(string), map(number) and object({ name = string, size = optional(number, 10) }). Precise types give earlier, clearer errors.
A validation block inside a variable holds a condition and an error_message, for example checking a CIDR with can(cidrhost(var.cidr, 0)). Bad input is rejected before anything is planned.
TF_VAR_name sets an input variable, handy in CI and for secrets. Others change Terraform itself: TF_LOG for debug logs, TF_CLI_ARGS_plan for default flags and TF_DATA_DIR for the working data directory.
.tfvars files hold name = value pairs per environment, such as prod.tfvars. terraform.tfvars and *.auto.tfvars load automatically; others are passed with -var-file. Keep secrets out of committed tfvars.
A locals block names expressions computed once and reused as local.name, such as common tags or derived names. Unlike variables they cannot be set from outside the module.
Fast checks that run before a plan: formatting, syntax and type validation, and linting for provider-specific mistakes. They belong in pre-commit hooks and the first stage of CI.
Rewrites files to the canonical style. Use terraform fmt -recursive locally and terraform fmt -check -recursive in CI to fail on unformatted code.
Checks syntax, references and types without contacting remote APIs or reading state. It needs an initialised directory; terraform init -backend=false is enough in CI.
A pluggable linter that catches what validate cannot: invalid instance types, deprecated syntax, unused declarations and naming conventions, with rulesets for AWS, Azure and Google Cloud.
Terraform records what it manages in a state file that maps resource addresses to real object IDs and caches their attributes. Plans are computed against it, so a lost or corrupted state means Terraform no longer knows what it owns.
A backend such as S3, Azure Storage, GCS or HCP Terraform stores state centrally so a team shares one copy. Other configurations can read its outputs with the terraform_remote_state data source.
Bring manually created infrastructure under management with an import block (Terraform 1.5+), which can also generate configuration with terraform plan -generate-config-out=file.tf. The older terraform import command still works.
State is shared, sensitive and critical, so treat it like a production database: remote, locked, versioned, encrypted and split into pieces whose blast radius you can live with.
Backends that support locking stop two runs from writing state at once. S3 now supports native lock files (use_lockfile), replacing the older DynamoDB table approach; never disable locking with -lock=false casually.
Turn on object versioning in your state bucket, or rely on HCP Terraform's state history, so you can roll back after a bad apply or accidental overwrite.
State holds every attribute in plain text, including generated passwords and keys. Encrypt the backend at rest, restrict read access tightly and never commit terraform.tfstate to Git.
Keep separate state per environment and per layer, such as network, data and apps, so a plan touches less, runs faster and a mistake cannot destroy everything. Share values via outputs or data sources.
The CLI can read state and surgically change it for refactors and recoveries. Prefer declarative moved, import and removed blocks, which are reviewed in a plan, over imperative terraform state commands.
terraform graph prints the dependency graph in DOT format; pipe it to Graphviz (| dot -Tsvg > graph.svg) to see why resources are ordered the way they are.
terraform state list prints every resource address in state, optionally filtered by prefix. Use it to find the exact address before running show, mv or rm.
terraform output reads the root module's outputs from state without planning. -json gives machine-readable output and -raw name prints a single string for shell scripts.
Renders either the whole current state or a saved plan file for humans. With -json it emits a machine-readable document that policy engines and cost estimators consume.
terraform state rm makes Terraform forget a resource without destroying it, for handing it to another configuration. A removed block with destroy = false is the declarative equivalent.
terraform state mv renames an address or moves it into a module so a refactor does not recreate the resource. A moved block in code does the same and documents it for everyone.
pull downloads remote state to stdout, useful for backups and inspection; push overwrites remote state with a local file and is a last-resort recovery tool, guarded by lineage and serial checks.
Rewrites the provider source recorded for resources, needed when a provider moves namespace or you switch to a fork, so Terraform does not try to recreate everything.
terraform force-unlock LOCK_ID releases a lock left behind by a crashed or cancelled run. Make sure no other run is actually in progress first, or you risk corrupting state.
Deploying is the plan-then-apply loop: preview exactly what will change, review it, and apply that reviewed plan. In teams this runs in CI or HCP Terraform rather than on laptops.
Refreshes state, compares it with config and shows creates, updates, replacements and destroys. Save it with -out=tfplan so apply runs exactly what was reviewed; -detailed-exitcode tells CI whether changes exist.
Executes changes, either from a fresh plan with a confirmation prompt or from a saved plan file without one. -auto-approve skips the prompt and should only be used in automation after review.
terraform apply -replace=aws_instance.web forces one resource to be destroyed and recreated, for example a broken VM. It replaces the deprecated terraform taint and shows the replacement in the plan first.
Short-lived environments should be torn down when no longer needed to save money. Destroying is also planned and reviewed, and prevent_destroy or deletion protection guard resources that must never go.
Destroys everything in the current state, in reverse dependency order. It is an alias for terraform apply -destroy; preview it with terraform plan -destroy, and use -target only for exceptional cases.
A module is a directory of Terraform files; calling it with a module block reuses that code with different inputs. Good modules encapsulate one concern behind a small set of variables and outputs.
The root module is the directory where you run Terraform; it owns the backend and provider configuration. Child modules are called from it and should receive providers rather than configure their own.
Call registry modules with source = "terraform-aws-modules/vpc/aws" and always pin version. Read their inputs and outputs, and check how actively they are maintained before depending on them.
Put related resources in a folder like modules/network with main.tf, variables.tf and outputs.tf, and call it with source = "./modules/network". Run terraform init after adding a module.
Variables are a module's parameters and outputs its return values. Pass outputs of one module into inputs of another to wire them together without hard-coding IDs.
Keep modules small and focused, avoid deep nesting, document inputs, use semantic versioning for shared modules, and do not wrap a single resource in a module just to rename its arguments.
Provisioners run scripts on a local or remote machine as part of creating or destroying a resource. HashiCorp treats them as a last resort because their effects are invisible to plans and failures leave resources tainted.
Only when no better option exists: prefer cloud-init or user_data, prebuilt images from Packer, or a provider resource. Legitimate uses include calling a tool that has no provider.
By default provisioners run after a resource is created; when = destroy runs them before deletion. A failed creation-time provisioner marks the resource tainted, and on_failure = continue overrides that.
Copies a file or directory from the machine running Terraform to the new resource over SSH or WinRM, configured with a connection block.
Runs a command on the machine running Terraform, with environment and interpreter options. Its side effects are not tracked in state, so make the command idempotent.
Runs commands or scripts on the created machine over SSH or WinRM. It needs network access and credentials from where Terraform runs, which is often awkward in CI.
Vendor-specific provisioners such as chef and puppet were removed in Terraform 0.15, and plugin-based custom provisioners are not a supported extension path. Write a provider or call a script through local-exec instead.
A data block reads existing information without managing it, such as the latest AMI, an existing VPC or the current account ID, and exposes it as data.type.name. Data is read during plan when possible, so missing objects fail early.
The templatefile(path, vars) function renders an external file with interpolation and directives, commonly for cloud-init scripts, policies and config files. Keep templates in a templates/ folder and use jsonencode for JSON rather than string templating.
CLI workspaces keep several state files for one configuration (terraform workspace new staging) and expose the name as terraform.workspace. They are useful for short-lived copies, but separate directories or backends are clearer for long-lived environments. HCP Terraform workspaces are a different, richer concept.
Running Terraform in a pipeline gives every change the same versions, credentials and review: format and validate, plan on pull requests with the plan posted for review, then apply the saved plan after merge. Set TF_IN_AUTOMATION and use short-lived cloud credentials via OIDC.
The hashicorp/setup-terraform action installs a pinned version; workflows plan on pull_request and apply on push to main, authenticating to clouds with OIDC rather than stored keys.
CircleCI's Terraform orb provides ready jobs for init, plan and apply; a manual approval job between plan and apply gives a review gate.
GitLab can host Terraform state over its HTTP backend and show plan summaries in merge requests. Its built-in Terraform templates moved to OpenTofu components, so check which your instance offers.
Self-hosted pipelines run Terraform in shell steps from a Jenkinsfile, with an input step for approval. Pin the Terraform binary in the agent image and keep credentials in the Jenkins credentials store.
Infrastructure code needs tests too, from cheap static checks to deploying real resources and asserting on them. Terraform's native terraform test framework (1.6+) runs .tftest.hcl files with run blocks and assertions, with mocking available for providers.
Test module logic without creating infrastructure: run blocks with command = plan assert on computed values, and mock_provider fakes provider responses so tests run fast and free.
Check that a module's interface holds its promises: variable validation, type constraints and pre- and postconditions reject bad inputs and verify the outputs consumers rely on.
Apply a module into a sandbox account, assert on real attributes and destroy it afterwards. terraform test with command = apply or Terratest in Go both handle the lifecycle.
Deploy a full stack and check it actually works, for example by making HTTP requests to the load balancer or connecting to the database. Slow and costly, so run it on a schedule or before releases.
Keep tests in a tests/ folder next to the module and include example configurations in examples/. Run them in CI on every change to a shared module before publishing a new version.
As configurations and teams grow, plans slow down and changes collide. Scaling means smaller states, consistent tooling, automation and visibility into cost before anything is applied.
Break a monolithic state into components by layer, team or lifecycle. Use moved, removed and import blocks, or terraform state mv between states, to migrate without recreating resources.
Terraform walks the graph concurrently, 10 operations at a time by default. Raise -parallelism to speed up large applies or lower it when provider APIs rate-limit you.
Standardise how changes flow: branch, plan in CI, review the plan, apply from automation, and promote the same module version through dev, staging and production.
Pin Terraform with required_version and a .terraform-version file read by tfenv, pin providers via the lock file, and pin module versions so upgrades are deliberate.
A thin wrapper by Gruntwork that keeps backend and provider config DRY across many small root modules and runs them in dependency order. Useful for many environments, at the cost of another tool to learn.
Estimates the monthly cost of a plan and posts the difference on pull requests, so expensive changes are visible during review.
Terraform holds the keys to your whole infrastructure. Protect credentials and state, scan configuration for misconfigurations before apply, and enforce policies so insecure changes cannot merge.
Never put secrets in .tf or committed tfvars. Read them at runtime from Vault or a cloud secret manager, mark variables sensitive, and prefer ephemeral or write-only values where providers support them so secrets stay out of state.
Policy as code checks plans before apply. HashiCorp's Sentinel and Open Policy Agent policies run in HCP Terraform and Enterprise to enforce rules like required tags or banned instance types.
Aqua Security's scanner covers containers, dependencies and IaC; trivy config . checks Terraform for misconfigurations and absorbed the former tfsec rules.
A static analyser from Prisma Cloud with hundreds of built-in policies for Terraform files and plan JSON, plus custom policies in Python or YAML. Easy to drop into CI.
Checkmarx's open-source scanner ("Keeping Infrastructure as Code Secure") with queries written in Rego for Terraform and many other IaC formats.
Tenable's open-source IaC scanner with policies written in Rego, covering Terraform plus Kubernetes and other formats. Check its maintenance status before adopting it; Trivy and Checkov are more active.
HCP Terraform (formerly Terraform Cloud) is HashiCorp's managed service for running Terraform: remote state, remote runs, team access control, policies and a private registry. Terraform Enterprise is the self-hosted edition.
Worth it when several people change shared infrastructure and you want state, locking, runs, approvals and audit in one place without building CI plumbing. Small solo projects are fine with a remote backend and CI.
Paid tiers add policy enforcement, SSO, audit logging, drift detection, private agents for isolated networks and self-hosting through Terraform Enterprise.
terraform login stores an API token for the CLI. Use team or organisation tokens for automation, and dynamic provider credentials (OIDC) so runs get short-lived cloud credentials instead of stored keys.
Connect a workspace to a GitHub, GitLab, Bitbucket or Azure DevOps repository; pull requests trigger speculative plans shown as checks, and merges queue real runs.
Hooks that call external services at stages of a run, such as cost estimation or a security scanner, and can block the apply if they fail.