Skip to content
Cloud, DevOps & Infrastructure

Terraform interview questions and answers

77 questions, 39 with code. About 6 h 42 min to read them all.

By TestLab · Updated

Plan for an interview
77 questions

Track what you know and what to revise.

Sign in to track progress

You can open a few full answers without signing in. Sign in to read all

1

What are the benefits of infrastructure as code with Terraform?

Infrastructure as code (IaC) manages infrastructure through versioned, declarative configuration instead of manual console changes or ad hoc scripts. Terraform expresses cloud and on-premises resources as code, making environments repeatable, reviewable, auditable, and easier to recover through automation.

Read full answer

Applies toTerraform 1.10+ (Terraform 1.x), AWS provider 5.x, and OpenTofu 1.x

Core Concept

IaC represents resources, their relationships, and their desired configuration in files that can be stored in Git and processed by automation. Terraform reads that configuration, compares it with the current infrastructure, and produces a plan describing the actions required to reach the desired state.

This model does not eliminate change management. It makes changes:

  • Declarative: developers specify the desired result rather than every API call.

  • Reviewable: changes can be peer-reviewed before execution.

  • Repeatable: the same configuration can create equivalent environments.

  • Auditable: version history connects infrastructure changes to commits and approvals.

  • Recoverable: an environment can be reconstructed from configuration and state.

Terraform Building Blocks

  • Providers are plugins that expose resources and data sources for platforms such as AWS, Azure, Google Cloud, or Kubernetes.

  • Resources represent manageable objects, such as a VPC, virtual machine, database, or security group.

  • Data sources read existing information without managing its lifecycle.

  • Variables parameterize configurations for environments and reusable modules.

  • Outputs expose selected values, such as a load balancer address, to other configurations.

  • State records the mapping between Terraform configuration addresses and real infrastructure objects.

  • Modules package reusable infrastructure and are commonly consumed from the Terraform Registry or private repositories.

  • Workspaces maintain separate states for environments such as development and production; they are not security boundaries or substitutes for separate accounts and backend permissions.

  • Lifecycle rules control replacement and destruction. Use prevent_destroy for critical resources and create_before_destroy only where replacement ordering requires it.

  • Import brings existing infrastructure under Terraform management, but does not generate configuration. Write the resource configuration first, run terraform import, and then verify with a plan.

Benefits and Trade-offs

Capability Manual infrastructure Infrastructure as code
Consistency Depends on operator knowledge Defined by reusable configuration
Change review Often informal Pull requests and approval gates
Auditability Console logs and tickets Code history, plans, and provider logs
Recovery Slow and error-prone Repeatable automation and state-backed reconstruction
Scaling Duplicated work Parameterized modules and automation
Visibility State can be unclear Plans expose intended changes

IaC also introduces costs: state must be protected, provider APIs impose rate limits, configuration can become complex, and poorly designed modules can create fragile dependencies. IaC should not replace cloud-native monitoring, backup systems, incident response, or governance; it manages infrastructure while other systems operate it.

Minimal Terraform Example

terraform {
  required_version = ">= 1.10, < 2.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "us-east-1"
}

resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"

  tags = {
    Name = "example-main"
  }
}

Initialize the provider plugins, validate the configuration, and review the exact changes before applying them:

terraform init
terraform fmt -check -recursive
terraform validate
terraform plan -out=tfplan
terraform show tfplan
terraform apply tfplan

A saved plan is immutable and should be applied only after review. Avoid routine use of terraform destroy; production removal should require explicit approval and a recovery plan.

Production and CI/CD Workflow

A typical pipeline initializes Terraform, formats and validates the configuration, runs security and policy checks, and creates a plan artifact. An authorized environment then applies the exact reviewed plan. Production pipelines should separate plan and apply credentials, require approval, and restrict who can modify pipeline configuration.

During upgrades:

  • Review provider and Terraform release notes before changing version constraints.

  • Run terraform plan against a representative environment.

  • Test replacement behavior for databases, networking, and stateful resources.

  • Upgrade in controlled stages rather than changing every environment simultaneously.

  • Monitor provider API errors, Terraform logs, CloudTrail events, service health, and application metrics.

Backups remain essential. IaC reconstructs declared resources, but it does not necessarily reproduce data, backups, or resources managed outside Terraform.

State Safety, Testing, and OpenTofu

Store production state in a remote backend with encryption, versioning, locking, audit logging, and least-privilege access. Separate state by environment and trust boundary. Never commit state to Git.

State can contain sensitive values even when outputs are marked sensitive. Use a secret manager for credentials and avoid placing secrets directly in Terraform configuration.

Use terraform plan -refresh-only to inspect drift without proposing configuration changes. Investigate unexpected drift rather than automatically accepting it. ignore_changes can conceal real operational problems and should be narrowly scoped.

Terraform 1.6+ also supports native tests through .tftest.hcl files and terraform test. Complement these with plan checks, policy scanning, and tests in a disposable environment.

OpenTofu is an open-source fork with a similar HCL and provider model. It can run many equivalent configurations, but provider compatibility, backend locking, state migration, and tooling must be validated before adopting it in production.

2

What is Terraform and how does it manage infrastructure as code?

Terraform is an infrastructure as code tool that declares desired infrastructure in HCL, compares it with recorded state, builds a dependency graph, and uses provider plugins to create, update, or destroy resources through each platform’s API. It is declarative rather than continuously reconciling: drift is normally detected when a later plan refreshes state and compares it with the real platform.

Read full answer

Applies toTerraform 1.x (AWS provider 5.x where AWS-specific details are mentioned; S3 `use_lockfile` requires Terraform 1.10+)

Core Concepts

Terraform separates infrastructure into reusable building blocks:

Element Purpose
Resource Declares a manageable object, such as aws_vpc or aws_subnet
Data source Reads existing information without managing it, such as an AMI or availability zone
Variable Supplies input values to make configurations reusable
Output Exposes selected values for other modules or automation
Module Packages related resources, variables, and outputs into a reusable interface
Provider Implements platform-specific operations, usually through CRUD APIs
State Records resource IDs and metadata needed to map real infrastructure to configuration

During plan, Terraform evaluates expressions, reads data sources, refreshes relevant state, and constructs a dependency graph. It then calculates the actions required to reach the declared configuration. During apply, it executes that graph in dependency order through providers.

State and Production Safety

State is Terraform’s record of resource bindings and metadata; it is not a substitute for version-controlled configuration. State may contain sensitive values returned by providers, including generated credentials or resource properties.

Production practices should include:

  • Store state in an encrypted remote backend with restricted access.

  • Use locking to prevent concurrent operations from corrupting state.

  • Enable backend versioning or regularly copy state to a protected backup location.

  • Keep configuration and provider versions in source control, including .terraform.lock.hcl.

  • Review every plan, especially replacements, destroys, IAM changes, and networking changes.

  • Store secrets outside Terraform configuration using a secret manager or CI identity mechanism.

  • Remember that sensitive = true only redacts display output; it does not encrypt state.

With the S3 backend, use_lockfile = true provides S3-native locking on Terraform 1.10+. Older Terraform 1.x releases can use the backend’s dynamodb_table locking option. The identity running Terraform also needs explicit state and lock-object permissions.

Workflow and Commands

A typical production sequence is terraform init, terraform fmt -check -recursive, terraform validate, terraform plan -out=tfplan, and terraform apply tfplan. terraform plan refreshes state by default; use -refresh=false only when refresh is intentionally controlled, because stale state can produce an unsafe plan. Saved plan files can contain sensitive information and should be treated as protected build artifacts.

For adopting existing infrastructure, use terraform import RESOURCE_ADDRESS RESOURCE_ID. Terraform 1.5+ also supports configuration-driven import blocks. Import records an object in state; it does not generate the corresponding resource configuration.

Modules, Testing, and CI/CD

Modules should have narrow inputs and outputs, use clear ownership boundaries, and follow semantic versioning. Pin module and provider versions for production to avoid unexpected upgrades.

Terraform 1.6+ provides terraform test with .tftest.hcl files. These tests can assert planned values and outputs or use mock providers. Provider acceptance tests are also valuable because they exercise real APIs, but they require credentials, cost, and cleanup.

In CI/CD, authenticate to the cloud using short-lived OIDC credentials rather than static access keys, use a separate state workspace or state key for each environment and pipeline, run formatting, validation, policy checks, and tests before planning, save plans as protected artifacts, require approval before applying, and avoid applying an old plan after unrelated state or configuration changes.

OpenTofu is an independently developed open-source fork offering a similar HCL and provider workflow. Pin and test it separately; do not assume every Terraform CLI, testing, or backend option is identical.

Operational Pitfalls

  • Partial failure: An apply can stop after creating some resources because of quotas, permissions, or provider errors. Inspect state before retrying.

  • Unexpected replacement: Changes to immutable fields can destroy and recreate resources. Review replacement actions carefully.

  • Lock contention: A stale lock requires investigation before removing it; never disable locking to bypass an active operation.

  • Dependency cycles: Restructure resources or split modules rather than forcing invalid dependency relationships.

  • Provider throttling: Retry through CI and request quota increases before broad parallel deployments.

  • Configuration drift: Run scheduled plans and monitor infrastructure outside Terraform for unauthorized or unexpected changes.

  • Upgrades: Read provider changelogs, test upgrades in staging, and use terraform init -upgrade explicitly rather than silently changing versions.

3

How do Terraform, CloudFormation, Pulumi, and Ansible differ?

The core difference is their infrastructure as code models: Terraform, CloudFormation, and Pulumi are primarily declarative provisioning systems, while Ansible is primarily an automation and configuration-management tool. Terraform is cloud-agnostic, CloudFormation is AWS-native, and Pulumi provides infrastructure code through general-purpose programming languages.

Read full answer

Applies toTerraform 1.x with AWS provider 5.x; AWS CloudFormation; Pulumi 3.x; Ansible Core 2.x

Conceptual Model

  • Terraform: Describes resources in HCL using providers. It reads current infrastructure from state, compares it with the configuration, creates a plan, and applies changes. It supports multiple clouds through providers and AWS through the AWS provider 5.x.

  • CloudFormation: Uses YAML or JSON templates to provision AWS resources. CloudFormation maintains service-managed state, detects drift, and evaluates changes before an update. It integrates directly with IAM, StackSets, Change Sets, and other AWS governance features.

  • Pulumi: Uses languages such as TypeScript, Python, Go, C#, Java, or YAML through Pulumi YAML. It follows a desired-state model like Terraform but allows ordinary programming constructs, functions, loops, and strongly typed resource definitions.

  • Ansible: Executes tasks against an inventory. Provisioning modules can call cloud APIs, install packages, configure servers, and orchestrate workflows. Its convergence model is useful for changing existing systems, but it does not maintain a complete infrastructure graph in the same way as the other tools.

Feature Comparison

Area Terraform CloudFormation Pulumi Ansible
Primary role Declarative provisioning AWS provisioning Declarative provisioning through code Automation and configuration management
Language HCL YAML, JSON Several programming languages; YAML YAML
Cloud scope Multi-cloud AWS only Multi-cloud Broad platform and cloud support
State External, usually remote Managed by AWS External checkpoint Inventory and execution context; no equivalent infrastructure state
Planning terraform plan Change Sets pulumi preview Check mode, but not a complete infrastructure diff
Reuse Modules and provider packages Templates, nested stacks, StackSets Packages, components, policies Roles, playbooks, collections
Drift detection Requires refreshed state and plan review Built-in drift detection Requires refreshing and previewing Re-runs tasks toward the task’s desired condition
Typical fit Standardized multi-cloud infrastructure AWS-centric organizations Teams wanting real programming languages Linux, application, and operational automation

State and Drift

Terraform state is an operational database, not merely a cache. It can contain credentials, private keys, tokens, and other sensitive values even when an output is marked sensitive.

  • Store state in a remote backend with encryption, versioning, access controls, and locking.

  • Use separate states or carefully designed instances for independent environments.

  • Review plans containing secrets before sharing them through CI.

  • Import existing resources instead of allowing Terraform to recreate them.

  • Refresh state before checking for drift; an outdated plan may propose unnecessary changes.

CloudFormation avoids a customer-managed state file, but its templates and stack events still require strict IAM and change-review controls. Pulumi checkpoints also contain potentially sensitive values, so the checkpoint backend must be protected similarly.

OpenTofu is a fork of Terraform with a compatible HCL ecosystem and many of the same state-safety concerns. It can be attractive where Terraform’s licensing or vendor dependence is unacceptable, but migration still requires validating providers, backend behavior, and team tooling.

Security and Governance

  • Terraform: Use a least-privilege CI role, protected remote state, branch restrictions, and reviewed plans. Do not place credentials in HCL or commit .tfvars files containing secrets.

  • CloudFormation: Use service roles, IAM boundaries, StackSets, and Change Sets. Restrict who can execute stack updates or change capabilities such as IAM resource creation.

  • Pulumi: Store sensitive values in a secret manager or use encrypted configuration where available. Treat checkpoints as secrets stores.

  • Ansible: Secure inventories and vault passwords, minimize plaintext credentials, and run tasks under dedicated automation accounts.

For all four tools, audit infrastructure changes separately from application deployment logs.

Production Workflow

A typical Terraform pipeline runs terraform fmt -check, terraform init -backend-config=..., terraform validate, and terraform plan before approval and terraform apply. Pin provider versions through the dependency lock file, test modules in isolated accounts, and keep production apply permissions separate from pull-request permissions.

CloudFormation normally uses validation tools, Change Sets, approval gates, stack events, and controlled rollback policies. Pulumi similarly previews updates, stores checkpoints, and applies through a protected pipeline. Ansible runs linting and syntax checks, executes playbooks in check mode where appropriate, and then deploys through a controlled runner or AWX workflow.

Failure Modes and Operational Trade-offs

  • Terraform: Provider throttling, eventual consistency, state-lock contention, failed state persistence, and partial applies can require careful recovery. Never bypass locks casually or manually edit state while automation is running.

  • CloudFormation: Failed updates can roll back, disable rollback, or leave resources in UPDATE_ROLLBACK_FAILED; retain or termination-protection policies can complicate cleanup.

  • Pulumi: Program exceptions and provider failures can occur after some resources have changed. Checkpoints make recovery possible but require backup and integrity monitoring.

  • Ansible: Unreachable hosts, idempotency mistakes, task ordering, secret exposure, and partial playbooks are common risks. Use serial execution, retries, explicit handlers, and failure reporting for critical hosts.

Choose CloudFormation for deep AWS governance, Terraform for portable declarative provisioning, Pulumi for programming-language flexibility, and Ansible for configuration and operational automation. Many production estates combine one provisioning tool with Ansible rather than treating them as interchangeable.

4

What is OpenTofu, and what motivated its creation?

OpenTofu is an open-source infrastructure-as-code (IaC) tool for declaring and managing cloud, network, and platform resources using HCL. It was created as a community-governed fork of Terraform after HashiCorp changed Terraform’s licensing and release governance, preserving open-source development under the MPL-2.0 license.

Read full answer

Applies toOpenTofu 1.x

Why It Was Created

  • License change: HashiCorp released Terraform 1.5.7 as the final MPL-2.0 release. Beginning with Terraform 1.6, new releases used the Business Source License 1.1, a source-available license that is not considered open source by the OSI.

  • Governance concerns: OpenTofu was created to provide a governance model not controlled by a single commercial vendor.

  • Continuity: The fork retained Terraform’s HCL language, provider ecosystem, CLI workflows, state model, and module structure rather than starting with an incompatible design.

  • Linux Foundation stewardship: The project is hosted by the Linux Foundation and governed through participation from multiple companies and community contributors.

  • Not primarily a technical replacement: OpenTofu was not created because Terraform had failed technically. Its original motivation was licensing, governance, and long-term project openness.

How It Works

OpenTofu follows the same basic declarative workflow:

  1. tofu init downloads the required providers and modules and initializes the configured backend.

  2. tofu plan reads the current state, refreshes information through providers, and calculates the changes needed to match the configuration.

  3. tofu apply asks the relevant providers to create, update, or destroy resources.

  4. The resulting resource identifiers and metadata are recorded in Terraform-compatible state files.

Providers implement the APIs for specific platforms such as AWS, Azure, Google Cloud, Kubernetes, or GitHub. OpenTofu supports many Terraform-compatible providers, but provider releases, external backends, and modules should still be tested before adoption.

OpenTofu vs Terraform

Area OpenTofu Terraform
Primary purpose Open-source infrastructure as code Infrastructure as code with commercial and hosted offerings
License MPL-2.0 BUSL 1.1 for releases since 1.6
Governance Linux Foundation and community governance HashiCorp and its stated product strategy
Configuration HCL, resources, data sources, modules, variables, outputs HCL and the same core IaC concepts
Provider ecosystem Terraform-compatible providers Native provider ecosystem
CLI Uses tofu; commands closely follow terraform Uses terraform
Compatibility Substantial, but not guaranteed for every provider, backend, or release Reference implementation for the original behavior

OpenTofu 1.6 originated from the Terraform 1.5.7 codebase rather than the Terraform 1.6 codebase. Later OpenTofu releases incorporate differing upstream Terraform changes, so they should not be assumed to be interchangeable with every later Terraform release without testing provider behavior, state handling, backend features, and module requirements.

Production and State Safety

State is the authoritative record of managed infrastructure. Production teams should:

  • Use a remote backend: Store state outside local developer machines, with restricted access, encryption, audit logging, and tested recovery procedures.

  • Enable locking: Locking prevents two applies from modifying the same state concurrently. Use a backend and locking implementation appropriate to the platform and OpenTofu version.

  • Protect secrets: State can contain passwords, tokens, certificates, and generated credentials even when variables are marked sensitive. sensitive primarily masks output; it does not encrypt state.

  • Review plans carefully: Inspect replacement, destruction, IAM, networking, and data-store changes. An apply can still partially succeed if an individual provider operation fails.

  • Detect drift: A normal plan refreshes provider data and reveals differences between recorded state and real infrastructure. IaC does not continuously enforce desired state until an apply occurs.

  • Control upgrades: Pin provider versions, review release notes, and test upgrades against realistic infrastructure. Provider upgrades can expose schema or state-upgrade behavior that changes resource replacement decisions.

  • Separate credentials: Prefer short-lived OIDC or workload-identity credentials over long-lived cloud access keys, and grant the CI pipeline only the permissions required for planning or applying.

  • Retain observability: Terraform-style reconciliation complements, but does not replace, service monitoring, alerting, backup verification, or incident response.

CI/CD and Migration Practices

A typical pipeline initializes the backend, validates formatting and configuration, creates a saved plan, and publishes that plan for review:

  • tofu fmt -check -recursive verifies HCL formatting.

  • tofu validate checks configuration consistency after initialization.

  • tofu plan -out=reviewed.tfplan creates a reviewable plan.

  • tofu apply reviewed.tfplan applies the reviewed plan without recalculating it.

Apply the same saved plan that was reviewed; generating a new plan immediately before apply can introduce changes that reviewers did not inspect. Avoid auto-approval for production infrastructure, and securely dispose of plan artifacts because they may also contain sensitive values.

When migrating from Terraform, test provider compatibility, backend configuration, modules, hooks, state schema, and planned changes in an isolated environment. Do not let Terraform and OpenTofu mutate the same state concurrently. Adopt OpenTofu when its governance and licensing model fit organizational requirements, but select providers and backends based on operational behavior rather than assuming complete drop-in compatibility.

5

What is HashiCorp Configuration Language in Terraform?

HCL (HashiCorp Configuration Language) is a declarative, configuration-oriented language used by Terraform to define resources, variables, outputs, providers, and other infrastructure behavior. Terraform 1.x uses HCL’s native syntax, commonly called HCL2.

Read full answer

Applies toTerraform 1.x and OpenTofu 1.x

Core Syntax

HCL organizes configuration into reusable blocks, attributes, and expressions:

  • Blocks: Represent a configuration object, such as resource, variable, provider, or output.

  • Attributes: Assign a value to a property within a block.

  • Expressions: Calculate values using literals, variables, resource references, functions, operators, or conditionals.

  • Traversal expressions: Access values across nested structures, such as aws_instance.web.private_ip.

  • Template interpolation: Embed expression results inside strings using ${...}.

For example, an EC2 instance configuration could define its type, subnet, and tags. The configuration describes the desired state rather than containing procedural instructions such as “create a server.”

How Terraform Processes HCL

Terraform performs several distinct stages during its workflow:

  1. Parsing: HCL is parsed into an expression tree. Syntax errors are detected at this stage.

  2. Configuration loading: Terraform evaluates expressions and resolves references between blocks.

  3. Schema validation: Provider schemas check whether resource types and arguments are valid.

  4. Planning: Terraform compares the desired configuration with the current infrastructure and state to produce a proposed action plan.

  5. Apply: Terraform executes the approved plan and records the resulting changes in state.

A syntax-valid configuration can still fail validation if it contains an unknown resource type, invalid argument, or incompatible value. The terraform fmt, terraform validate, and terraform plan commands are therefore separate and useful checks.

HCL, Terraform, and State

HCL is only the configuration format; it is not the deployment engine and does not store the live infrastructure inventory. Terraform’s state records the metadata needed to map configuration objects to real infrastructure and detect changes.

For production use:

  • Store state in a remote backend with encryption, access controls, versioning, and locking.

  • Review terraform plan output before applying changes.

  • Detect and investigate drift between real infrastructure and state.

  • Treat state as sensitive because it can contain sensitive values even when they are not displayed in plans.

  • Do not hard-code credentials in HCL; prefer workload identity, environment variables, or a secrets manager.

HCL files are usually committed to source control, while state files should be handled as protected operational data.

Modules and Reusability

Terraform modules organize HCL into reusable components. A module receives values through input variables and exposes results through outputs. This allows teams to define common infrastructure patterns while keeping environment-specific configuration separate.

Remote module sources can be retrieved from version-control repositories, registries, or object storage. Production workflows should pin module and provider versions to make plans reproducible. Provider version constraints belong in required_providers, while backend configuration is initialized separately with terraform init.

HCL Compared with Alternatives

Format Strength Terraform consideration
HCL native syntax Readable blocks, typed expressions, comments, reusable abstractions Standard and most expressive Terraform format
Terraform JSON syntax Machine-generated JSON configurations Supported variant, but less natural for humans
YAML Familiar to some teams Not natively supported by Terraform
Python or Go configuration Full programming capabilities Requires a wrapper tool and introduces imperative behavior

HCL deliberately avoids unrestricted general-purpose programming. Although it supports expressions, functions, and conditionals, its declarative model is easier to review and maintain than an imperative script. Terraform can still encounter operational failures such as provider API errors, expired credentials, eventual-consistency problems, state-lock contention, and provider-version incompatibilities; HCL syntax alone cannot eliminate those risks.

OpenTofu uses the same HCL-style configuration model and is largely compatible with existing Terraform modules, although organizations should evaluate its current feature support and operational tooling before adopting it.

6

What are providers in Terraform and how do they work?

A provider is a plugin that lets Terraform interact with a platform or service, such as AWS, Azure, Google Cloud, Kubernetes, or GitHub. Terraform Core builds the dependency graph and coordinates operations, while providers translate Terraform resource definitions into platform-specific API calls.

Read full answer

Applies toTerraform 1.x, AWS provider 5.x, and OpenTofu 1.x

How Providers Work

Terraform generally runs each provider as a separate process and communicates with it through an RPC protocol. This isolation prevents a provider failure from directly crashing Terraform Core and allows providers to evolve independently.

During a plan or apply, Terraform performs the following steps:

  1. Loads provider requirements from the configuration.

  2. Downloads the required provider plugins or retrieves them from an approved private mirror.

  3. Starts the relevant provider processes.

  4. Sends provider configuration, such as AWS region or Kubernetes context.

  5. Asks the provider to plan, create, read, update, or delete resources.

  6. Uses provider-generated data to populate Terraform state and outputs.

A provider usually exposes three kinds of functionality:

Function Purpose Example
Resource Represents a manageable object An AWS EC2 instance
Data source Reads an existing object An existing AMI or VPC
Provider function Performs a provider-specific calculation A provider-generated identifier

Providers also define schemas, validation rules, timeouts, retry behavior, import behavior, and relationships between resources.

Provider Configuration and Versions

Provider requirements should be declared explicitly under required_providers. The local name, such as aws, is used in resource blocks, while source identifies the registry package, such as hashicorp/aws.

For AWS provider 5.x, the requirement would use source = "hashicorp/aws" and a constraint such as version = "~> 5.0". The provider itself is configured with a provider "aws" block containing settings such as region.

terraform init installs provider plugins and creates .terraform.lock.hcl. Commit this lock file to version control so every developer and CI job uses verified provider versions and checksums.

  • terraform init: Installs providers without changing selected versions when possible.

  • terraform init -upgrade: Selects newer versions allowed by the constraints.

  • terraform providers: Displays the providers required by the current configuration.

  • terraform validate: Checks whether the configuration and provider schemas are valid.

Provider upgrades can change schemas, defaults, validation, or planning behavior. Upgrade them separately from infrastructure changes and review the resulting plan carefully.

Authentication and Security

Providers authenticate through mechanisms supported by the target platform, including environment variables, shared credential files, workload identity, OIDC, or explicit role assumption.

For production:

  • Prefer short-lived OIDC or workload identity over long-lived access keys.

  • Give each Terraform deployment only the permissions it requires.

  • Avoid placing credentials directly in HCL or committing credential files.

  • Treat remote state as sensitive: resource attributes may contain passwords, tokens, private keys, or connection strings.

  • Mark sensitive outputs appropriately, but remember that sensitive = true only hides display output; it does not remove the underlying value from state.

  • Restrict state access and enable backend encryption, auditing, versioning, and recovery.

Backend state locking and provider locking solve different problems. Backend locking prevents concurrent state-changing operations, while .terraform.lock.hcl ensures consistent provider binaries.

State, Drift, and CI/CD

A remote backend is recommended for production because it provides centralized state, controlled access, backups, and locking. Configure the backend separately from provider credentials, commonly through protected CI variables or a controlled terraform init -backend-config step.

At the start of planning, providers refresh existing resources through read APIs. Terraform can then report drift between the recorded state and the remote platform. A useful operational response is terraform plan -refresh-only, followed by investigation and a controlled apply. Always review plans because provider read behavior and API defaults can affect the proposed changes.

A production CI/CD pipeline typically runs formatting, initialization, validation, tests, security scanning, and a saved plan before approval. After approval, apply the reviewed plan rather than generating a different one. In Terraform 1.7 and later, terraform test supports provider mocks, which can test configuration behavior without modifying real infrastructure.

Failure Modes and Trade-offs

Common provider-related failures include:

  • Authentication or authorization errors: Credentials are missing, expired, or lack required permissions.

  • API throttling: The provider exhausts retry limits during a large plan or apply.

  • Partial applies: Some resources succeed before another operation fails. Inspect state and remote objects before retrying.

  • Version inconsistency: Different teams use different provider versions and produce different plans.

  • Schema changes: A provider upgrade introduces incompatible arguments or changed defaults.

  • Plugin or network failures: Downloads fail, checksums do not match, or provider processes terminate unexpectedly.

Providers are not merely configuration helpers: they encode assumptions about how a platform behaves. Terraform cannot guarantee consistency across unrelated providers, and provider quality directly affects plan accuracy, retry safety, state management, and incident recovery. OpenTofu uses the same provider plugin model, so most provider documentation and configuration practices apply there as well.

7

How do you pin Terraform provider versions?

Use version constraints in required_providers to define acceptable provider releases, then commit .terraform.lock.hcl to record the exact selected versions and checksums. The lock file provides the actual reproducible pin and prevents terraform init from silently selecting a different compatible provider.

Read full answer

Applies toTerraform 1.x; example uses hashicorp/aws 5.x

How Pinning Works

Terraform resolves providers through two related mechanisms:

  • required_providers constraints: Define an allowed version range, an exact version, or a compatible major-version range.

  • Dependency lock file: .terraform.lock.hcl records the exact provider version, package checksums, and supported platform hashes used by the configuration.

For example, ~> 5.0 allows AWS provider versions from 5.0 up to, but not including, 6.0. Once .terraform.lock.hcl is committed, normal initialization preserves the exact locked version as long as it satisfies the constraint.

A constraint alone is therefore not a complete pin. A changed constraint, deleted lock file, or terraform init -upgrade can select another version.

Upgrade Workflow

To upgrade deliberately:

  1. Review the provider’s changelog, especially resource schema, default-value, and validation changes.

  2. Change the constraint in required_providers to the intended release range.

  3. Run terraform init -upgrade to select the newest matching provider and update the lock file.

  4. Review .terraform.lock.hcl and run terraform plan.

  5. Test in a non-production environment before rolling out the change.

terraform init -upgrade intentionally ignores the currently locked provider versions, so it should not run on every ordinary deployment.

For CI runners on additional platforms, refresh platform checksums with a command such as:

terraform providers lock -platform=linux_amd64

Review and commit the resulting lock-file changes. Keep CI and developer workflows on the same Terraform CLI major version.

Production and State Safety

Use a remote backend with state locking for production deployments. Backend locking prevents concurrent operations from modifying the same state; it is separate from provider version pinning. For example, an S3 backend can use a DynamoDB lock table, with appropriate bucket encryption, versioning, and least-privilege access.

Provider installations and Terraform state are different security boundaries:

  • Secrets in state: Provider arguments can leave credentials, tokens, certificates, or generated secrets in state. Use IAM roles, workload identity, secret references, and encrypted remote state rather than static credentials.

  • Plan sensitivity: Saved plans and CI plan artifacts may contain sensitive values. Restrict access and avoid publishing them publicly.

  • Drift detection: Run scheduled plans against remote state to detect manual or external changes.

  • Plan review: Require reviewed plan artifacts and approval before production applies.

  • Backups: Enable backend versioning or regular state backups, and test state restoration procedures.

Do not alternate between Terraform and OpenTofu in the same CI workflow without validating compatibility. OpenTofu also supports required_providers and .terraform.lock.hcl, but provider and lock-file behavior should be tested under the CLI your team actually operates.

Code Example

Declare the provider source and constraint in the root module:

terraform {
  required_version = ">= 1.5.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "us-east-1"
}

Initialize the configuration and commit the generated lock file:

terraform init -input=false
terraform fmt -check
terraform validate
terraform providers

Commit .terraform.lock.hcl alongside the HCL files:

git add .terraform.lock.hcl
git commit -m "Pin Terraform provider versions"

The provider constraint and lock file serve different purposes:

Mechanism Purpose Allows automatic upgrades?
required_providers Defines acceptable versions Yes, when constraints change
.terraform.lock.hcl Records exact versions and checksums No, during normal initialization

Best Practices and Failure Modes

  • Commit .terraform.lock.hcl and review every change to it.

  • Use terraform init -lockfile=readonly -input=false in CI to prevent dependency changes during validation and planning.

  • Keep constraints broad enough for controlled maintenance, but rely on the lock file for exact reproducibility.

  • Never routinely run terraform init -upgrade in deployment pipelines.

  • Do not manually fabricate lock-file checksums; let Terraform generate and verify them.

  • Expect initialization to fail when the lock file conflicts with a constraint, a checksum is invalid, or a required platform package is unavailable.

  • Treat provider upgrades like application upgrades: canary them, review plans, monitor resources afterward, and maintain a tested rollback and state-recovery plan.

8

Terraform resource vs data source: what’s the difference?

A Terraform resource creates and manages infrastructure, while a data source reads information about infrastructure that already exists. Resources participate in the full create, update, and delete lifecycle; data sources are read-only queries whose results can be referenced by other configuration.

Read full answer

Applies toTerraform 1.x, provider-neutral; examples align with AWS provider 5.x

Core Distinction

Behavior Resource Data source
Purpose Manage the lifecycle of an infrastructure object Read information about an existing object
Lifecycle Create, update, and potentially delete Read only
State Contains the managed object’s attributes and identifiers Contains the latest read result
Typical use An S3 bucket, EC2 instance, IAM role, or VPC An existing AMI, account details, or hosted zone
Configuration effect Terraform attempts to make reality match the declared configuration Terraform observes reality without trying to change it

For example, a resource configuration might declare an aws_s3_bucket and allow Terraform to create it. A data source might read the ID of an AMI that another team already provisioned.

How Plan and Apply Differ

During planning and refresh, Terraform evaluates the dependency graph:

  • Resources: Terraform compares the desired configuration with the object recorded in state and the provider’s current view. Proposed changes appear in the plan; approved changes are applied later.

  • Data sources: Terraform calls the provider’s read API and exposes the returned attributes as values. Most reads happen during refresh and planning.

  • A data source that depends on a resource being created may be deferred until apply, because its value cannot be known before that resource exists.

  • Removing a resource from configuration normally proposes destroying the corresponding remote object. Removing a data source only stops Terraform from querying it; it does not delete anything.

Both resource and data-source results are recorded in state. The important distinction is ownership: a resource is managed by Terraform, whereas a data source is only observed by it.

Ownership and Lifecycle

Use a resource when Terraform should own the object’s lifecycle, including:

  • Creating it during an initial apply.

  • Updating it when its arguments change.

  • Destroying it when it is removed from configuration.

  • Applying lifecycle rules such as prevent_destroy, replacement triggers, or custom timeouts.

  • Importing an existing object and subsequently managing it.

Use a data source when the object is managed externally or must remain read-only for the current configuration. A common example is reading the latest Amazon Linux AMI instead of managing the AMI itself.

If ownership changes from external management to Terraform management, add the corresponding resource configuration and import the existing object. Using an import block or terraform import records the object in state without first creating a duplicate.

Production and State Safety

Resource management and state are closely connected, so production deployments need controlled state handling:

  • Store state in a remote backend with encryption, versioning, and restricted access.

  • Enable backend locking so concurrent Terraform runs cannot corrupt state or apply conflicting plans.

  • Review plans carefully, especially replacements and destroy operations; Terraform cannot undo a failed apply automatically.

  • Remember that state may contain sensitive values. Do not place secrets directly in configuration, and treat state access as privileged even when using sensitive input variables.

  • Monitor drift by scheduling read-only plan runs. A data source is useful for observing external state, but it does not itself correct drift in a managed resource.

  • Protect backend credentials, audit state changes, and retain recoverable state versions for incident response.

Choosing the Correct Declaration

Ask who is responsible for changing the object:

  • Terraform is responsible: use a resource.

  • Another system or team is responsible: use a data source.

  • Terraform must only inspect an object temporarily: use a data source.

  • Terraform must enforce settings over time: use a resource, potentially with lifecycle rules and validation.

Avoid using a resource merely because an object already exists. Conversely, avoid using a data source for an object Terraform is expected to own and maintain, because configuration changes would not be enforced. Terraform and OpenTofu follow this same conceptual model, although their backend and provider implementations should be evaluated separately.

9

What is the Terraform init, plan, apply, and destroy workflow?

The Terraform workflow is a plan-driven infrastructure lifecycle: init prepares the working directory, plan calculates the required changes, and apply executes an approved plan. Destroy is a separate destructive workflow that removes managed resources and updates the state accordingly.

Read full answer

Applies toTerraform 1.x; AWS provider 5.x when AWS resources are used

How the Workflow Works

  1. terraform init: Prepares the working directory by downloading providers, installing modules, and configuring the backend. It creates .terraform/ and normally generates .terraform.lock.hcl to record provider dependency versions. It does not create infrastructure.

  2. Use terraform init -input=false in automation.

  3. Review backend migration prompts carefully because they can move state.

  4. Use terraform init -upgrade only when intentionally upgrading providers.

  5. terraform plan: Compares the configuration, current state, and provider-reported remote objects. It produces an execution plan showing creates, updates, replacements, and deletes without changing infrastructure.

  6. By default, Terraform refreshes state before planning.

  7. -out=tfplan saves the plan as an artifact.

  8. Data sources are read during planning when their values are needed.

  9. terraform apply: Executes the approved changes and writes the resulting resource bindings and values back to state.

  10. terraform apply tfplan applies a previously reviewed saved plan exactly.

  11. terraform apply without a saved plan creates a new plan and normally requests approval.

  12. -auto-approve removes the interactive safeguard and should only be used after an equivalent review exists.

  13. terraform destroy: Plans and executes deletion of resources managed by the configuration. It updates state, but normally does not delete the remote backend state object itself. Prefer a reviewed destroy plan over terraform destroy -auto-approve.

Configuration Model

  • Providers implement integrations with cloud platforms and other APIs.

  • Resources represent infrastructure that Terraform manages.

  • Data sources read existing objects without managing their lifecycle.

  • Variables parameterize configurations; outputs expose selected values.

  • Modules package reusable configuration, inputs, and outputs.

  • Lifecycle rules control operations such as create_before_destroy, replacement triggers, and prevent_destroy.

  • Workspaces maintain separate state entries under one backend configuration. They are not strong tenant isolation and should not substitute for separate accounts or backends.

  • terraform import brings an unmanaged object under Terraform management without recreating it; afterward, plan and review the imported configuration.

State Safety and Drift

  • Store state in a remote backend with encryption, access controls, versioning, backups, and locking. Do not commit state to source control.

  • State may contain sensitive values captured from resources, data sources, or outputs. A sensitive variable alone does not guarantee that its value is absent from state; prefer a secret manager and avoid exposing secrets in outputs.

  • Treat state as the record of resource bindings, not as an automatic rollback mechanism.

  • Plan regularly to detect drift. Provider refresh behavior determines which out-of-band changes Terraform can observe, and a plan normally proposes reconciling them.

  • Review plan diffs for unintended replacement or deletion. Replacement can occur when configuration forces a new resource or when provider upgrade guidance requires it.

  • Commit .terraform.lock.hcl, but review provider upgrades as a separate change from application infrastructure.

CI/CD and Testing

A production pipeline should run formatting, validation, planning, approval, and application as distinct stages:

  • terraform fmt -check -recursive checks formatting.

  • terraform validate checks configuration validity.

  • terraform plan -detailed-exitcode returns 0 for no changes, 2 for changes, and 1 for errors.

  • terraform test, available in Terraform 1.6 and later, runs native tests from .tftest.hcl files.

  • Save a plan artifact, publish it for human review, and apply that exact artifact after approval. The apply environment must use the same configuration, provider lock file, backend, and credentials.

  • After applying, monitor cloud metrics, logs, service health, cost, and security controls. Failed applies can leave partial changes and require a new corrective plan.

Production Pitfalls and OpenTofu

  • Avoid -target as a substitute for a complete plan; it can omit dependent changes.

  • Do not use terraform destroy as a shortcut for replacing infrastructure when targeted replacement or module versioning is safer.

  • A failed apply is not rolled back automatically. Use staged changes, canaries, backups, and tested recovery procedures.

  • Keep backend, provider, and module upgrades independently reviewable.

  • OpenTofu 1.x supports the same core workflow through tofu init, tofu plan, tofu apply, and tofu destroy. Validate provider compatibility and backend behavior, and do not let Terraform and OpenTofu mutate the same state concurrently.

10

What does the terraform init command do?

terraform init prepares a Terraform working directory before any plan or apply can run. It installs the providers and modules your configuration requires, initializes the state backend, and creates the local .terraform/ directory plus the .terraform.lock.hcl dependency lock file. It does not create or modify your actual cloud resources — it only sets up the tooling and state plumbing needed for terraform plan, terraform apply and terraform destroy.

Read full answer

Applies toTerraform 1.x (1.5+); OpenTofu 1.x uses the equivalent `tofu init`

What It Actually Does, Step by Step

  1. Selects the working directory and creates .terraform/ if it does not exist. Terraform refuses to run plan/apply without a valid initialized directory.

  2. Installs providers: reads the required_providers block, downloads matching provider binaries (e.g. hashicorp/aws 5.x) into .terraform/providers/, and writes .terraform.lock.hcl with the selected versions and their zh: hashes.

  3. Downloads modules: fetches module sources from the registry, Git, HTTP or local paths into .terraform/modules/, and records them in .terraform/modules/modules.json.

  4. Initializes the backend: configures the remote or local state storage. It may prompt for missing backend values and may copy existing state when the backend changes. It does not create the storage itself: the S3 bucket must already exist.

  5. Prints Terraform has been successfully initialized! followed by the suggested next command (terraform plan).

Files It Creates

Path Purpose Commit to VCS?
.terraform/ Cached provider binaries, modules, cached backend config No (gitignore it)
.terraform.lock.hcl Pinned provider versions + checksums Yes
.terraform/modules/ Downloaded module sources No
.terraform/terraform.tfstate Cached backend configuration No

Flags You Will Use in Practice

Flag Effect
-input=false Never prompt; fails instead of waiting for input. Standard in CI.
-backend-config=file.hcl or key=value Supplies backend values separately from the backend block (keeps non-secret config in code, secrets out).
-reconfigure Forget the cached backend configuration and re-read it, without migrating state.
-migrate-state Copy existing state from the old backend to the new one (Terraform 1.1+).
-upgrade Ignore the versions recorded in the lock file and pick the newest provider/module versions allowed by the version constraints.
-lockfile=readonly Fail if .terraform.lock.hcl would need to change — the right CI default.
-plugin-dir Use a local directory or filesystem mirror of provider binaries instead of the registry.
-no-color Plain output for log capture.

State and Backend Safety

  • Never keep local state for anything shared. terraform init with no backend block uses a local terraform.tfstate file, which is unsuitable for teams.

  • Backend config is cached in .terraform/terraform.tfstate. If you edit the backend "s3" { ... } block, init will report that the backend configuration changed; use -reconfigure (same backend, new settings) or -migrate-state (move state to a different backend). Plain init will not move your state for you.

  • Locking: the S3 backend supports native locking with use_lockfile = true (Terraform 1.10+), replacing the older DynamoDB lock table approach. Locking prevents two engineers from applying concurrently.

  • State contains secrets: resource attributes such as passwords, tokens and private keys are stored in the state JSON in plain text; bucket encryption protects the stored object, but anyone who can read the state sees the values. Use sensitive = true on outputs, keep state in a tightly locked-down bucket, and prefer an external secret manager (AWS Secrets Manager, Vault) over password fields in resources.

  • CI/CD pattern: terraform init -input=false -backend-config=backend.hcl -lockfile=readonly, then terraform plan -out=tfplan and terraform apply tfplan. Keep the saved plan as a protected pipeline artifact (never in Git, since it can hold secrets) so the applied change is exactly the reviewed one.

  • Bootstrap separately: manage the state bucket (and any lock table) in its own bootstrap stack, because the bucket must exist before the main stack can initialize.

Common Failure Modes

  • No credentials at init time: the S3 backend authenticates during init, so CI roles or environment credentials must be present before the command runs.

  • Provider not found: private registries need a token in TF_TOKEN_<hostname>; otherwise init fails with a 404-style error.

  • Lock file drift: running init -upgrade in CI silently changes provider versions. Use -lockfile=readonly to catch this.

  • Wrong directory: init operates on the current working directory; a monorepo needs one init per stack directory.

  • Config errors are not caught by init: terraform init does not fully validate your HCL; run terraform validate afterwards.

Code Example

# main.tf
terraform {
  required_version = ">= 1.5"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }

  # Partial backend configuration; values supplied via -backend-config
  backend "s3" {}
}
# backend.hcl — non-sensitive backend settings, safe to commit
bucket       = "example-tf-state"
key          = "prod/platform/terraform.tfstate"
region       = "us-east-1"
encrypt      = "true"
use_lockfile = true # native S3 locking, Terraform 1.10+
terraform fmt -check
terraform init -input=false -backend-config=backend.hcl -lockfile=readonly
terraform validate
terraform plan -out=tfplan
terraform apply tfplan

Best Practices

  • Run terraform init in every working directory before the first plan, and after changing provider requirements, module sources or the backend block.

  • Commit .terraform.lock.hcl; treat unexpected changes as a review signal.

  • Separate backend configuration from state location decisions, and never store credentials in .tf files — pass them via environment variables, OIDC role assumption or workload identity.

  • With OpenTofu, run tofu init with the same flags; it uses its own provider registry and locks state the same way, so the same CI structure applies.

11

How do you read the changes shown by terraform plan?

The plan output from terraform plan is a preview of the actions Terraform intends to take. By default, it refreshes the prior state through provider APIs before comparing that state with the desired configuration; it does not apply the infrastructure changes.

Read full answer

Applies toTerraform 1.10+; OpenTofu 1.x; AWS provider 5.x examples

Reading the Plan

Terraform compares the configuration with its refreshed prior state. The state records resource attributes, metadata, and dependency information; it does not contain a saved copy of the configuration. Provider APIs are also used to read data sources and, unless refresh is disabled, query live infrastructure.

A summary commonly resembles:

Plan: 1 to add, 1 to change, 0 to destroy.
Symbol Meaning Operational impact
+ Create Creates a new resource.
~ Update in place Changes attributes without replacing the resource.
- Destroy Removes the resource.
-/+ Destroy, then create Replaces the resource and may cause downtime or data loss.
+/- Create, then destroy Replaces the resource using create-before-destroy ordering.
<= Read Reads a data source and normally does not modify infrastructure.

Review a plan in this order:

  1. Read the summary and identify creates, updates, replacements, and destroys.

  2. Inspect every changed attribute and confirm it comes from an intentional variable, module, or provider change.

  3. Treat replacements as potentially disruptive: addresses, certificates, identifiers, or persistent data may change.

  4. Check dependencies because one replacement can trigger changes to several dependent resources.

  5. Review output changes and known after apply values, which cannot be finalized until apply time.

  6. For controlled deployments, save the plan and apply that exact artifact rather than generating a different plan.

State, Drift, and Locking

Production state should use a remote backend with encryption at rest, tightly restricted access, versioning or protected backups, and locking. Separate environments should use separate state keys. Terraform 1.10 and later support native S3 backend lock files through use_lockfile = true; the state bucket must already exist and its name must be globally unique.

The lock protects Terraform state access, but it does not make an apply atomic or prevent resource changes outside Terraform. If live infrastructure differs from recorded state, a normal plan proposes changes that reconcile that drift with the configuration. terraform plan -refresh-only creates a state-only reconciliation plan; apply that reviewed plan when the intention is to update Terraform’s record rather than restore configuration-defined infrastructure.

OpenTofu 1.x has a similar plan/apply workflow, but its backend and locking options must be checked against the OpenTofu release in use.

Failure Modes and Security

  • Lock contention: Another operation owns the state lock. Investigate it rather than routinely bypassing locking.

  • Insufficient permissions: Refresh or planning can fail when the provider lacks read permissions.

  • Provider upgrade: Schema or behavior changes can alter planned actions; review the dependency lock file and upgrade incrementally.

  • Partial apply: Terraform is not atomic across resource types. After a failure, inspect the updated state, correct the cause, and normally generate and review a fresh plan before continuing.

  • Secrets: sensitive = true redacts values from normal CLI output but does not remove them from state or a saved plan. Protect state and plan artifacts, avoid static credentials, and prefer workload identity or a secrets manager.

Code Example

This Terraform 1.10+ and AWS provider 5.x configuration includes an S3 backend with native locking:

terraform {
  required_version = ">= 1.10"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }

  backend "s3" {
    bucket       = "example-company-tf-state"
    key          = "production/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    use_lockfile = true
  }
}

provider "aws" {
  region = "us-east-1"
}

resource "aws_s3_bucket" "artifacts" {
  bucket = "example-company-artifacts"
}

Replace both bucket names with globally unique values. The state bucket must exist before initialization; the artifacts bucket is managed by Terraform.

terraform init
terraform validate
terraform plan -out=tfplan
terraform show -no-color tfplan
terraform apply tfplan

terraform show -json tfplan produces machine-readable output for policy checks and CI integrations. Because JSON plan output can contain sensitive values in clear text, store and transmit artifacts securely.

Production Workflow

Use terraform plan -detailed-exitcode in CI: it returns 0 when there are no changes, 2 when changes exist, and 1 on error. Require peer review for replacements or destroys, test in staging, and verify backups and disaster recovery for stateful resources before applying.

After apply, monitor affected services and reconcile Terraform state with reality. If operators make manual changes, follow them with either a reviewed apply that restores the intended configuration or a reviewed refresh-only apply that accepts the live state. During incidents, preserve state and provider logs and pause further automation rather than improvising destructive changes.

12

Why does Terraform need a state file?

Terraform state is the persisted record of the infrastructure objects Terraform manages. It is needed to correlate real cloud resources with Terraform configuration, detect changes, calculate required actions, and track resource IDs and outputs across runs.

Read full answer

Applies toTerraform 1.x

State Contents and Purpose

After an apply, Terraform writes a state snapshot containing:

  • Resource addresses: Logical names such as aws_instance.web.

  • Provider and resource types: For example, the AWS provider and aws_instance.

  • Cloud identifiers: Instance IDs, bucket names, security group IDs, and other provider-returned identifiers.

  • Resource attributes: The last known configuration of each managed object.

  • Dependencies: Relationships Terraform uses to determine operation ordering.

  • Outputs: Values exported by the configuration, potentially including sensitive outputs.

  • Metadata: A state serial, lineage, and Terraform version information.

Terraform configuration expresses the desired state, while Terraform state represents the last known observed state. The state is not merely a cache; it is essential for safely updating infrastructure without recreating every resource.

How Terraform Uses State

During a normal workflow, Terraform performs these steps:

  1. terraform init installs the required providers and initializes the configured backend.

  2. terraform plan reads the current state and refreshes tracked resources through provider APIs.

  3. Terraform compares the refreshed reality with the configuration.

  4. The provider produces a plan containing actions such as create, update, replace, or delete.

  5. terraform apply executes those actions and writes the resulting state.

The recorded resource IDs prevent unnecessary replacement. For example, if a security group’s description changes, Terraform can update that group in place rather than destroy it and create a new one.

State also helps Terraform understand that a resource already exists when configuration changes. Without a valid state, Terraform may propose creating duplicate objects or be unable to correlate existing infrastructure.

Backend, Locking, and Security

The default local backend stores state in terraform.tfstate. Production environments should generally use a remote backend with:

  • Encryption at rest and TLS in transit.

  • Strong identity controls and least-privilege access.

  • Versioning, retention, and recovery procedures.

  • Backend-managed state locking.

  • Restricted access to state because it can contain credentials generated during provisioning.

State locking prevents two Terraform processes from modifying the same state concurrently. Without locking, concurrent applies can overwrite each other’s results or lose track of created resources. Use the locking mechanism supported by the selected backend and Terraform version; for example, current AWS S3 backend configurations can use S3-native locking, while older configurations may use a DynamoDB lock table.

Marking an output as sensitive only controls display in Terraform output; it does not remove the value from state. Secrets passed into a resource can also appear in resource attributes. Treat the state file as a secret-bearing artifact.

OpenTofu generally supports Terraform-compatible state, but teams should test migrations and must never have Terraform and OpenTofu mutate the same state concurrently.

Workspaces and Lifecycle Rules

A workspace selects a separate logical state within the backend. This allows separate state for development, staging, and production while using the same configuration.

  • Benefits: Isolated outputs and resource tracking for multiple environments.

  • Limitations: Workspaces do not enforce infrastructure isolation; credentials, networking, and backend permissions must still isolate environments.

  • Operational guidance: Avoid creating excessive workspaces and restrict who can select production.

Lifecycle rules also influence planned state changes:

Rule Effect
create_before_destroy Creates a replacement before destroying the original
prevent_destroy Rejects plans that would destroy a resource
ignore_changes Preserves specified externally managed attributes
replace_triggered_by Forces replacement when a referenced value changes

Drift, Recovery, and Imports

Drift occurs when a resource changes outside Terraform. Because plan refreshes tracked resources, it can expose differences such as an administrator manually changing a firewall rule. Review these actions carefully because applying a drift correction may overwrite the external change.

If state is lost or corrupted:

  1. Stop automated applies.

  2. Restore the most recent known-good state from the backend’s version history or backup.

  3. Verify that resource IDs still match the actual infrastructure.

  4. Use terraform import for existing resources that are not tracked.

  5. Run a reviewed plan before making further changes.

Do not manually edit state unless absolutely necessary. Use terraform state rm only when deliberately removing an object from Terraform management, not as a substitute for state recovery.

Production and CI/CD Practices

Use a pipeline that separates planning from applying:

  • Authenticate to the backend using short-lived credentials, preferably workload identity.

  • Run terraform plan in pull requests and retain the plan artifact.

  • Require approval before applying to production.

  • Protect the apply job so only controlled automation can update state.

  • Review drift corrections and replacement actions explicitly.

  • Monitor failed refreshes, plans, applies, lock contention, and backend errors.

  • Back up state before provider or state-schema migrations and test restoration procedures.

Avoid routinely using -refresh=false: it can produce an incorrect plan when infrastructure has changed. Commit configuration and backend settings, but never commit a state file containing production secrets.

13

What risks does storing Terraform state files locally?

Local Terraform state is simple for prototypes, but it creates significant security, concurrency, and disaster-recovery risks for production infrastructure. The state file records the mapping between Terraform configuration and real resources, and it may contain sensitive values even when variables are marked as sensitive.

Read full answer

Applies toTerraform 1.x

Why State Matters

Terraform uses terraform.tfstate to determine what resources already exist and how they should be managed. It includes resource identifiers, attributes, provider metadata, dependency information, and values such as generated passwords, private keys, and connection strings.

State is not merely a cache. It is the authoritative record Terraform uses to detect changes, plan updates, and determine what must be destroyed or imported.

Principal Risks

  • Sensitive data exposure: Sensitive values are not encrypted in the state file. Marking an input as sensitive = true prevents Terraform from displaying it in normal CLI output, but it does not encrypt the value stored in state.

  • Accidental source control leakage: A local state file in the working directory can be committed to Git, uploaded as a CI/CD artifact, or included in a backup without the protections applied to infrastructure code.

  • No effective team locking: The local backend does not provide remote locking. Two engineers or CI jobs can modify the same infrastructure concurrently, causing conflicting plans, overwritten state, or destructive actions.

  • Stale or divergent state: Separate developers can each maintain a different local copy. A configuration might successfully plan on one workstation but fail on another because required resources are missing or have different attributes.

  • Data loss and corruption: Disk failure, accidental deletion, an interrupted write, malware, or an incomplete workspace cleanup can remove the only record of managed resources.

  • Poor disaster recovery: A local file does not naturally provide replication, versioning, access auditing, or geographic redundancy. Restoring a workstation is not equivalent to restoring production infrastructure.

  • Confusing plan and apply workflows: If state is not shared, a plan created against one state snapshot may be applied against a changed environment. Terraform normally detects some inconsistencies, but resource APIs and external changes can still create difficult failures.

  • Incorrect lifecycle decisions: Without an accurate shared state file, Terraform may attempt to recreate resources or destroy resources that already exist. This can affect databases, load balancers, DNS records, and stateful components.

Security Implications

State should be treated as a secret-bearing operations artifact rather than an ordinary build output. Depending on the resources and providers involved, it may expose:

  • Database passwords and connection strings

  • Private keys and certificates

  • API tokens

  • Bootstrap credentials

  • Internal hostnames, account identifiers, and resource configuration

Restricting access to the state file is necessary but insufficient. A remote backend should also provide encryption at rest, encryption in transit, versioning, audit logging, and tightly controlled access.

Local and Remote State Compared

Concern Local state Production-grade remote state
Setup complexity Very low Requires a cloud account, IAM policy, networking, and backend configuration
Multi-user coordination Unsafe without additional controls Designed for shared use with locking
Confidentiality Depends entirely on the machine and filesystem Can use encryption, restricted IAM, and private networking
Version history Usually unavailable Commonly available through object versioning
Disaster recovery Manual backups Replicated and independently recoverable
Auditability Limited Access and infrastructure activity can be logged
Appropriate use Prototypes, learning, isolated experiments Shared and production environments

Production Safeguards

  1. Use a remote backend for shared or production state, with locking enabled. Select a backend supported by both Terraform and your organization; configure private access, encryption, versioning, and least-privilege permissions.

  2. Enable state versioning and retention so an accidental overwrite or deletion can be recovered.

  3. Restrict backend access by environment and role. Developers should not automatically receive write access to production state.

  4. Never expose state through public object storage. Review backend IAM policies, bucket policies, public-access blocks, and network rules.

  5. Do not rely on sensitive = true as encryption. Avoid placing long-lived secrets in Terraform inputs where possible; use a secrets manager and inject values at runtime.

  6. Review plans in CI/CD against the correct workspace and backend. Protect production applies with approvals, limited credentials, and branch or environment restrictions.

  7. Back up and test restoration. Versioning helps, but teams should also verify that an earlier state version can actually be restored and reconciled with the live cloud environment.

  8. Monitor for drift using scheduled plans and alerting. State protects Terraform-managed resources; it does not detect all out-of-band changes in real time.

  9. Use remote state for OpenTofu too where compatibility permits. OpenTofu provides additional backend choices and state-encryption capabilities, but the same security and concurrency fundamentals apply.

Local state is reasonable for a disposable prototype on one workstation. It should not be the system of record for infrastructure shared by multiple engineers, automated pipelines, or production environments.

14

How do you configure an S3 remote backend with state locking in Terraform?

Configuring an S3 remote backend with state locking means storing Terraform state in an S3 bucket while serializing concurrent operations so two runs cannot corrupt the state file. Terraform supports two locking mechanisms: a DynamoDB table (all versions) or native S3 locking via conditional writes (Terraform 1.10+).

Read full answer

Applies toTerraform 1.x with AWS provider 5.x (native S3 locking requires Terraform 1.10+).

How It Works

  • The state file is stored at the key path inside the S3 bucket.

  • Before plan or apply, Terraform acquires a lock; after completion it releases it.

  • With DynamoDB locking, Terraform writes a lock item to a table whose partition key is LockID (String) using a conditional write, so only one holder succeeds.

  • With native S3 locking (1.10+), Terraform creates a .tflock object using S3 conditional writes (If-None-Match), removing the DynamoDB dependency entirely.

  • If a run crashes, the lock may remain; use terraform force-unlock <LOCK_ID> only after confirming no other process is running.

DynamoDB-Based Configuration

terraform {
  backend "s3" {
    bucket         = "example-tf-state"
    key            = "prod/terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "terraform-locks"
    encrypt        = true
    kms_key_id     = "alias/terraform-state"
  }
}

The DynamoDB table must have a partition key named LockID of type String. Enable point-in-time recovery and encryption at rest on the table.

Native S3 Locking (Terraform 1.10+)

terraform {
  backend "s3" {
    bucket       = "example-tf-state"
    key          = "prod/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    use_lockfile = true
  }
}

No DynamoDB table is required. The S3 bucket must support conditional writes (available in all standard regions). This is the recommended approach for new setups.

Security and State Safety

  • Always set encrypt = true; prefer SSE-KMS with a dedicated key for auditability.

  • Enable S3 versioning and MFA delete on the state bucket to recover from accidental overwrites.

  • Block all public access on the bucket; restrict IAM to least privilege (read/write only the state key and lock object).

  • State files contain plaintext secrets (passwords, tokens); treat the bucket as sensitive data and limit who can read it.

  • Use separate state files per environment and per stack to limit blast radius.

Best Practices

  • Bootstrap the bucket and lock table with a separate, minimal Terraform config or CLI before the main config references them.

  • Run terraform plan in CI on pull requests and terraform apply only on merge to the default branch.

  • Never commit .tfstate or .tfstate.backup to version control.

  • Periodically run terraform plan to detect drift; alert on unexpected changes.

  • Back up state via S3 versioning rather than manual copies.

Code Example

# Bootstrap resources (apply once, manually or via a separate workspace)
resource "aws_s3_bucket" "state" {
  bucket = "example-tf-state"
}

resource "aws_s3_bucket_versioning" "state" {
  bucket = aws_s3_bucket.state.id
  versioning_configuration {
    status = "Enabled"
  }
}

resource "aws_dynamodb_table" "locks" {
  name         = "terraform-locks"
  billing_mode = "PAY_PER_REQUEST"
  hash_key     = "LockID"

  attribute {
    name = "LockID"
    type = "S"
  }
}

The backend block itself is configured in the root module as shown above; after terraform init, state operations use the remote backend automatically.

15

How does Terraform state locking work?

Terraform state locking is an exclusive, temporary lock that prevents multiple Terraform operations from modifying the same backend state concurrently. Terraform acquires the lock before a command reads state for an operation requiring coordination and normally releases it when the operation finishes.

Read full answer

Applies toTerraform 1.10+ with the S3 backend; locking support in other Terraform 1.x backends is backend-specific.

How the Locking Lifecycle Works

A typical remote-backend operation follows this sequence:

  1. Terraform authenticates to the backend and requests an exclusive lock.

  2. It reads the latest state after obtaining the lock.

  3. It performs the requested operation, such as planning or applying changes.

  4. It writes updated state when required.

  5. It releases the lock.

The lock applies to one backend state, not individual resources. Separate state files can therefore be modified concurrently. Commands that acquire the lock for the same state serialize through that lock.

Command Typical locking behavior
terraform plan Acquires a lock while reading state
terraform apply Locks state while reading, evaluating, and writing changes
terraform import Locks state because it changes state
terraform state mv or terraform state rm Locks state because it changes state
terraform output Does not modify state and normally does not require a lock
terraform validate Does not access remote state and does not require a lock

A lock timeout prevents a command from waiting indefinitely. For example, terraform plan -lock-timeout=10m -out=tfplan and terraform apply -lock-timeout=10m tfplan wait up to ten minutes for the lock. The saved plan should be reviewed before applying it so infrastructure is not changed based on an unreviewed or unexpectedly different plan.

Remote State and Lock Configuration

Production systems should use a remote backend rather than local state. A minimal S3 backend configuration sets bucket = "example-terraform-state", key = "prod/platform/terraform.tfstate", region = "us-east-1", encrypt = true, and use_lockfile = true under backend "s3". Initialize it with terraform init -reconfigure.

Native S3 locking was introduced in Terraform 1.10. The older DynamoDB locking option is deprecated but remains available for compatibility; current Terraform guidance recommends the native S3 lockfile for new configurations.

The backend should also be protected operationally:

  • Encryption: Enable S3 encryption at rest and require TLS for backend access.

  • Access control: Restrict state access to the CI system and authorized operators.

  • Versioning: Enable S3 bucket versioning to recover prior object versions after an overwrite or deletion.

  • Separate states: Use separate backend keys for environments, teams, or business units where independent locking is appropriate.

  • Backup and recovery: A lock prevents concurrent writes, but it does not protect against state loss.

Workspaces normally use separate state files within the backend, so their locks are independent. A lock on one workspace does not block a different workspace, even when both use the same S3 bucket.

Failure Modes and Recovery

The most common production failure is a second CI job attempting to use a state file already locked by another job. The second job waits until the lock timeout and then fails. This is safer than allowing both jobs to calculate changes from the same old state and overwrite one another.

A process crash, network failure, or infrastructure interruption can leave a lock behind. Terraform cannot safely assume that an old lock is abandoned because another process might still be running. Before removing a stale lock, verify that no Terraform process or CI job is active. Use terraform force-unlock <LOCK_ID> only after confirming that the lock is stale; it is not a routine concurrency workaround.

Other important failure modes include:

  • Backend or IAM failure: Terraform should fail before modifying infrastructure if it cannot acquire the lock or access state.

  • State drift: Locking does not detect drift. A normal plan refreshes remote objects and compares them with the recorded state.

  • Local backend limitations: A local file-based lock only coordinates processes sharing the same filesystem, making it unsuitable for distributed CI systems.

  • OpenTofu: OpenTofu uses the same general backend-locking model, but its supported backend features and options should be checked separately from Terraform.

Security and CI/CD Practices

State locking is a concurrency control, not a security mechanism. Terraform state commonly contains sensitive values such as database passwords, API tokens, private keys, and connection strings. Resources marked sensitive are still stored in state; sensitivity only affects display and plan output.

In CI/CD:

  • Store backend credentials in the CI secret manager, never in Terraform configuration.

  • Grant the CI role only the permissions needed for the selected state bucket and lockfile.

  • Use -lock-timeout to tolerate short-lived jobs without allowing indefinite blocking.

  • Save and review a plan artifact before applying it.

  • Protect the plan artifact because it may also contain sensitive values.

  • Monitor lock-acquisition failures, stale locks, unexpected state changes, and plan drift.

State locking prevents concurrent state mutation, while encryption, access control, versioning, backups, and operational monitoring provide the broader protection required for production infrastructure.

16

Which sensitive data enters Terraform state and how is it protected?

Terraform state can contain plaintext secrets because it records resource arguments and provider-returned attributes required to manage infrastructure, including database passwords, API keys, connection strings, private keys, Kubernetes secret data, and sensitive values returned by data sources. The sensitive flag controls redaction in normal human-readable output; it does not encrypt, hash, or remove a secret from state.

Read full answer

Applies toTerraform 1.10+ with the built-in S3 backend and AWS provider 5.x

Sensitive Data That Can Enter State

Terraform state generally contains:

  • Resource arguments and attributes: Explicitly configured secrets, such as aws_db_instance.password, and provider-generated credentials or private-key material.

  • Data-source results: Any sensitive value returned by a data source is persisted. Referencing a secret store’s ARN is different from reading the secret’s actual value; if Terraform resolves that value, it will usually enter state.

  • Output values: Both ordinary and sensitive root-module outputs are stored. Marking an output sensitive changes how it is displayed and propagated, not whether its value is stored.

  • Provider-returned metadata: Connection strings, tokens, certificates, endpoints, and similar attributes may reveal or contain credentials.

Input variable values are not normally stored as top-level state entries. However, when a sensitive variable is used in a resource argument, the resulting value can still be persisted as part of that resource’s state. Sensitive variable values can also appear in saved plan files.

Terraform state is normally represented as structured JSON, but JSON encoding or base64 encoding is not encryption. Confidentiality must be provided by the backend and its storage controls.

How State Should Be Protected

  • Use a controlled remote backend: Avoid leaving production state on developer laptops, ephemeral CI workers, or shared build containers. A remote backend improves availability and governance but is not secure merely because it is remote.

  • Encrypt state at rest: With the S3 backend, configure encrypt = true and use a customer-managed KMS key through kms_key_id where appropriate. Restrict KMS permissions separately from S3 permissions.

  • Require encryption in transit: Require S3 requests to use TLS and reject non-TLS access through bucket and IAM policy controls.

  • Enable state locking: Terraform 1.10+ supports S3-native locking through use_lockfile = true. This prevents concurrent state-writing operations, although it does not prevent unauthorized reads. The older DynamoDB locking mechanism is deprecated in favor of S3-native locking.

  • Apply least privilege: Permit state reads and writes only to the CI workload identity and explicitly authorized operators. Separate production, non-production, and unrelated trust domains into different state keys or buckets.

  • Protect the bucket: Block public access, enable versioning, use protected replication or backups where required, and regularly test restoration. MFA deletion may be appropriate for highly sensitive buckets.

  • Audit access: Enable the required S3 data-event auditing in CloudTrail, retain access logs, and alert on unexpected state reads, writes, lock-file activity, or KMS decrypt operations.

  • Prevent accidental publication: Ignore *.tfstate, .tfstate., .terraform.tfstate.lock.info, and saved plan files in Git. Treat CI workspaces and artifacts containing plans as confidential because saved plans can contain sensitive values.

Production Practices and Failure Modes

  • Prefer secret references where possible: Store credentials in AWS Secrets Manager, AWS Systems Manager Parameter Store, Vault, or another dedicated secret store. Configure Terraform to retain only an ARN or identifier when that is sufficient; avoid data sources that retrieve the underlying secret unless that exposure is explicitly accepted.

  • Use workload identity: Authenticate Terraform to cloud providers with OIDC or another short-lived identity mechanism rather than embedding access keys in variables, provider blocks, or long-lived CI environment variables.

  • Protect diagnostic output: terraform state pull, terraform output -json, terraform show -json, and saved-plan inspection can expose raw sensitive values even though ordinary console output redacts them. Do not publish these outputs to logs or unencrypted artifacts.

  • Review plans and imports carefully: Review changed addresses and sensitive-value annotations before approval. Importing a resource or adding a secret-reading data source can populate state with values that were not previously present.

  • Handle drift deliberately: A plan compares desired configuration with the current environment. Investigate unexpected changes rather than automatically accepting a plan, particularly when it affects secret storage or permissions.

  • Migrate state safely: Back up the original state, configure the destination backend, and use the supported terraform init -migrate-state workflow. Validate the resulting state before allowing normal operations.

  • Respond to compromise as a credential incident: Revoke state access, preserve audit evidence, rotate credentials that may have existed in the exposed state, and review downstream systems that Terraform managed.

  • Manage plans as confidential: Initialize with terraform init, save a plan with terraform plan -out=tfplan, and apply that exact plan with terraform apply tfplan. Remove the plan and any runner snapshots or artifacts according to the CI system’s confidential-data retention policy.

  • Account for OpenTofu: OpenTofu 1.x has the same state-content model. Use an encrypted, access-controlled, locked remote backend and apply equivalent secret-management and audit controls.

17

What are Terraform input variables and how do you set them?

Input variables are Terraform’s mechanism for parameterizing configuration so the same module can be reused across environments, regions, or teams without editing source code. They act as function parameters for a module and are declared with variable blocks.

Read full answer

Applies toTerraform 1.x (HCL2), AWS provider 5.x where examples use AWS resources.

How They Work

When Terraform evaluates a configuration, each variable block declares a named input with an optional type, default, description, and validation rules. Values are resolved at plan time from multiple sources in a defined precedence order. Variables can be referenced anywhere in the configuration as var.<name>. Root module variables become the public interface of a module; child module variables are passed explicitly through module blocks.

Declaring Variables

A variable block lives in any .tf file, conventionally variables.tf. Only name is required; everything else is optional but recommended for production use.

variable "instance_type" {
  type        = string
  default     = "t3.micro"
  description = "EC2 instance type for the web tier"

  validation {
    condition     = contains(["t3.micro", "t3.small", "t3.medium"], var.instance_type)
    error_message = "instance_type must be a supported t3 size."
  }
}

variable "vpc_cidr" {
  type    = string
  default = "10.0.0.0/16"
}

variable "tags" {
  type    = map(string)
  default = {}
}

Setting Values

Terraform resolves variable values from several sources, from lowest to highest precedence:

  1. Default value in the variable block.

  2. Environment variables named TF_VAR_<name> (e.g. TF_VAR_instance_type=t3.small).

  3. terraform.tfvars or *.auto.tfvars files in the working directory, loaded automatically.

  4. -var and -var-file flags on terraform plan/apply, in the order given.

If a variable has no default and no value from any source, Terraform prompts for it interactively (with -input=false in CI, it fails instead).

export TF_VAR_instance_type="t3.medium"
terraform plan -var="vpc_cidr=10.1.0.0/16" -var-file="prod.tfvars"

A typical prod.tfvars:

instance_type = "t3.medium" # must pass the validation rule above
tags = {
  Environment = "prod"
  Owner       = "platform-team"
}

Types and Validation

Supported types include string, number, bool, list, set, map, object, and tuple, plus any. Terraform performs type coercion where safe (e.g. "10" to number) but rejects incompatible values. The validation block runs a condition expression and fails the plan with a clear error message when it returns false, which is the right place to enforce naming conventions, CIDR ranges, or allowed regions.

Sensitive Variables and State Safety

Mark secrets with sensitive = true. This redacts the value from plan/apply output and from logs, but it does not remove it from state. When such a variable is passed to a resource attribute (for example password), the value is stored in state as part of that resource, and saved plan files also contain variable values. Mitigations:

  • Use a remote backend with encryption at rest and strict access controls (S3 with KMS, Terraform Cloud, etc.).

  • Enable state locking (use_lockfile = true for S3 on Terraform 1.10+, or a DynamoDB table on older versions) to prevent concurrent writes.

  • Prefer referencing secrets from a secret manager via data sources rather than passing them as variables where possible.

  • Never commit .tfvars containing secrets; load them from CI secret stores.

Best Practices

  • Always set description and a concrete type; avoid any in shared modules.

  • Provide sensible defaults only for non-environment-specific values; force explicit input for things like region or account.

  • Keep environment-specific values in per-environment .tfvars files or workspaces, not in code.

  • Run terraform plan in CI with -input=false and review the diff before apply; variables that change unexpectedly are a common source of drift.

  • Use sensitive = true for any credential, and rotate values through the secret manager rather than editing tfvars.

Code Example

# variables.tf
variable "environment" {
  type        = string
  description = "Deployment environment"
  validation {
    condition     = contains(["dev", "staging", "prod"], var.environment)
    error_message = "environment must be dev, staging, or prod."
  }
}

variable "db_password" {
  type      = string
  sensitive = true
}

# main.tf
resource "aws_db_instance" "main" {
  identifier = "app-${var.environment}"
  password   = var.db_password
  # ...
}
terraform plan -var-file="prod.tfvars" -input=false
18

How do variable validation rules work in Terraform?

Variable validation rules in Terraform are validation blocks inside a variable declaration that enforce constraints on input values before any plan or apply runs, failing fast with a custom error message.

Read full answer

Applies toTerraform 1.1+ (variable validation blocks since 0.13; OpenTofu 1.x compatible)

How It Works

When Terraform evaluates a variable, it runs each validation block’s condition expression against the supplied value. If any condition evaluates to false, Terraform aborts with the block’s error_message, before touching providers or state. This makes validation a cheap, early guardrail in both local runs and CI pipelines.

Validation Block Syntax

A variable block can contain one or more validation blocks, each with two required arguments:

  • condition — a boolean expression, typically referencing var.<name> and built-in functions such as contains, length, regex, or can.

  • error_message — a non-empty string shown when the condition fails; keep it actionable and specific.

Multiple validation blocks are evaluated independently, so you can separate concerns (format vs. allowed values) for clearer errors.

Type Constraints and Related Checks

Validation complements, but does not replace, the type constraint:

  • type rejects values of the wrong kind (e.g., a string where a number is expected) during evaluation.

  • validation enforces semantic rules (ranges, allowed sets, regex patterns, cross-field logic via functions).

  • nullable = false (Terraform 1.1+) rejects null even when the type would otherwise allow it.

  • sensitive = true redacts the value from plan output and logs; it does not remove it from state, so secrets still live in the state file.

Common Patterns

  • Allowed values: contains(["dev", "staging", "prod"], var.environment)

  • Numeric ranges: var.replica_count >= 1 && var.replica_count <= 10

  • Format checks: can(regex("^[a-z][a-z0-9-]{2,}$", var.name))

  • Non-empty collections: length(var.subnet_ids) > 0

Production Considerations

  • Validation runs during terraform plan, so bad inputs fail in CI before any infrastructure changes; wire terraform validate and terraform plan into pull-request checks.

  • Because error_message is shown to operators, avoid leaking secrets or internal naming in it.

  • sensitive only hides output; combine it with a secrets manager and never commit .tfvars containing credentials. State files still contain sensitive values, so protect remote backends with encryption and least-privilege access.

  • Validation cannot reference other variables directly; express cross-variable rules via a single object variable or move complex checks into policy-as-code tools such as Sentinel or OPA.

Best Practices

  • Prefer type constraints first, then validation for business rules.

  • Keep conditions pure and deterministic; avoid side effects.

  • Provide messages that state the valid range or format, not just “invalid value”.

  • Test validation with terraform test (Terraform 1.6+) by asserting plan failures for bad inputs.

  • Review validation changes in pull requests, since loosening a rule can widen the blast radius of a misconfigured apply.

19

What are local values in Terraform?

Local values are named expressions within a Terraform module that derive reusable values from input variables, resource attributes, data-source results, functions, and other local values. They allow a module to calculate a value once and reference it as local.name without creating infrastructure or storing the local as an independent state object.

Read full answer

Applies toTerraform 1.x

Purpose

Terraform provides three related value mechanisms:

Mechanism Direction Purpose State behavior
Input variables Caller → module Accept values from outside the module Not stored independently
Local values Within a module Derive and reuse expressions Not stored independently
Output values Module → caller Expose module results Root-module outputs are recorded in state; child-module outputs are not separate top-level state entries

Local values are useful for:

  • Standardizing names: Combining an environment and workload name into a consistent resource name.

  • Centralizing configuration: Defining common tags, subnet lists, or naming conventions once.

  • Transforming data: Calculating CIDRs, formatted strings, or account-specific identifiers.

  • Simplifying expressions: Keeping resource definitions readable and maintainable.

  • Conditional logic: Selecting values based on an environment, region, or feature flag.

Declaration and Scope

Local values are declared in one or more locals blocks. Each identifier in a block is assigned an expression, and it is referenced elsewhere in the same module by adding the local. prefix.

  • Each local name must be unique within its module.

  • A local can reference other locals in the same module.

  • A local can reference resource attributes and data-source results. Terraform’s dependency graph determines the evaluation order rather than the textual order of declarations.

  • Child modules do not inherit the parent module’s locals. Values must be passed to a child module through its input variables.

  • A local value does not create a cloud resource or an independent object in Terraform state.

Evaluation and Unknown Values

Locals are expressions, so their values are evaluated during Terraform’s plan and apply phases. If a local depends on a resource attribute that is unknown until apply, the local and any dependent resources can also remain unknown until that attribute is resolved.

Terraform rejects cyclic dependencies. For example, a local cannot depend on itself directly or through another local because Terraform must determine a valid evaluation order.

State, Secrets, and Drift

A local is not stored independently in state. However, if its value is copied into a resource attribute or an output, that resulting value can still be recorded in state.

Terraform does not support marking a local declaration with sensitive = true; the sensitive meta-argument applies to input variables and outputs. Even when an output is marked sensitive, Terraform redacts it from normal CLI output but does not encrypt it in state. Avoid placing secrets directly in locals when they will be persisted. Instead, retrieve secrets from a secret manager and use ephemeral or provider-supported write-only values where available.

For production use, protect remote state with encryption, locking, restricted access, versioning, and suitable backup retention. Secrets can otherwise remain in historical state versions, so state access and retention controls are important.

Production Practices

  • Use locals for derivation rather than as a substitute for clearly defined module inputs and outputs.

  • Review plans for changes caused by computed values, especially where unknown results are deferred until apply.

  • Run terraform fmt and terraform validate before creating a plan.

  • Review terraform plan output before applying it through an automated CI/CD workflow.

  • Run periodic plans against production to detect drift, and investigate unexpected changes rather than applying them automatically.

  • Keep backend and provider compatibility in mind when migrating from Terraform to OpenTofu; OpenTofu supports comparable local-value behavior, but providers and backends should be tested separately.

20

How do Terraform outputs pass values between modules?

Terraform module outputs are the return values a child module publishes to its caller. The parent reads them as module.<name>.<output_name> and can pass those values into other modules or expose them as root outputs.

Read full answer

Applies toTerraform 1.x with AWS provider 5.x

How Outputs Work

An output block defines a named value:

# modules/network/outputs.tf
output "vpc_id" {
  description = "The ID of the VPC created by this module."
  value       = aws_vpc.main.id
}

Terraform evaluates output expressions during planning when their dependencies are known. Values dependent on resources that do not yet exist remain unknown during planning and are finalized during application. Root-module output values are persisted in Terraform state; child-module outputs are exposed to their parent and become persisted indirectly when included in a root output.

The two main uses are:

  • Module communication: A child module publishes values that its caller can access.

  • External visibility: Root-module outputs can be read by operators, CI/CD systems, or other automation.

Outputs do not replace input variables. Use variables for values passed into a module and outputs for values returned from it.

Using Outputs Across Modules

Suppose the network module publishes its VPC ID. The parent accesses it through the module label and output name:

module "network" {
  source = "./modules/network"
}

module "application" {
  source = "./modules/application"

  vpc_id = module.network.vpc_id
}

The referenced value is module.network.vpc_id, not a global variable. Terraform derives the dependency graph from these references, so the application module can depend on the network module’s output.

A module can also expose a value calculated from several resources. For example, value = aws_subnet.private[*].id exposes a list of subnet IDs, which the caller reads as module.network.private_subnet_ids.

Root Outputs and the CLI

Root-module outputs are available through the Terraform CLI:

terraform init
terraform plan
terraform apply
terraform output
terraform output -json

For example:

# outputs.tf
output "vpc_id" {
  description = "VPC ID for downstream systems."
  value       = module.network.vpc_id
}

terraform output -json is useful for scripts, but sensitive output values can be printed in plaintext by both terraform output and terraform output -json.

Code Example

The following configuration creates a VPC in one module, passes its ID into a second module, and publishes the resulting subnet ID at the root.

# main.tf
terraform {
  required_version = ">= 1.0.0, < 2.0.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "us-east-1"
}

module "network" {
  source = "./modules/network"
}

module "application" {
  source = "./modules/application"
  vpc_id = module.network.vpc_id
}
# modules/network/main.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
}
# modules/network/outputs.tf
output "vpc_id" {
  description = "The VPC ID."
  value       = aws_vpc.main.id
}
# modules/application/main.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

variable "vpc_id" {
  description = "The VPC where the application subnet is created."
  type        = string
}

resource "aws_subnet" "main" {
  vpc_id            = var.vpc_id
  cidr_block        = "10.0.1.0/24"
  availability_zone = "us-east-1a"
}
# modules/application/outputs.tf
output "subnet_id" {
  description = "The application subnet ID."
  value       = aws_subnet.main.id
}
# outputs.tf
output "application_subnet_id" {
  description = "Subnet ID created for the application."
  value       = module.application.subnet_id
}

Production and Best Practices

  • Keep state secure: Root outputs are stored in Terraform state. Use an encrypted remote backend, least-privilege access, and a backend that supports state locking.

  • Treat sensitivity correctly: sensitive = true redacts values in plan and user-interface contexts and propagates sensitivity through references, but it does not encrypt state or prevent terraform output from printing values in plaintext.

  • Avoid exposing secrets unnecessarily: Retrieve secrets from AWS Secrets Manager or another secret manager at runtime rather than passing credentials through module outputs.

  • Review module contracts: Document output names, inferred types, sensitivity, and stability. Expose meaningful contracts rather than every resource attribute.

  • Manage drift: Root-module outputs are derived values recorded in state. Run terraform plan regularly and review output and infrastructure changes before applying.

  • Use reviewed CI/CD plans: Run terraform plan -out=tfplan, review the saved plan, and apply that exact plan with terraform apply tfplan. Protect backend credentials and ensure the backend supports locking.

  • Prefer explicit dependencies: Module output references establish dependencies naturally. Use depends_on only for ordering that cannot be expressed through data or resource references.

21

How does Terraform handle sensitive variables and outputs?

Sensitive is Terraform’s metadata for suppressing secret values in CLI output. Marking a variable or output sensitive controls redaction; it does not encrypt the value or prevent it from being stored in Terraform state.

Read full answer

Applies toTerraform 1.10+ (1.x), current OpenTofu 1.x, and AWS provider 5.x

Core Behavior

Terraform tracks sensitivity while evaluating its configuration graph:

  • Sensitive variables are declared with sensitive = true.

  • Sensitive outputs are declared with sensitive = true.

  • Terraform redacts sensitive values in normal plan, apply, and output displays.

  • Sensitivity propagates when a sensitive value is used in another expression, including module inputs and outputs.

  • Redaction is a display safeguard, not an access-control boundary.

A sensitive value can still appear in automation outputs such as terraform output -json, terraform show -json, or terraform state pull. Protect these outputs as secret material.

Variables Compared with Outputs

Aspect Sensitive variable Sensitive output
Purpose Accepts a secret input Publishes a value from the configuration
Declaration variable block with sensitive = true output block with sensitive = true
Typical source CI secret, environment variable, secret manager Sensitive variable or sensitive resource attribute
Consumers Resources and modules within the configuration Root modules, parent modules, or command-line automation
Stored in state Input values can exist in state Output values are recorded in state
Display Redacted in normal CLI output Redacted in normal CLI output

A variable’s type does not automatically make it sensitive. Likewise, marking an output sensitive does not encrypt the underlying value or make a resource attribute secure.

State and Production Security

Terraform state may contain secret values in a recoverable form. The sensitive flag has no effect on state contents.

Production state should therefore use:

  • A remote backend with encryption at rest, such as S3 server-side encryption with AWS KMS.

  • Backend locking to prevent concurrent operations from corrupting state or applying conflicting plans.

  • Strict IAM access, preferably using short-lived workload identities rather than static credentials.

  • Versioned, encrypted state backups with equally strict access controls.

  • Audit logging for state downloads, backend access, and infrastructure changes.

  • Protection for plan files, CI artifacts, logs, and terraform output -json files because they may contain secrets.

Terraform 1.10+ supports S3 backend locking through use_lockfile = true. Older Terraform 1.x releases used DynamoDB-based locking. OpenTofu supports the same general sensitive-value model, but backend locking and encryption capabilities should be checked against the OpenTofu and backend versions in use.

Operational Failure Modes

  • Partial apply: A failed apply can leave resources created and their values recorded in state.

  • State corruption: Concurrent writes can damage state; use locking and never bypass it to “make the apply work.”

  • Undetectable drift: If a secret is rotated outside Terraform, the next plan may show drift or continue managing the old value. Decide explicitly which system owns rotation.

  • Over-redaction: Sensitive plan changes may show only (sensitive value), making review harder. Review configuration changes separately without exposing the secret in shared logs.

  • Accidental publication: A sensitive output can be consumed by another module or automation system. Redaction does not prevent downstream misuse.

Code Example

terraform {
  backend "s3" {
    bucket       = "example-terraform-state"
    key          = "production/app/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    kms_key_id   = "arn:aws:kms:us-east-1:111122223333:key/example-key-id"
    use_lockfile = true
  }
}

variable "api_token" {
  type      = string
  sensitive = true
}

output "api_token" {
  value     = var.api_token
  sensitive = true
}

Inject the value through a CI secret or protected shell environment:

export TF_VAR_api_token='replace-with-a-secret-from-your-secret-manager'

terraform init -reconfigure
terraform plan -out=tfplan
terraform apply tfplan
terraform output api_token

The final command redacts the value, but the secret still exists in state and in the saved plan. The example output should normally be omitted in production; publish a secret identifier or ARN instead.

Best Practices

  • Prefer an external secret manager and have Terraform manage only non-secret metadata, such as a secret ARN.

  • Use TF_VAR_<name> or protected CI secret injection instead of committing secrets to .tfvars files.

  • Avoid passing secrets with -var, because command-line arguments may appear in shell history or process listings.

  • Mark module inputs and outputs sensitive so secrets remain sensitive across module boundaries.

  • Keep remote state encrypted, locked, access-controlled, backed up, and audited.

  • Save and review plans with terraform plan -out=tfplan, then apply that exact plan with terraform apply tfplan.

22

What is the difference between count and for_each in Terraform?

In Terraform, count and for_each are both meta-arguments that create multiple instances of a resource or module, but they identify instances differently: count produces a numbered list indexed by position, while for_each produces a map keyed by stable string identifiers.

Read full answer

Applies toTerraform 1.x (examples use AWS provider 5.x).

How They Work

  • count takes an integer and creates that many instances, addressed as resource.name[0], resource.name[1], etc. Inside the block you reference count.index.

  • for_each takes a map or a set of strings and creates one instance per key, addressed as resource.name["key"]. Inside the block you reference each.key and each.value.

  • Setting count = 0 or for_each = {} creates no instances, which is the common pattern for conditionally creating a single resource.

State Addresses and Drift

  • With count, instances are tied to their position in a list. Reordering or removing an element from the middle shifts every later index, so Terraform plans destroys and recreations even though the underlying objects did not change.

  • With for_each, instances are tied to their key. Adding or removing one key only affects that instance; the rest of the state is untouched.

  • This is the main reason for_each is preferred for collections of distinct objects, while count suits truly identical copies or simple on/off toggles.

Comparison

Aspect count for_each
Input integer map or set of strings
State address [0], [1] ["key"]
Stability position-based, fragile to reordering key-based, stable
Conditional creation count = var.enabled ? 1 : 0 for_each = var.enabled ? tomap({...}) : {}
Best for N identical copies, feature toggles named, distinct instances

Common Pitfalls and Best Practices

  • Do not use count over a list of objects whose order can change; prefer for_each with a map keyed by a stable name.

  • for_each keys must be known at plan time. You cannot use values that are only computed during apply as keys.

  • You cannot combine count and for_each on the same resource or module.

  • Switching an existing resource from count to for_each changes its state address. Use terraform state mv to migrate instances, or the plan will destroy and recreate them.

  • Both forms store full resource attributes in state, including sensitive values. Keep state in a remote backend with locking and encryption, and review plans before applying.

  • When importing existing infrastructure, the import address must match the chosen form, e.g. aws_subnet.named["public_a"] versus aws_subnet.public[0].

  • OpenTofu supports the same count and for_each meta-arguments.

23

How do dynamic blocks work in Terraform?

A dynamic block in Terraform generates zero or more nested configuration blocks from a collection. It is useful when the number of repeated blocks—such as firewall rules or storage settings—depends on a variable or computed value.

Read full answer

Applies toTerraform 1.x with AWS provider 5.x

How They Work

A dynamic block has two important elements:

  • for_each: Defines the collection Terraform iterates over. It can be a list, set, or map.

  • content: Defines the nested block generated for each collection element.

For example, Terraform can expand a list of ingress rules into multiple ingress blocks belonging to one aws_security_group. Each iteration behaves as though the nested block had been written manually.

Inside content, the current element is accessed through the block name:

  • ingress.value: The current list or set element.

  • ingress.key: The current map key.

  • iterator: An optional custom name that replaces the default iterator, which is helpful when nested dynamic blocks use similar names.

Dynamic blocks operate during Terraform’s configuration evaluation. Terraform expands them before sending the resulting configuration to the provider, so the provider sees ordinary nested blocks rather than a special dynamic structure.

When to Use Them

Dynamic blocks are appropriate when:

  • A resource needs a variable number of nested blocks.

  • The same nested configuration is repeated across multiple elements.

  • Generating blocks from a map makes configuration easier to maintain than manually duplicating them.

They should not be used when:

  • The nested block is fixed and can be written normally.

  • The provider already accepts the same information as a list or map argument.

  • You want to create multiple resources. Use count or for_each on the resource itself for that purpose.

A dynamic block is a Terraform configuration construct; it does not independently create resources or state objects.

Code Example

This example creates multiple ingress rules on an AWS security group:

terraform {
  required_version = ">= 1.0, < 2.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

variable "vpc_id" {
  type = string
}

variable "ingress_rules" {
  type = list(object({
    from_port   = number
    to_port     = number
    protocol    = string
    cidr_blocks = list(string)
  }))
  default = []
}

resource "aws_security_group" "application" {
  name_prefix = "application-"
  vpc_id      = var.vpc_id

  dynamic "ingress" {
    for_each = var.ingress_rules

    content {
      from_port   = ingress.value.from_port
      to_port     = ingress.value.to_port
      protocol    = ingress.value.protocol
      cidr_blocks = ingress.value.cidr_blocks
    }
  }
}

For a list, ingress.value is the complete rule object. For a map, ingress.value is the map value and ingress.key identifies its key. Setting iterator = rule would replace the default iterator name, allowing the content to reference rule.value and rule.key.

Operational and State Considerations

  • Plan review: Always inspect the rendered plan to confirm that the expected number of blocks was generated. A dynamic expression can silently produce fewer or different rules than intended.

  • Unknown values: The collection must be sufficiently known during planning. Avoid using dynamic expansion to define structure solely from values that will first become known during apply.

  • State exposure: Dynamic blocks do not automatically make data sensitive or prevent it from entering Terraform state. Avoid placing credentials, tokens, or private keys directly in configuration.

  • Drift detection: With a recent provider schema, dynamic blocks participate in drift detection like statically declared blocks.

  • State management: Use a remote backend with locking, encryption, access controls, and versioning. Dynamic-block expansion does not replace these protections.

  • Provider upgrades: A provider upgrade can change nested-block schemas. Review the generated plan before upgrading AWS provider 5.x or later releases.

Best Practices and Pitfalls

  • Prefer a static block for one fixed occurrence; dynamic blocks add unnecessary abstraction.

  • Use typed variables so invalid rules fail during validation rather than during apply.

  • Validate the final plan in CI/CD before approval or application.

  • Keep the dynamic block near the resource it configures and document the expected collection shape.

  • Do not use dynamic to work around a provider argument that already accepts a collection.

  • OpenTofu supports the same HCL dynamic-block pattern, but provider schemas and validation behavior still depend on the provider version being used.

24

How do Terraform conditional expressions select values?

Conditional expressions in Terraform evaluate a Boolean condition and return one of two result values. The form condition ? true_value : false_value lets configuration vary without duplicating entire resources.

Read full answer

Applies toTerraform 1.9+ within the 1.x line, AWS provider 5.x in the example

Syntax and Evaluation

A conditional expression contains three parts:

  • Condition: A Boolean expression, commonly using ==, !=, &&, ||, or !.

  • True result: Returned when the condition is true.

  • False result: Returned when the condition is false.

Common condition sources include input variables, local values, and data-source attributes. For example, var.environment == "prod" and data.aws_region.current.name == "us-east-1" are valid conditions. Parentheses can group compound expressions.

Terraform evaluates the condition and selects the corresponding result while constructing the configuration. Changing a referenced variable or data-source value can therefore change the planned result.

Conditional expressions can also control resource existence:

Mechanism Behaviour and trade-off
count = condition ? 1 : 0 Simple, but removing the instance destroys it; multiple instances use numeric addresses such as [0].
for_each = condition ? { audit = true } : {} Uses stable string keys and avoids index shifts, but adding or removing keys still creates or destroys instances.

Type and Value Rules

  • Result conversion: Terraform converts compatible result types to a common type. Incompatible results cause a type error during evaluation, validation, or planning.

  • Explicit conversion: tostring(), tonumber(), and tobool() make intended conversions clear when branches may have different types.

  • No truthiness: The condition must be Boolean. Terraform does not treat an arbitrary non-empty value as true; write an explicit comparison when necessary.

  • Unknown conditions: The conditional result remains unknown. Terraform may resolve some ordinary values during apply, but an unknown condition cannot control count or for_each because Terraform must know the resource instances before planning.

  • Reevaluation: Changing an input used by the condition can select the other branch in a subsequent plan.

Modules, Workspaces, and Testing

  • Modules: Pass typed variables into modules and expose selected values through outputs. Conditionals work normally inside modules.

  • Workspaces: A workspace selects a named state within the configured backend. It is not a security boundary and should not replace separate production credentials or approval controls.

  • Import: terraform import brings an existing object into state; it does not evaluate conditional expressions. Add equivalent configuration before the next plan to prevent Terraform from proposing replacement.

  • Testing: Terraform 1.9’s terraform test framework can use .tftest.hcl files to assert the outputs produced by each conditional branch.

Code Example

The following configuration selects an S3 bucket name and versioning status. The account ID reduces the risk of a global S3 bucket-name collision.

terraform {
  required_version = ">= 1.9.0, < 2.0.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

variable "environment" {
  type    = string
  default = "dev"

  validation {
    condition     = contains(["dev", "prod"], var.environment)
    error_message = "environment must be either dev or prod."
  }
}

variable "aws_region" {
  type    = string
  default = "us-east-1"
}

provider "aws" {
  region = var.aws_region
}

data "aws_caller_identity" "current" {}

locals {
  account_id = data.aws_caller_identity.current.account_id

  # Select one complete bucket name during planning.
  bucket_name = var.environment == "prod" ? "prod-example-${local.account_id}-app" : "dev-example-${local.account_id}-app"
}

resource "aws_s3_bucket" "app" {
  bucket = local.bucket_name

  tags = {
    Environment = var.environment
    ManagedBy   = "Terraform"
  }
}

resource "aws_s3_bucket_versioning" "app" {
  bucket = aws_s3_bucket.app.id

  versioning_configuration {
    status = var.environment == "prod" ? "Enabled" : "Suspended"
  }
}

output "bucket_id" {
  value = aws_s3_bucket.app.id
}

Typical commands are:

terraform fmt -check
terraform init
terraform validate
terraform plan -out=tfplan
terraform apply tfplan

Supply AWS credentials through environment variables, workload identity, or CI/CD OIDC; do not put credentials directly in Terraform configuration.

Operational Behavior and Failure Modes

  • Unexpected branch selection: Validate enumerated values and require explicit approval for production changes.

  • Type errors: Convert branch values explicitly when necessary.

  • Unstable inputs: Timestamps and random values are normally unknown during planning and cannot determine count or for_each. Prefer stable, approved inputs.

  • Resource changes: A known input change can update, replace, or destroy resources depending on provider schema. Use lifecycle { prevent_destroy = true } for appropriate critical resources, while retaining backups and plan review.

  • Provider validation: The selected result remains subject to AWS provider and service-side validation.

State Safety and CI/CD

Conditional results and resource attributes are persisted in state, so sensitive values can still appear there.

  • Use a remote backend with encryption, access controls, locking, backups, and versioning where supported.

  • Mark sensitive outputs as sensitive = true; this only redacts normal CLI output and does not remove values from state.

  • Review plans for branch-dependent encryption, public access, retention, count, and for_each changes.

  • Use terraform plan -refresh-only to reconcile state with remote drift, followed by a separate review.

  • In CI/CD, use short-lived credentials, save a plan, review it, and apply that exact plan.

  • Protect saved plan files as sensitive artifacts because they can contain sensitive values.

OpenTofu supports the same conditional-expression syntax and the same state-safety practices.

25

What are Terraform built-in functions and common examples?

Terraform built-in functions are reusable expression operations provided by Terraform core for type conversion, string and collection manipulation, calculations, encoding, filesystem access, and controlled error handling. They return values that can be used in resources, data sources, variables, locals, outputs, module arguments, and condition expressions.

Read full answer

Applies toTerraform 1.x (`plantimestamp` requires 1.5+; provider-defined functions are stable in 1.8+); OpenTofu 1.6+

Core Behavior

  • Built-in functions evaluate expressions and return a value; they do not create or manage infrastructure themselves.

  • Most functions are deterministic. Time- or randomness-dependent functions such as timestamp(), uuid(), and plantimestamp() can create perpetual plan differences when used directly in managed-resource attributes.

  • uuidv5() is deterministic when given the same namespace UUID and name, making it more appropriate for reproducible identifiers.

  • Provider-defined functions are separate from Terraform core functions and require a compatible provider and Terraform version.

  • OpenTofu supports Terraform-compatible core functions, but provider-defined functions and version-specific additions should be checked against the OpenTofu documentation.

Common Function Families

Category Examples Typical use
Type conversion tostring, tonumber, tobool, tolist, toset, tomap Normalize input types
Strings upper, lower, trimspace, replace, split, join, format, substr, regex, regexall Build names, identifiers, and URLs
Collections length, concat, contains, keys, values, lookup, merge, flatten, distinct, range, sort Combine and inspect collections
Numbers max, min, ceil, floor, abs, parseint Perform arithmetic and conversions
Networking cidrhost, cidrnetmask, cidrsubnet, cidrsubnets Allocate addresses and subnets
Encoding jsonencode, jsondecode, yamlencode, yamldecode, base64encode, base64decode, urlencode, csvdecode Serialize or transport data
Date and time formatdate, timeadd, timecmp, timestamp, plantimestamp Format timestamps and calculate time
Files and templates file, fileexists, fileset, templatefile, abspath, dirname, basename Load files and render templates
Fallbacks try, can, coalesce Handle missing or invalid values safely
Sensitive values sensitive, nonsensitive Control CLI redaction of values
Hashing and identifiers md5, sha256, sha512, uuid, uuidv5 Create checksums or identifiers

Evaluation and Error Semantics

  • try(): Evaluates expressions in order and returns the first result that evaluates without a dynamic error. It does not catch syntax errors, invalid configuration, or other failures that occur before expression evaluation.

  • can(): Returns true when an expression can be evaluated successfully and false when it encounters a catchable evaluation error.

  • coalesce(): For string arguments, returns the first non-null, non-empty string. It returns an error if every argument is null or empty.

  • lookup(): Reads a key from a map or object and supplies a default when the key is absent.

  • templatefile(): Renders a template file using a supplied variable map. The template and any referenced files must exist and be readable during evaluation.

  • file(): Reads a file as a string; the file must contain valid UTF-8.

  • sensitive(): Marks a value for redaction in normal CLI output. It does not encrypt the value or prevent it from being stored in state.

  • nonsensitive(): Removes sensitive marking and can expose a value in plan output. Use it only when the value is demonstrably safe to display.

Production Best Practices and Pitfalls

  • Protect state: Use a supported remote backend with encryption, restricted access, locking, versioning, and backups. Sensitive values remain present in state, so never commit state or saved plan files containing secrets.

  • Review transformations: Inspect computed names, CIDRs, endpoints, rendered templates, and generated configuration in every plan. Functions can hide consequential changes.

  • Keep evaluation reproducible: Avoid depending on implicit local-machine state. Pass file locations and other external inputs explicitly, and ensure modules receive all required values.

  • Validate in CI: A source-only job can run terraform fmt -check -recursive, terraform init -backend=false, and terraform validate. An apply job should initialize the configured backend, run terraform plan -out=tfplan, review it with terraform show -no-color tfplan, and apply that exact saved plan only after approval.

  • Test behavior: Use terraform test on Terraform 1.6+ or the corresponding OpenTofu test command when supported. Treat the saved plan artifact as sensitive because it can contain sensitive values.

  • Detect drift: Functions do not monitor or repair infrastructure. Regular terraform plan runs compare configuration and refreshed provider state to reveal drift.

26

How does Terraform construct its dependency graph?

Terraform constructs a dependency graph by representing configuration objects as nodes and connecting objects whose expressions reference one another. The graph determines evaluation and operation ordering while allowing independent work to proceed concurrently.

Read full answer

Applies toTerraform 1.6+ (Terraform 1.x); OpenTofu 1.x where noted

How the Graph Is Built

Terraform loads the root module and any referenced modules, then transforms their configuration into graph nodes. These can represent:

  • Managed resources and resource instances: Individual infrastructure objects that Terraform creates, updates, or destroys.

  • Data sources: Reads of existing infrastructure whose results can feed other configuration.

  • Module calls and expanded module contents: Modules participate in the same graph as root-module objects.

  • Variables, local values, and outputs: Input, intermediate, and result nodes used to connect configuration objects.

  • Provider configurations: Resources are associated with the provider configuration they require.

Terraform then performs reference analysis over HCL expressions. If resource B reads an attribute of resource A, Terraform creates a dependency edge ensuring that A is evaluated or applied before B. References through variables, locals, module inputs and outputs, functions, conditionals, and collection expressions are all considered.

Most dependencies are implicit because they arise from ordinary expression references. For example, a policy resource that reads a bucket resource’s id depends on that bucket. Terraform does not infer dependencies from file order, resource names, shared tags, or two resources merely using the same provider.

Explicit Dependencies and Graph Ordering

Terraform also supports the depends_on meta-argument for resource and module blocks. It adds an ordering dependency even when no expression reference exists. This is appropriate for a genuine operational dependency, but unnecessary uses can over-serialize unrelated resources and create dependency cycles.

Terraform rejects cycles during graph construction rather than inventing an arbitrary order. Graph transformations subsequently expand count and for_each, resolve module instances, and account for lifecycle behavior such as create_before_destroy.

During planning and application:

  • Dependencies are evaluated before their dependents.

  • Independent operations may execute concurrently.

  • Data-source reads are normally performed during planning when their arguments are known.

  • If a data source requires values that remain unknown until apply, its read is deferred until apply.

  • During destruction, Terraform generally destroys a dependent object before the object on which it depends.

  • Replacement operations can alter ordering because creation and destruction may be inverted for create_before_destroy.

Inspecting the Graph

The terraform graph command renders the dependency graph in DOT format. Its plan and apply graph types show the graph before and after apply-specific transformations. This is useful for investigating unexpected ordering, but normal workflows should still use terraform plan and terraform apply, which evaluate actual provider behavior and proposed changes.

A typical CI/CD sequence is to run terraform init, terraform fmt -check, terraform validate, and any framework or module tests before producing a saved plan. A reviewer should inspect that saved plan, and production automation should apply the reviewed artifact rather than regenerate a different plan.

State Safety and Drift

The dependency graph does not make Terraform state safe or consistent. Production teams should use an encrypted, access-controlled remote backend with locking, retain recoverable or versioned state where supported, and monitor lock contention, failed applies, and backend availability.

State can contain sensitive values even when an output is marked sensitive; that setting only controls display. Credentials should therefore come from an appropriate secrets mechanism or provider credential chain rather than being embedded in configuration.

Regular terraform plan runs refresh the relevant state and expose drift between Terraform’s recorded state and remote infrastructure. Reviewed plans should be used for production changes. When adopting existing infrastructure, terraform import can bring objects under management, but the resulting state and subsequent plans must be reviewed carefully because imports do not automatically correct every configuration mismatch.

Modules, Workspaces, Testing, and Upgrades

Modules should have documented inputs and outputs, explicit version constraints, and their own validation and tests. Module output references become part of the caller’s dependency graph, allowing Terraform to schedule upstream work before downstream consumers.

Each Terraform workspace uses a separate state namespace, commonly through backend-specific workspace naming. The dependency graph itself comes from configuration and references; workspace selection determines which state is used during refresh, plan, and apply, so automation must select the intended workspace explicitly.

Terraform 1.6+ provides terraform test for .tftest.hcl tests; provider mocking (mock_provider, override_resource) requires Terraform 1.7+. Provider and Terraform upgrades should be constrained, tested against representative state, and rolled out through the same reviewed plan-and-apply pipeline. OpenTofu 1.x follows the same general dependency model while using its corresponding CLI, backend, and locking mechanisms.

27

What is depends_on in Terraform and when to use it?

depends_on is Terraform’s mechanism for declaring an explicit dependency between resources or modules when no attribute reference exists to infer ordering automatically.

Read full answer

Applies toTerraform 1.x with AWS provider 5.x (and OpenTofu 1.x)

How It Works

Terraform builds a directed acyclic graph (DAG) of resources before applying. Edges come from two sources:

  • Implicit dependencies: created automatically when one resource references another’s attribute, e.g. subnet_id = aws_subnet.main.id. Terraform knows aws_subnet.main must be created first.

  • Explicit dependencies: declared with depends_on = [aws_iam_role_policy.app], adding a graph edge even though no attribute is referenced.

During apply, Terraform walks the graph in topological order, creating independent resources in parallel and waiting where edges require it. The same ordering applies in reverse during destroy.

When to Use It

  • A resource depends on a side effect not captured by attributes, such as an IAM policy that must exist before an EC2 instance boots and calls AWS APIs, even though the instance never references the policy’s ARN.

  • Ordering between modules where outputs do not carry the dependency.

  • Forcing a null_resource or provisioner to run only after a resource is fully created.

  • Ensuring a database user exists before an application container starts, when the connection string is supplied separately.

Caveats and Pitfalls

  • Applying depends_on to a module makes every resource in that module depend on the target, which can serialize large parts of the graph and slow plans and applies.

  • It hides real data flow; prefer passing values through variables and outputs so dependencies stay implicit and visible.

  • It guarantees creation ordering, not readiness. Terraform considers a resource done when the API returns success, so use health checks, time_sleep, or application-level retries for actual readiness.

  • Overuse makes plans harder to reason about and can mask missing references.

Code Example

resource "aws_iam_role" "app" {
  name = "app-role"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Action    = "sts:AssumeRole"
      Effect    = "Allow"
      Principal = { Service = "ec2.amazonaws.com" }
    }]
  })
}

resource "aws_iam_role_policy" "app" {
  name   = "app-policy"
  role   = aws_iam_role.app.id
  policy = jsonencode({
    Version = "2012-10-17"
    Statement = [{
      Action   = ["s3:GetObject"]
      Effect   = "Allow"
      Resource = "arn:aws:s3:::example-bucket/*"
    }]
  })
}

resource "aws_instance" "app" {
  ami           = "ami-0c55b159cbfafe1f0"
  instance_type = "t3.micro"

  # No attribute of the policy is referenced, but the instance
  # needs the policy attached before it starts calling AWS APIs.
  depends_on = [aws_iam_role_policy.app]
}

Best Practices

  • Prefer implicit dependencies via attribute references; they are self-documenting.

  • Scope depends_on to the smallest resource, never an entire module, unless unavoidable.

  • Add a comment explaining why the explicit edge is needed.

  • Review terraform plan output for unexpected serialization or long apply times.

  • In CI, run terraform plan on every change and require review before apply to catch dependency mistakes early.

28

How do Terraform lifecycle rules affect resource replacement and deletion?

Lifecycle rules are Terraform meta-arguments that control how resources are replaced, updated, or protected from deletion. They change Terraform’s execution plan but do not make infrastructure changes atomic or protect resources from manual deletion outside Terraform.

Read full answer

Applies toTerraform 1.x with AWS provider 5.x

How Lifecycle Rules Work

Terraform refreshes its state, compares the observed infrastructure with the configuration, and builds a dependency graph containing create, update, replace, and destroy actions.

  • Replacement occurs when an immutable argument changes, such as an EC2 instance’s instance_type or an AMI.

  • With create_before_destroy, Terraform creates the replacement before destroying the original.

  • The original remains tracked as a deposed object until its destruction succeeds.

  • If creation fails, the original normally remains available. If destruction fails afterward, Terraform can retain the deposed object for a later operation.

  • Ordering is not transactional: creation can succeed while subsequent destruction fails, leaving duplicate resources and temporary double costs.

Rule Comparison

Rule Behavior Production implications
create_before_destroy Creates a replacement before destroying the original Reduces downtime, but temporarily doubles resources, usage, and cost
prevent_destroy Rejects a plan that would destroy the resource Protects critical infrastructure from accidental deletion
ignore_changes Suppresses normal updates for listed arguments Can conceal configuration drift and unexpected infrastructure changes
replace_triggered_by Forces replacement when a referenced object changes Useful for propagating changes through tightly coupled resources

prevent_destroy also blocks replacement when the old resource must be destroyed. It protects against Terraform-driven deletion, but it does not prevent API-level deletion, terraform state rm, or removal of the lifecycle block in a later reviewed change.

Code Example

The EC2 instance can run concurrently during replacement, so create_before_destroy is appropriate. The S3 bucket uses a generated unique name and is protected from Terraform-driven deletion.

terraform {
  required_version = ">= 1.0, < 2.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "us-east-1"
}

variable "instance_type" {
  type    = string
  default = "t3.micro"
}

data "aws_ami" "amazon_linux" {
  most_recent = true
  owners      = ["137112412989"]

  filter {
    name   = "name"
    values = ["al2023-ami-2023.*-x86_64"]
  }
}

data "aws_availability_zones" "available" {
  state = "available"
}

resource "aws_vpc" "demo" {
  cidr_block = "10.0.0.0/16"
}

resource "aws_subnet" "demo" {
  vpc_id            = aws_vpc.demo.id
  cidr_block        = "10.0.1.0/24"
  availability_zone = data.aws_availability_zones.available.names[0]
}

resource "aws_instance" "web" {
  ami           = data.aws_ami.amazon_linux.id
  instance_type = var.instance_type
  subnet_id     = aws_subnet.demo.id

  tags = {
    Name = "web"
  }

  lifecycle {
    # Create the replacement before destroying the original.
    create_before_destroy = true
  }
}

resource "aws_s3_bucket" "protected_archive" {
  bucket_prefix = "example-audit-archive-"

  lifecycle {
    # Reject plans that would destroy this bucket.
    prevent_destroy = true
  }
}

output "web_instance_id" {
  value = aws_instance.web.id
}

Run it with:

terraform init
terraform plan -out=tfplan
terraform apply tfplan

Changing instance_type demonstrates replacement ordering. A terraform destroy plan fails because the protected S3 bucket would be destroyed.

State, Drift, and Production Behavior

  • Remote state: Use an encrypted, versioned remote backend with locking. Local state does not provide safe concurrent access.

  • Secrets: State can contain sensitive values even when outputs are marked sensitive. Store credentials in AWS Secrets Manager or SSM Parameter Store where possible.

  • Drift: prevent_destroy does not detect or stop out-of-band changes. Review terraform plan -refresh-only output during operational reviews.

  • Unique resources: create_before_destroy fails when both versions cannot coexist, such as two S3 buckets with the same globally unique name.

  • Dependencies: Replacement ordering can expose dependency issues and requires careful review of security groups, DNS records, load balancers, and application connections.

  • Ownership: Import existing infrastructure before relying on lifecycle protection. Terraform 1.x supports both terraform import and, from Terraform 1.5, import blocks.

Best Practices and CI/CD

  • Apply lifecycle rules selectively; excessive protection makes routine updates fail, while excessive ignore_changes hides drift.

  • Pin module and provider versions and commit .terraform.lock.hcl.

  • Treat workspaces as state namespaces, not security boundaries; use separate backends or accounts for stronger environment isolation.

  • Run terraform validate, review the complete plan, and apply a saved plan rather than generating a second plan during deployment.

  • Use Terraform 1.6 or newer for native terraform test files; Terraform 1.7 or newer also supports mocked-provider testing.

  • OpenTofu is a relevant alternative with Terraform-compatible lifecycle concepts, but compatible provider and module versions should be verified separately.

A typical pipeline is:

terraform fmt -check -recursive
terraform init -input=false
terraform validate
terraform plan -lock-timeout=5m -out=tfplan
terraform apply -lock-timeout=5m tfplan

Protect the saved plan as sensitive, require human approval for destructive changes, and monitor failed applies for deposed resources, quota exhaustion, and resources left running after partial failures.

29

How does Terraform lifecycle ignore_changes work?

ignore_changes is a resource-level Terraform lifecycle argument that suppresses planned actions for selected attributes or attribute paths. It is useful when another system owns those values, but it creates an explicit exception to Terraform’s desired-state reconciliation.

Read full answer

Applies toTerraform 1.x and OpenTofu 1.x, with AWS provider 5.x in the example

How It Works

During a normal plan, Terraform first refreshes its prior state from the remote object. The planner then compares the configuration with that refreshed state to propose actions. Paths listed in ignore_changes are excluded from the planned difference, so Terraform neither shows nor applies a change to those paths.

This suppression covers both changes made outside Terraform and changes made to the corresponding value in the HCL configuration.

The setting supports:

  • Top-level arguments, such as tags.

  • Map elements or nested attribute paths, where supported, such as tags["environment"].

  • All attributes, using the special value ignore_changes = all. This is exceptionally broad and should be avoided for normal production resources.

It applies to resources declared directly or inside modules, but each resource must declare its own lifecycle block. It does not disable management of non-ignored arguments.

Important Limitations

  • Creation and destruction still work: ignore_changes does not prevent either operation.

  • Replacement is not generally prevented: another argument that requires replacement can still replace the resource.

  • Provider updates can still affect ignored fields: ignoring an argument does not guarantee that an update caused by another argument will never include it in the provider request.

  • It is not module-wide: configure it on every resource that needs the exception.

  • It does not apply to data sources: data sources do not support the resource lifecycle’s ignore_changes argument.

Production Behavior

Ignoring an argument means Terraform is no longer enforcing its configured value. This can be appropriate for values managed by a separate compliance, policy, or provisioning system.

It is risky for security controls, encryption settings, public-access settings, network policies, resource sizing, failover configuration, and cost-allocation tags that Terraform is expected to own.

During refresh, Terraform reads the remote value into state, but the corresponding planned action is suppressed. The remote value can therefore diverge permanently from the HCL configuration without appearing as a normal plan difference.

State, Security, and CI/CD

ignore_changes does not remove sensitive data from state. Terraform state can contain ignored arguments, provider-generated values, and sensitive outputs. Use an encrypted, versioned remote backend with tightly restricted access, and never hard-code credentials in configuration.

For current Terraform versions, use the S3 backend’s native locking with use_lockfile = true, available in Terraform 1.10+. DynamoDB locking is deprecated from Terraform 1.11 and should not be selected for new current-version deployments.

Marking an output as sensitive redacts it from normal CLI output; it does not encrypt the underlying state. A production workflow should still validate configuration, review complete plans, apply approved saved plans under backend locking, and monitor resources for unauthorized drift.

A typical sequence is:

terraform init
terraform plan -out=tfplan
terraform show tfplan
terraform apply tfplan

Use Terraform Cloud or another remote execution system when shared environments require approval gates, audit history, and controlled applies.

Code Example

The following resource leaves the entire tags map under the ownership of an external tagging system:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "us-east-1"
}

resource "aws_s3_bucket" "assets" {
  bucket = "example-assets-unique-name"

  tags = {
    environment = "dev"
  }

  lifecycle {
    # Ignore all additions, removals, and updates to tags.
    ignore_changes = [tags]
  }
}

To ignore only one map entry, use a path such as ignore_changes = [tags["environment"]]. The attribute path must be valid for the resource schema; Terraform reports an error for an unsupported path.

Best Practices and Pitfalls

  • Prefer the precise attribute or map-key path over ignoring an entire argument.

  • Document the exception, its reason, and the system that owns the value.

  • Do not use ignore_changes merely to conceal inconvenient drift or failed reconciliation.

  • Review plans carefully because ignored differences will not appear as normal actions.

  • Test lifecycle behavior with terraform test against the actual provider version.

  • When importing an existing resource, refresh and plan first; imported resources can immediately expose differences that the lifecycle rule is intended to suppress.

  • Treat ignore_changes as an ownership exception, not a replacement for declarative management.

30

What does a Terraform module represent?

A Terraform module is a reusable package of Terraform configuration that groups related infrastructure components. It accepts inputs through variables, returns values through outputs, and declares its provider requirements, allowing teams to share standardized patterns without duplicating configuration.

Read full answer

Applies toTerraform 1.x and OpenTofu 1.x

Module Model

Module type Meaning
Root module The configuration directory in which Terraform is invoked. It usually contains provider configuration and calls child modules.
Child module A module invoked by another module through a module block.
Local module A child module referenced with a relative source path such as ./modules/network.
Remote module A module obtained from a registry, version-control system, HTTP endpoint, or supported object-storage location. Registry modules are commonly pinned with an exact version.

A module is a configuration and reuse boundary, not a deployment or state-isolation boundary. Its resources remain in the root module’s state under addresses such as module.network.aws_vpc.this, and child-module outputs are accessed as module.network.vpc_id.

Composition and Contract

  • A module can contain managed resources, data sources, locals, and nested module calls.

  • Variables define its input contract, while outputs expose selected values for the calling module.

  • required_providers declares the providers a module expects and the compatible version constraints.

  • Child modules inherit default provider configurations from their parent by default. They can also receive explicitly mapped or aliased provider configurations where necessary.

  • Provider constraints across the root and child modules must admit one compatible provider version. terraform init resolves that version, and the dependency lock file records the selected providers and modules.

  • Internal modules can be published to a private registry. Registry versions should be immutable, while other remote sources should be pinned to reviewed tags or commits.

  • Module source and provider requirements should be reviewed before adoption because plan and apply can perform provider operations and data-source reads, and apply can run provisioners configured by the module.

State and Production Safety

Modules do not automatically create separate state files. Use a remote backend with locking rather than committing state to source control. For AWS S3, Terraform 1.10+ supports native state locking; earlier Terraform 1.x releases use DynamoDB locking. Terraform Cloud also provides managed state and locking.

State can contain credentials, tokens, and other sensitive values. Marking an output sensitive controls its display but does not encrypt the underlying state, so remote state must remain encrypted, access-controlled, versioned where supported, and backed up.

By default, planning refreshes state to identify drift between Terraform and real infrastructure; refresh can be disabled with terraform plan -refresh=false. Plans should be reviewed for replacements, destructive changes, and security impact. Workspaces maintain separate state for the same configuration, but they do not provide account-level or project-level isolation.

Existing resources can be imported into the appropriate module address with terraform import, provided the module and provider are initialized. After import, run a plan and verify that Terraform proposes no unexpected changes.

Testing and CI/CD

Terraform 1.6 introduced native tests using .tftest.hcl files and terraform test; mocked providers are available from Terraform 1.7. Tests should verify inputs, expected plans, outputs, and policy requirements before a module version is published.

A typical CI sequence is terraform init -backend-config=path/to/backend.hcl, terraform fmt -check -recursive, terraform validate, terraform plan -out=tfplan, and terraform apply tfplan. Use a short-lived CI identity with least-privilege access, protect the saved plan because it may contain sensitive values, and require review and approval before applying to production.

Operational Guidance

Use lifecycle rules such as prevent_destroy, create_before_destroy, and ignore_changes only in the module that owns the resource. These rules can prevent necessary remediation or create replacement-ordering problems, so they require explicit testing and operational ownership.

OpenTofu 1.x supports a similar module model and provides equivalent tofu commands, but provider availability, registry contents, and remote-source compatibility should be verified rather than assumed.

31

How do you structure a reusable Terraform module?

A reusable Terraform module packages related resources behind a stable contract of variables and outputs. Treat it as a versioned product: keep environment-specific providers, backend configuration, state, and credentials in the root module.

Read full answer

Applies toTerraform 1.6-1.x with AWS provider 5.x

Module Structure

Organize a module by responsibility:

modules/s3-bucket/
├── main.tf
├── variables.tf
├── outputs.tf
├── versions.tf
├── README.md
└── tests/
    └── default.tftest.hcl
  • Resources and data sources: Manage owned infrastructure and read external dependencies.

  • Variables and outputs: Define the input contract and expose only useful values.

  • Provider requirements: Declare required_providers in the module, but configure providers in the root module.

  • Documentation and tests: Document inputs, outputs, examples, limitations, and expected behavior.

A module call expands into the root module’s dependency graph. It has no independent state, backend, or apply operation. Workspaces are root-state namespaces, not security boundaries; avoid making reusable modules depend on terraform.workspace.

Inputs, Outputs, and Composition

Use explicit variable types and validation for invalid inputs. Outputs should form a stable API and must not expose credentials. Mark sensitive outputs with sensitive = true, but remember that sensitive values still exist in state.

Source Use
Local path Developing modules in one repository
Git Private or unreleased modules; pin a tag or commit
Terraform Registry Shared modules; pin an immutable semantic version

Document breaking input or output changes. Prefer passing environment-specific identifiers into a module rather than hiding lookups inside it.

State Safety and Drift

Configure a remote backend only in the root module. Select a backend supporting encryption, versioning, access control, and locking; the S3 backend supports locking.

  • Treat state as sensitive because it can contain secrets even when outputs are marked sensitive.

  • Never commit state or credentials.

  • Review plans for destructive changes and apply only reviewed plans.

  • Run periodic plans to detect drift.

  • Use locking to prevent concurrent operations.

  • Import existing resources with import blocks or terraform import, then verify the plan is non-destructive.

Lifecycle and Operations

  • prevent_destroy: Protects critical resources from accidental deletion.

  • create_before_destroy: Controls replacement ordering when dependencies permit it.

  • ignore_changes: Suppresses fields legitimately controlled by another system.

Avoid local-exec and remote command provisioners where declarative resources exist. Provisioners can leave partial work after failure and need idempotency, timeouts, logging, and cleanup procedures. Return the identifiers needed to integrate monitoring, backup, encryption, and access logging.

Code Example

This module uses typed inputs, provider constraints, encryption, ownership controls, public-access blocking, and stable outputs:

# modules/s3-bucket/main.tf
terraform {
  required_version = ">= 1.6, < 2.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

variable "bucket_name" {
  type = string

  validation {
    condition = (
      length(var.bucket_name) >= 3 &&
      length(var.bucket_name) <= 63 &&
      can(regex("^[a-z0-9][a-z0-9.-]*[a-z0-9]$", var.bucket_name)) &&
      !strcontains(var.bucket_name, "..") &&
      !can(regex("[.-]-[.-]", var.bucket_name)) &&
      !can(regex("^([0-9]+\\.){3}[0-9]+$", var.bucket_name))
    )
    error_message = "bucket_name must satisfy the basic S3 length, character, separator, and IP-address rules."
  }
}

variable "tags" {
  type    = map(string)
  default = {}
}

resource "aws_s3_bucket" "this" {
  bucket = var.bucket_name
  tags   = var.tags
}

resource "aws_s3_bucket_ownership_controls" "this" {
  bucket = aws_s3_bucket.this.id

  rule {
    object_ownership = "BucketOwnerEnforced"
  }
}

resource "aws_s3_bucket_server_side_encryption_configuration" "this" {
  bucket = aws_s3_bucket.this.id

  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm = "AES256"
    }
  }
}

resource "aws_s3_bucket_public_access_block" "this" {
  bucket = aws_s3_bucket.this.id

  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

output "bucket_arn" {
  value = aws_s3_bucket.this.arn
}

AWS remains authoritative for reserved prefixes and suffixes. Bucket names are globally unique, so production callers must supply an available name.

# main.tf
terraform {
  required_version = ">= 1.6, < 2.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "us-east-1"
}

module "artifacts" {
  source = "./modules/s3-bucket"

  bucket_name = "example-app-artifacts-123456789012"
  tags = {
    Environment = "production"
  }
}

output "artifacts_bucket_arn" {
  value = module.artifacts.bucket_arn
}

Testing and CI/CD

Use terraform fmt -check -recursive, terraform init -backend=false, terraform validate, and terraform test for module checks. Terraform 1.6 tests can provision real resources, so isolate them in a dedicated test account; Terraform 1.7+ can use mocked providers.

A deployment pipeline should:

  1. Authenticate with short-lived CI credentials.

  2. Initialize the correct root configuration and backend.

  3. Run formatting, validation, tests, and security scanning.

  4. Save a plan with terraform plan -out=tfplan.

  5. Require review of that exact plan.

  6. Apply it with terraform apply tfplan.

Saved plans can contain sensitive values, so encrypt them, restrict access, and retain audit logs. OpenTofu is largely compatible with this HCL; validate migrated modules with tofu init, tofu validate, and tofu test.

32

How do you version and publish Terraform modules?

A reusable Terraform module should use semantic versioning and be published from an immutable Git tag. For registry distribution, publish the tagged revision to the Terraform Registry or a private registry; for internal distribution, consumers can reference the Git repository directly with an exact ref.

Read full answer

Applies toTerraform 1.x, public Terraform Registry, HCP Terraform private registry

Versioning Contract

Treat a module version as a public API:

  • Major version: Increment for breaking changes, such as removing or renaming variables, changing output types, or changing resource addresses.

  • Minor version: Increment for backward-compatible functionality, such as adding optional variables or outputs.

  • Patch version: Increment for backward-compatible fixes that do not alter the module contract.

  • Tag releases consistently as v1.2.3. Never move or overwrite an existing tag because consumers may already have downloaded it.

  • Document resource-address changes and provide moved blocks or explicit terraform state mv instructions when an upgrade requires state migration.

Module versions are independent of provider versions. A module can release v2.0.0 while still supporting AWS provider 5.x.

Repository and Publishing Process

Use a conventional layout such as terraform-aws-vpc, with the reusable module under modules/vpc or at the repository root:

terraform-aws-vpc/
├── modules/
│   └── vpc/
│       ├── main.tf
│       ├── variables.tf
│       ├── outputs.tf
│       └── versions.tf
├── README.md
└── examples/

The publishing process is:

  1. Validate the module with formatting, initialization, validation, and tests.

  2. Configure the repository through the registry’s publishing workflow. Public modules use the Terraform Registry’s supported repository integration; private modules can use HCP Terraform’s private registry.

  3. Merge the release changes through pull-request review.

  4. Create an annotated tag such as v1.2.3 and push the tag.

  5. Confirm that the registry publishes and exposes the new version.

The public Registry does not use a general terraform publish command; publication is based on the repository’s registered release tag. For an internal Git-only workflow, no registry is required: pin the Git ref directly.

Consuming Published Versions

Consumer configuration Accepted versions Typical use
version = "1.2.0" Exactly 1.2.0 Production reproducibility
version = "~> 1.2.0" >=1.2.0,<1.3.0 Conservative patch updates
version = "~> 1.2" >=1.2.0,<2.0.0 Accept compatible minor releases
version = ">=1.2.0" Includes later major versions Avoid unless explicitly required

For Git-hosted modules, use an immutable tag:

module "vpc" {
  source = "git::https://github.com/example-org/terraform-aws-vpc.git?ref=v1.2.3"
  cidr   = "10.0.0.0/16"
}

A ref pointing to main is mutable and unsuitable for production. Run terraform init -upgrade to update module references and terraform get -update when updating modules without changing providers.

Code Example

A minimal AWS module should declare compatible provider requirements without configuring the provider itself:

# modules/vpc/versions.tf
terraform {
  required_version = ">= 1.6.0, < 2.0.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

# modules/vpc/main.tf
resource "aws_vpc" "this" {
  cidr_block           = var.cidr
  enable_dns_support   = true
  enable_dns_hostnames = true

  tags = merge(var.tags, {
    Name = var.name
  })
}

# modules/vpc/variables.tf
variable "name" {
  type = string
}

variable "cidr" {
  type = string
}

variable "tags" {
  type    = map(string)
  default = {}
}

# modules/vpc/outputs.tf
output "vpc_id" {
  value = aws_vpc.this.id
}

Consumers select the published version:

terraform {
  required_version = ">= 1.6.0, < 2.0.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "us-east-1"
}

module "vpc" {
  source  = "example-org/vpc/aws"
  version = "1.2.0"

  name = "production-vpc"
  cidr = "10.0.0.0/16"
  tags = {
    Environment = "production"
  }
}

Do not commit credentials in either module. Use environment variables, workload identity, or another secret-delivery mechanism.

Validation and CI/CD

Run these checks from the module directory before tagging:

terraform fmt -check -recursive
terraform init -backend=false
terraform validate
terraform test

Use terraform test with .tftest.hcl files to exercise defaults, validation failures, and important plan assertions. In CI, require pull-request approval, a protected release tag, registry publication, and a smoke-test plan against representative inputs.

Production Safety

  • State: Modules can create stateful resources, so use an encrypted remote backend with locking, state versioning, and tested restoration. Terraform 1.10+ supports native S3 locking with use_lockfile = true; older 1.x releases require DynamoDB locking.

  • Secrets: Sensitive inputs and outputs remain stored in state. sensitive = true only redacts CLI output; it does not encrypt state.

  • Drift: Schedule plans against the remote backend to detect configuration drift and module upgrades.

  • Backups and recovery: For databases and persistent resources, combine Terraform state backups with provider-native snapshots, replication, and restore drills.

  • OpenTofu: Ordinary Terraform modules are generally source-compatible with OpenTofu, but registry publication is registry-specific; publish to the OpenTofu Registry when that is the intended distribution channel.

33

What role does the Terraform Registry play in Terraform?

The Terraform Registry is a catalog for discovering and downloading Terraform providers and reusable modules. It acts as a package-discovery service and source of version metadata; Terraform still runs locally to plan and apply infrastructure changes.

Read full answer

Applies toTerraform 1.x and OpenTofu 1.x

What It Contains

The public registry at registry.terraform.io contains two main package types:

Package type Example source address Purpose
Provider hashicorp/aws Supplies the implementation for managing AWS resources, data sources, and provider configuration
Module terraform-aws-modules/vpc/aws Reusable Terraform configuration containing resources, variables, outputs, and sometimes provider requirements

Organizations can also publish private modules through Terraform Cloud or Terraform Enterprise. The Terraform Registry Protocol supports building private registries or mirrors compatible with Terraform’s module and provider discovery mechanisms.

The registry also displays available versions, documentation, dependency requirements, and publisher information. These details help users select compatible releases, but registry inclusion should not be treated as a complete security endorsement.

How Terraform Uses It

When configuration declares a provider or module, Terraform resolves it during terraform init:

  1. Terraform parses the source address, such as hashicorp/aws or terraform-aws-modules/vpc/aws.

  2. It queries the registry for matching versions and metadata.

  3. It downloads the selected provider package or module source.

  4. It creates dependency locks and then builds the Terraform configuration graph.

Providers execute on the local workstation or CI runner and call the relevant cloud APIs. Modules are configuration packages assembled into the root configuration; they can include resources across multiple providers, such as a networking module that creates AWS VPC components.

A provider version constraint alone does not select one exact provider release. The selected provider version is recorded in .terraform.lock.hcl, including platform-specific package hashes. Module versions should also be pinned explicitly, for example with an exact version = "5.8.1" constraint.

Registry Versus State

The registry is not a Terraform state backend. It does not store resource state, credentials, drift history, or execution locks.

For production:

  • Store state in a remote backend with encryption, access controls, versioning, and locking.

  • Treat state as sensitive because it may contain plaintext secrets even when sensitive values are marked.

  • Use a separate secret manager for credentials rather than placing long-lived credentials in state or Terraform variables.

  • Review plans to detect configuration changes and runtime drift.

  • Protect terraform apply with approvals, restricted CI credentials, and audit logging.

If an organization needs controlled package distribution, it can mirror approved providers and modules internally and configure Terraform to use that registry.

Security and Supply-Chain Considerations

Community providers and modules are not automatically trusted merely because they appear in the registry. Providers often operate with broad cloud permissions, and modules can contain provisioners or provider configurations that introduce unintended behavior.

Practical controls include:

  • Prefer established publishers and review source repositories before adoption.

  • Pin module versions and commit .terraform.lock.hcl.

  • Review changes when upgrading providers or modules.

  • Scan configurations and dependencies in CI.

  • Restrict provider credentials to the minimum required permissions.

  • Maintain an internal registry for approved organizational packages.

  • Avoid executing unreviewed modules in pipelines that possess production credentials.

Terraform Cloud and Terraform Enterprise can add approval policies, private registry features, and audit capabilities, but they do not eliminate the need to inspect dependency code.

OpenTofu Compatibility

OpenTofu supports Terraform-compatible public registry discovery and can install many providers and modules from the Terraform ecosystem. Because Terraform and OpenTofu have evolved independently, teams should verify provider and module compatibility with the OpenTofu release they use rather than assuming every Terraform release behaves identically.

34

How do Terraform workspaces isolate state, and when are they appropriate?

Terraform workspaces provide named, isolated state for the same configuration, making them useful for lightweight separation of environments such as development, staging, and production. They do not, however, provide the permissions, approval, or infrastructure isolation of separate Terraform roots or Terraform Cloud projects.

Read full answer

Applies toTerraform 1.10+ and OpenTofu 1.x for workspace behavior; backend-specific locking capabilities depend on the backend and release

How Workspaces Work

A workspace changes which state Terraform reads and writes. It does not change the configuration or provider resources by itself.

  • Each workspace has separate state containing its own resource instances and dependency records.

  • Resource addresses remain the same across workspaces. An aws_instance.web in staging represents a different resource from an aws_instance.web in production, assuming both exist in their respective states.

  • Selecting a workspace does not create resources. Applying in a workspace whose state lacks those resource addresses can create them.

  • With the local backend, the selected workspace name is recorded in .terraform/environment. Other backends track workspace selection through their own backend mechanisms.

  • Workspaces are supported by the local backend and by remote backends that implement workspace operations, including the S3 backend and Terraform Cloud.

  • Common CLI operations are terraform workspace list, terraform workspace new staging, terraform workspace select staging, and terraform workspace delete staging. Deletion refuses to remove a workspace containing resources unless they are destroyed first.

  • The TF_WORKSPACE environment variable can select a workspace explicitly, which is useful in CI jobs.

Backend configuration is shared by all workspaces within a Terraform root. A workspace therefore cannot select a different backend configuration from the other workspaces in that root.

Production Use Cases

Workspaces are appropriate when:

  • Several environments use substantially the same configuration and module structure.

  • Each environment needs independent state but does not need a completely separate root module.

  • The team wants a simple operational model with environment-specific state.

They are less suitable when:

  • Environments need different backend configurations, incompatible provider versions, substantially different modules, or state migrations.

  • Teams require independent IAM permissions, approval policies, variable sets, or execution isolation.

  • A destructive change in one environment could affect shared databases, IAM policies, DNS records, or other resources.

  • Development and production require strong separation between pipelines and credentials.

For those cases, use separate Terraform roots and backends, or separate Terraform Cloud projects with appropriately scoped workspaces.

Workspaces Compared with Other Approaches

Approach State isolation Configuration isolation Typical use
Terraform workspaces Separate state Shared configuration Lightweight environment separation
Separate directories Separate state when separately initialized Separate configuration Environment-specific provider or module setup
Separate backends Separate state and backend Usually separate configuration Stronger operational or organizational separation
Terraform Cloud workspaces Separate state and managed execution Can share VCS configuration and modules Controlled team and production workflows

Directories and workspaces can be combined: each directory can initialize a backend and use multiple workspaces. In Terraform Cloud, a workspace also represents a managed execution environment within a project.

State, Security, and Drift Risks

A workspace does not automatically make infrastructure safe.

  • State isolation: Workspaces isolate Terraform state, not physical resource names or external systems.

  • Locking: Use a backend with locking enabled. For the current Terraform S3 backend, prefer native S3 locking with use_lockfile = true; DynamoDB-based locking is deprecated and should be used only for compatibility during migration. Terraform Cloud provides managed locking.

  • Secrets: Sensitive values can still be stored in state. Store credentials in an appropriate secrets manager and inject them during Terraform execution where feasible.

  • Drift: State becomes stale when infrastructure changes outside Terraform. Run regular plans and investigate unexpected deletions, replacements, or data-source changes.

  • Plan review: Review production plans before applying, ideally in protected CI/CD workflows with approval gates and immutable or reviewed plan artifacts.

  • Shared resources: Separate states do not prevent multiple workspaces from accessing or modifying shared external resources.

Best Practices

  1. Use clear, consistently named workspaces such as development, staging, and production.

  2. Store remote state in an encrypted, versioned backend with locking enabled.

  3. Restrict production-state access according to least privilege.

  4. Set TF_WORKSPACE explicitly in CI rather than relying on a developer’s local selection.

  5. Run and review terraform plan before every apply, paying particular attention to destructive changes.

  6. Use separate roots, backends, or Terraform Cloud projects when environments require different permissions, approvals, provider configurations, or execution isolation.

  7. Back up state, monitor failed plans and applies, and test state migrations and provider upgrades before production use.

  8. Destroy resources explicitly before deleting a workspace; deleting workspace state does not destroy the infrastructure it described.

OpenTofu supports Terraform-compatible workspace behavior, but backend locking, state migration, and enterprise policy features must be verified against the selected OpenTofu release and backend.

35

How should Terraform manage dev, staging, and prod environments?

Use separate root configurations and isolated remote state for each environment while sharing reusable infrastructure through Terraform modules. Treat development, staging, and production as independently reviewed and promoted deployments rather than as one configuration controlled by a mutable environment switch.

Read full answer

Applies toTerraform 1.10 or later in the 1.x line with AWS provider 5.x

Environment Strategy

  • Root modules: Keep separate dev, staging, and prod directories so each environment has its own variables, provider configuration, plan, approvals, and pipeline controls.

  • Shared modules: Put reusable networking, compute, and observability resources in version-controlled modules. Remote module sources must use an immutable release tag or commit; local modules are effectively pinned by the reviewed repository commit used in CI.

  • Variables and validation: Supply environment-specific CIDRs, sizes, tags, and limits through typed variables with validation. Never embed production credentials in configuration.

  • Resources and data sources: Resources manage infrastructure; data sources only read existing objects for references and cannot manage their lifecycle.

  • Outputs: Export only the IDs, endpoints, and names other environments need. Mark sensitive outputs and avoid outputting secret values.

  • Providers: Configure providers in root modules rather than reusable child modules. Declare provider source and version constraints in both roots and reusable modules.

  • State: Store each environment in a separate remote-state key. Separate directories generally provide clearer permissions, review boundaries, and CI controls than a single directory selected by an environment variable.

Code Example

The reusable module declares its provider dependency and creates a VPC:

# modules/network/main.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

variable "name" {
  type = string
}

variable "cidr_block" {
  type = string
}

resource "aws_vpc" "this" {
  cidr_block = var.cidr_block

  tags = {
    Name        = var.name
    Environment = var.name
  }
}

output "vpc_id" {
  value = aws_vpc.this.id
}

Each environment has its own root module and backend key:

# environments/dev/main.tf
terraform {
  required_version = ">= 1.10.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }

  backend "s3" {
    bucket       = "company-terraform-state"
    key          = "network/dev/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    use_lockfile = true
  }
}

provider "aws" {
  region = "us-east-1"
}

variable "environment" {
  type    = string
  default = "dev"
}

variable "cidr_block" {
  type    = string
  default = "10.10.0.0/16"
}

module "network" {
  source = "../../modules/network"

  name       = var.environment
  cidr_block = var.cidr_block
}

output "vpc_id" {
  value = module.network.vpc_id
}

Create equivalent staging and production roots with different keys, CIDRs, and settings. Bootstrap the S3 bucket separately because it must exist before terraform init.

terraform fmt -recursive
cd environments/dev
terraform init
terraform validate
terraform plan -out=tfplan
terraform apply tfplan

Workspaces

Terraform workspaces maintain named states under one backend configuration. They are useful for temporary experiments or tightly controlled workflows, but a wrong workspace selection can modify production. Separate directories and state keys are usually safer for production because they provide clearer isolation, permissions, audit trails, and approval boundaries.

CI/CD Workflow

  1. Run terraform fmt -check -recursive.

  2. Authenticate to AWS with OIDC rather than long-lived credentials.

  3. Run terraform init for the selected environment and backend configuration.

  4. Run terraform validate and terraform test; execute tests only against disposable dev or staging resources.

  5. Run terraform plan -out=tfplan with pipeline-supplied variables.

  6. Inspect the plan for replacements, destruction, sensitive output changes, and unexpected resource movement.

  7. Apply the reviewed saved plan with environment-specific approval, preferably through a separate protected CI job.

A saved plan applies the reviewed actions but can contain sensitive values. Transfer it through protected CI artifacts and delete it promptly. Do not regenerate it after approval unless the plan is reviewed again.

State Safety and Production Operations

  • Locking and access: Use S3 with use_lockfile = true, bucket versioning, encryption, restricted IAM access, and audit logging. The S3 bucket must exist before initialization.

  • Secrets: Terraform variables and state can contain secrets even when variables are marked sensitive. Store secrets in Secrets Manager or another secret manager and inject them at runtime.

  • Drift: A plan refreshes state and detects out-of-band changes. Investigate unexpected drift before applying; do not automatically accept destructive changes.

  • Import: Adopt existing infrastructure with terraform import module.network.aws_vpc.this vpc-0123456789abcdef0, then plan to verify that no unintended changes will occur.

  • Lifecycle: Use prevent_destroy for critical production resources and create_before_destroy where overlap is required. Use ignore_changes only for fields deliberately managed outside Terraform.

  • Partial failure: Completed apply actions are recorded in state. Fix the API, permission, quota, or dependency failure and run another plan rather than editing state manually.

  • Monitoring: Monitor provider and cloud telemetry, synthetic application checks, and alarms after each deployment. Schedule read-only plans to detect drift.

  • Upgrades: Pin Terraform, provider, and module versions; review changelogs and test upgrades through dev and staging before production. Do not automatically upgrade production dependencies.

  • Recovery and incidents: Test state restoration from versioned backups. During an incident, preserve plans, logs, and state history, determine whether the fault is an apply failure or an application failure, and use import or controlled state recovery rather than ad hoc edits.

36

How do Terraform workspaces, separate directories, and Terragrunt compare?

Terraform workspaces create separate state instances from one configuration, separate directories isolate both configuration and state, and Terragrunt adds orchestration and configuration reuse while still running Terraform or OpenTofu. For production isolation, separate directories are usually the safest default; Terragrunt is strongest when managing many environments with shared modules.

Read full answer

Applies toTerraform 1.10+ within 1.x, AWS provider 5.x, Terragrunt 0.x, and OpenTofu 1.x

Comparison

Approach Configuration isolation State model Main benefit Main risk
Workspaces Shared configuration Separate state per workspace Fast environment switching with little extra configuration Easy to select or apply against the wrong workspace
Separate directories Separate root modules and inputs Normally one explicitly configured state per directory Strong boundaries and straightforward CI/CD promotion Duplication and configuration drift between directories
Terragrunt Reuses root modules through source Determined by each Terragrunt unit’s backend configuration DRY configuration, dependencies, and multi-environment orchestration Adds a tooling layer; incorrect backend settings can still corrupt state

How They Work

Workspaces are named instances managed by Terraform’s selected backend. A command such as terraform workspace select prod changes which state Terraform reads and writes. Resource definitions usually remain identical; environment-specific values come from variables or variable files.

Workspaces are convenient for temporary states, experiments, and tightly related variants of one configuration. They are not strong security boundaries: switching workspaces is easy, configuration remains shared, and backend access may still use the same IAM role or credentials. Some backends also represent workspaces differently, so verify the selected backend’s behavior.

Separate directories give each environment its own root module and normally its own backend key. A typical layout might contain environments/dev, environments/staging, and environments/prod, each calling reusable modules through source.

This makes accidental cross-environment access less likely and allows environment-specific provider configurations, lifecycle rules, and policies. It also enables separate CI/CD approvals and permissions. The trade-off is duplicated root configuration and the risk that backend keys are accidentally reused.

Terragrunt is a wrapper around Terraform or OpenTofu. It generates backend and provider configuration, references shared Terraform modules, passes inputs, and coordinates dependencies through run-all. It does not replace Terraform state or locking; every Terragrunt unit must still use an isolated state location and a locking-enabled backend.

State Safety and Drift

  • Remote state: Store state in an encrypted, versioned, access-controlled backend. Never commit .tfstate or .tfstate.backup files.

  • Locking: Use the backend’s native locking mechanism. With current Terraform S3 backends, use_lockfile = true provides S3-based locking. OpenTofu deployments should use the locking mechanism supported by their exact OpenTofu and backend versions.

  • Secrets: Terraform state commonly contains sensitive values, even if marked sensitive. Restrict read access, encrypt state, and use short-lived CI credentials through OIDC rather than static access keys.

  • Unique keys: Give every directory or Terragrunt environment a distinct state key. Reusing one key causes two configurations to compete for the same state.

  • Drift review: A refreshed plan exposes changes made outside Terraform. Review drift carefully, then import existing resources where appropriate; do not automatically apply every detected difference.

  • Recovery: Enable state versioning and maintain documented restoration procedures. Versioned state helps recover from accidental changes but is not a replacement for backups of the infrastructure itself.

Production Guidance

Use workspaces for small, short-lived variations where separate directories would be excessive. Use separate directories as the default for production accounts, regions, or security boundaries. Use Terragrunt when the number of environments makes duplicated directory configuration costly or when cross-unit dependencies and reusable module versioning are important.

In CI/CD, pin Terraform or OpenTofu, provider, and Terragrunt versions; use protected environments for approvals; generate and review a saved plan; and apply that exact plan. Terragrunt supports OpenTofu for many workflows, but compatibility should be tested against the selected Terragrunt, provider, and backend versions.

37

What is Terraform’s import workflow for existing infrastructure?

Terraform’s import workflow associates an existing infrastructure object with a Terraform resource address, records its provider-visible attributes in state, and then uses a reviewed plan to reconcile that state with the desired configuration. Import does not create the remote object, automatically discover dependencies, or verify that the infrastructure is safe for Terraform to manage.

Read full answer

Applies toTerraform 1.5 through current 1.x with AWS provider 5.x; Terraform 1.7+ for `removed` blocks; OpenTofu 1.6+ for configuration-driven import

Import Methods

Method Best use Behavior
import block Repeatable imports and CI/CD Stored in configuration and processed during planning and applying
terraform import One-off imports Imports one resource directly into state using a resource address and provider-specific ID
Generated configuration Resources not yet represented in HCL Produces candidate resource configuration during planning for review and refinement

The target must be a managed resource address, not a data-source address. For a resource inside a module, the address uses the module path, such as module.network.aws_vpc.main.

End-to-End Workflow

  1. Prepare configuration: Configure the correct provider, authentication, account, and region. For a one-off command-line import, declare the target resource in configuration before importing.

  2. Initialize the working directory: Run terraform init so the required provider plugins and modules are installed.

  3. Select the import mechanism: Add an import block for configuration-driven operation, or use terraform import for an individual resource.

  4. Generate configuration when necessary: If the corresponding resource configuration does not yet exist, run terraform plan -generate-config-out=generated.tf. Review the generated HCL carefully; it is candidate configuration and may require corrections before adoption.

  5. Import into state: The provider validates the resource-specific import ID, reads the object through the appropriate cloud API, and stores its manageable attributes in state. Terraform does not call the provider’s create API.

  6. Review reconciliation: Run a normal plan and inspect every proposed change. Configuration differences can cause destructive replacement, so resolve unexpected changes before applying.

  7. Apply safely: Save and review the plan with terraform plan -out=terraform.tfplan, then apply that exact plan with terraform apply terraform.tfplan.

For a one-off import, the corresponding command is terraform import aws_vpc.example vpc-0123456789abcdef0. The import ID format is provider- and resource-specific; it is not a universal object identifier.

State and Production Safety

  • Remote state: Store production state in an encrypted remote backend that supports locking. Use separate backends or state paths for separate accounts, regions, and environments; Terraform workspaces are logical namespaces, not strong security boundaries.

  • Secrets: State can contain sensitive values such as passwords, tokens, private keys, and user data. Do not commit state or saved plans, and restrict backend and plan-artifact access.

  • Drift: Import establishes the current remote configuration as Terraform’s initial baseline. Later plans can detect changes made outside Terraform, which should be reviewed rather than automatically reverted.

  • Backups: Enable backend versioning or equivalent state backups. A state backup does not back up the actual cloud infrastructure.

  • Lifecycle protection: Consider prevent_destroy for critical resources. Terraform 1.7+ also supports a removed block with destroy = false to remove a resource from state without deleting the remote object.

  • CI/CD: Validate and format the configuration, review a plan, and apply the same saved plan through the protected backend. Ensure backend locking prevents concurrent state-changing operations.

Provider and OpenTofu Notes

The provider controls import-ID validation and the read operation. AWS provider 5.x accepts resource-specific IDs such as vpc-0123456789abcdef0 for a VPC, i-0123456789abcdef0 for an EC2 instance, and sg-0123456789abcdef0 for a security group. Other resource types use different identifiers.

OpenTofu 1.6+ supports configuration-driven import blocks and generated configuration. Its equivalent workflow uses tofu init, tofu plan, and tofu apply; the one-off tofu import command is also available.

Common Pitfalls and Best Practices

  • Wrong account or region: Confirm the effective provider configuration before importing because IDs are commonly valid only within the expected account, region, or parent scope.

  • Insufficient permissions: Import generally requires read operations such as Describe, Get, or List; planning may require additional permissions.

  • Incorrect configuration: Generated or manually written configuration must match the remote object closely enough to avoid unintended replacement.

  • Missing dependencies: Networking, security groups, DNS records, and supporting resources are not discovered automatically and may need separate imports or explicit references.

  • Ownership assumptions: Import does not establish operational ownership. Inspect the imported state and first plan carefully.

  • Safe rehearsal: For high-risk resources, test the import and reconciliation in a disposable environment or against a safe clone before production.

38

How do Terraform import blocks differ from terraform import?

Import blocks are a declarative way to add existing infrastructure to Terraform state and review the operation through the normal plan-and-apply workflow. By contrast, terraform import is an imperative CLI command that updates state directly without producing an import plan.

Read full answer

Applies toTerraform 1.5+ for import blocks; Terraform 1.7+ for `for_each` in import blocks; `terraform import` in Terraform 1.x

How Import Blocks Work

An import block in Terraform configuration associates a resource address with the provider-specific ID of an object that already exists. Terraform 1.5 introduced the block, while Terraform 1.7 added support for for_each.

When Terraform plans an import block, it displays the resource as an import action. Applying that plan adds the remote object to state and may also apply configuration changes to the imported resource. Multiple import blocks can be processed in one operation.

Import blocks are normally temporary configuration. After a successful apply, remove the import block because the resource is now managed through its resource block. The imported object remains in Terraform state and under Terraform’s management.

How terraform import Works

The terraform import ADDRESS ID command imports one resource into state using its configuration address and provider-specific ID. The corresponding resource block must already exist, although it may initially contain only an empty block.

The command updates state immediately; it does not create an import plan for review and does not generate configuration for the remote object. After the import, run terraform plan separately to inspect any differences between the desired configuration and the imported remote object.

Although each invocation handles one resource, scripts can invoke the command repeatedly. It can therefore be automated in CI/CD, but it remains an imperative out-of-band operation rather than a declarative configuration change reviewed through a pull request.

Key Differences

Aspect Import block terraform import
Style Declarative Terraform configuration Imperative CLI operation
Plan review Import appears in terraform plan No import plan is produced
Multiple resources Multiple blocks are supported One resource per command invocation
Configuration generation Supported with terraform plan -generate-config-out=generated.tf Not supported
for_each Supported in Terraform 1.7+ Not applicable
State locking Uses the backend’s normal locking behavior Uses the backend’s normal locking behavior
CI/CD workflow Configuration can be reviewed and applied like other changes Automatable, but performed separately from configuration review

State, Drift, and Operational Considerations

Neither mechanism imports configuration into Terraform; both add the existing object to state. The configuration must still describe the remote object accurately, and subsequent plans expose drift between the desired configuration and reality.

Use a remote backend with locking enabled in production so concurrent plans and applies cannot corrupt or overwrite state. Protect the state file because it may contain sensitive values even when the original resource configuration does not expose them as outputs. Restrict backend access, enable encryption, and retain appropriate audit logs.

Review every generated plan carefully. For configuration-generated imports, inspect the generated HCL for completeness, hardcoded values, missing tags, and unsupported or omitted attributes. A post-import plan need not be empty when changes are intentional, but every proposed change should be understood and approved.

Common Pitfalls

  • Importing into the wrong workspace or backend, which can scatter resources across environments.

  • Forgetting to create or generate a resource block before applying an import block.

  • Assuming an import has configured the object; it has only brought the remote object under Terraform’s state management.

  • Retaining import blocks indefinitely, which can cause repeated import processing or ambiguity about whether the resource is already managed.

  • Treating generated configuration as automatically production-ready without reviewing and refactoring it.

  • Running terraform apply without first inspecting the import and any resulting changes in the plan.

39

How does Terraform's moved block simplify resource renaming?

The moved block tells Terraform that a resource or module has changed its address in the configuration, allowing the existing infrastructure to be tracked under the new name without destroying and recreating it. It is especially useful for refactoring Terraform code safely.

Read full answer

Applies toTerraform 1.1 and later Terraform 1.x releases with AWS provider 5.x; OpenTofu 1.x with AWS provider 5.x

How It Works

Terraform normally identifies managed infrastructure using addresses such as:

aws_instance.web
module.network.aws_subnet.private[0]

If a resource is renamed from aws_instance.web to aws_instance.api, Terraform would normally interpret that as one resource being destroyed and another being created. A moved block declares that these addresses represent the same real-world object:

moved {
  from = aws_instance.web
  to   = aws_instance.api
}

During planning, Terraform recognizes the relationship and reports the address move. Applying the plan updates the current state to use the destination address; it does not modify the remote object. If the resource configuration and remote object are otherwise unchanged, the plan contains only the address move and does not destroy or recreate the infrastructure.

A module can be moved as a whole:

moved {
  from = module.network
  to   = module.networking
}

This changes the address of the module call and the addresses of the resources inside it. The from and to values are static addresses; they cannot contain variables or arbitrary expressions. Moved blocks belong in the root module.

Why It Is Useful

  • Avoids unnecessary replacement: Renaming a resource does not require manually editing state or recreating servers, databases, buckets, or networking resources.

  • Supports safe refactoring: Teams can reorganize resources into modules, rename abstractions, and restructure code while preserving infrastructure identity.

  • Makes changes reviewable: The move appears in the Terraform plan, so reviewers can see the address transition before applying it.

  • Keeps configuration authoritative: Unlike changing state only with the CLI, the relationship is recorded in version-controlled HCL.

For example, a module could be reorganized from:

module.network

to:

module.networking

A corresponding moved block preserves the existing resources while the module structure changes.

Code Example

The following example renames an AWS EC2 instance:

moved {
  from = aws_instance.web
  to   = aws_instance.api
}

data "aws_ami" "ubuntu" {
  most_recent = true
  owners      = ["099720109477"]
}

resource "aws_instance" "api" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.micro"

  tags = {
    Name = "api"
  }
}

The original aws_instance.web resource is removed from the configuration, but the moved block tells Terraform to associate its existing state with aws_instance.api. The resource still needs to be configured for the target environment, including appropriate networking, storage, identity, and security settings.

A moved block can also be used while changing module names:

moved {
  from = module.network
  to   = module.networking
}

module "networking" {
  source = "./modules/networking"
}

The destination module must contain the corresponding resources, and the resource types and provider compatibility must remain valid.

Operational and Safety Considerations

  • Use remote state: A moved block changes addresses within the current Terraform state and workspace. It does not transfer state between backends, accounts, projects, or workspaces.

  • Enable backend locking: Use a backend such as S3 with DynamoDB locking, or another backend with equivalent locking, so concurrent applies cannot corrupt state.

  • Protect sensitive state: State may contain passwords, private keys, tokens, and other secrets. Encrypt it, restrict access, enable versioning, and avoid placing sensitive values in plaintext configuration.

  • Review plans carefully: A pure move should not show a destroy/create pair. Other configuration changes can still cause replacements, so distinguish the address move from unrelated infrastructure changes.

  • Check for drift: By default, Terraform refreshes state during a normal plan, although refresh can be disabled with -refresh=false. If the remote resource has changed outside Terraform, the plan may include corrective actions in addition to the move.

  • Prefer configuration over manual state commands: terraform state mv can move state entries, but moved blocks are preferable for normal refactoring because they document the transition in version control and are visible in plans.

  • Automate validation: In CI/CD, run terraform fmt, terraform validate, and a reviewed terraform plan before applying. Apply moves through the same protected pipeline used for other infrastructure changes.

40

How do you rename a Terraform resource address without destroying it?

Use a moved block to rename a resource’s Terraform address while preserving the existing cloud object and its state. Terraform records the address change during planning and applies it without creating or destroying the remote resource.

Read full answer

Applies toTerraform 1.1+ with AWS provider 5.x

How It Works

A Terraform resource has two potentially different identities:

  • Terraform address: The address used in configuration and state, such as aws_instance.web.

  • Cloud identity: The provider-managed object, such as an EC2 instance ID or an AWS VPC ID.

A moved block changes only the Terraform address. For example:

moved {
  from = aws_instance.web
  to   = aws_instance.web_server
}

If aws_instance.web already exists in state, Terraform associates that state with aws_instance.web_server. The plan reports a move, while the underlying EC2 instance remains unchanged.

A moved block does not rename provider-managed properties such as an EC2 instance ID, S3 bucket name, or database identifier. Changing those properties follows normal provider update or replacement behavior.

Code Example

The following configuration renames the Terraform address from aws_instance.web to aws_instance.web_server:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "us-east-1"
}

data "aws_ami" "ubuntu" {
  most_recent = true
  owners      = ["099720109477"]

  filter {
    name   = "name"
    values = ["ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"]
  }
}

resource "aws_instance" "web_server" {
  ami           = data.aws_ami.ubuntu.id
  instance_type = "t3.micro"

  tags = {
    Name = "web-server"
  }
}

moved {
  from = aws_instance.web
  to   = aws_instance.web_server
}

Apply the rename through a reviewed plan:

terraform init
terraform plan -out=rename.tfplan
terraform show rename.tfplan
terraform apply rename.tfplan

The plan should report that aws_instance.web moved to aws_instance.web_server, without showing the instance being destroyed and recreated.

Production Workflow

  1. Update the resource block to use the new address.

  2. Add the matching moved block in the same configuration version.

  3. Run terraform plan and verify that it shows a move rather than a replacement.

  4. Review the complete plan for unrelated infrastructure changes.

  5. Apply the saved plan with appropriate concurrency controls.

  6. Keep the moved block committed for historical clarity, or remove it after the successful apply. Removing it afterward is safe because state already contains the new address.

For example, changing the EC2 Name tag is normally an in-place update. Changing ami, availability_zone, or another replacement-triggering argument can still destroy and recreate the instance; moved does not prevent that.

State Safety and Operational Considerations

  • Remote state: Use an encrypted remote backend with locking enabled. A move modifies state, so concurrent applies could otherwise cause conflicting updates.

  • State backups: Back up state before emergency state operations and restrict access because state may contain sensitive values.

  • CI/CD: Run plans in pull requests, require review for move and replacement operations, and protect production applies with serialized execution or approval gates.

  • Drift: A moved block only changes the address. It does not repair drift between the remote object and its configuration; use a refresh or normal plan to detect those differences.

  • Import versus move: Use an import block when the object exists remotely but is absent from state. Use moved when the object is already managed under an old Terraform address.

Emergency Alternative

terraform state mv can change an address directly in state:

terraform state mv 'aws_instance.web' 'aws_instance.web_server'

This is mainly a recovery or migration tool. A committed moved block is preferable because it is reviewable, repeatable, and automatically included in future plans. Do not run terraform state mv concurrently with another operation against the same state.

Common Pitfalls

  • Incorrect source address: If from does not match the existing state address, Terraform may plan a new resource instead.

  • Duplicate destination: The destination address must not already refer to a different resource.

  • Assuming the physical name changed: The provider still determines whether a name or identifier change is an update or replacement.

  • Editing state manually: Manual state-file edits bypass locking and validation and can corrupt the state.

  • OpenTofu: OpenTofu also supports moved blocks, so the same version-controlled approach applies.

41

How do you move a resource in Terraform state?

To move a resource in Terraform state, use terraform state mv, which rewrites the resource’s address in state so Terraform treats an existing real-world object as a different configured resource without destroying or recreating it. It is the classic tool for refactoring: renaming resources, splitting configs, or moving resources into modules.

Read full answer

Applies toTerraform 1.x (and OpenTofu 1.x); behavior is identical for both.

How It Works

  • The command edits only state; it never calls the provider or touches real infrastructure.

  • Syntax: terraform state mv <source_address> <destination_address>.

  • After running it, terraform plan should show no changes if the configuration matches the new address.

  • It requires a state lock; with a remote backend the lock is acquired automatically, and the move is atomic across the team.

Common Use Cases

  • Renaming a resource: terraform state mv aws_instance.web aws_instance.app.

  • Moving into a module: terraform state mv aws_s3_bucket.logs module.logging.aws_s3_bucket.logs.

  • Moving between states: use -state / -state-out to migrate resources across separate state files, useful when splitting a monolith into multiple roots.

  • Moving a whole module: terraform state mv module.old module.new.

Modern Alternative: moved Blocks

Since Terraform 1.1, a moved block in configuration performs the same migration declaratively and is recorded in version control:

moved {
  from = aws_instance.web
  to   = aws_instance.app
}

Running terraform apply then performs the state move automatically. This is preferred in CI/CD because the migration is reviewable in a pull request and reproducible, whereas terraform state mv is an imperative, one-off operation.

Failure Modes and Safety

  • Wrong address / typo: the command fails before writing; nothing changes. Always run terraform plan afterward to confirm zero diff.

  • State drift: if the real object changed since the last apply, the move still succeeds but the next plan may show unexpected changes. Refresh first with terraform plan -refresh-only.

  • Locking conflicts: concurrent runs fail with a lock error; coordinate via the backend lock (DynamoDB for S3, GCS native locking, etc.).

  • Secrets in state: the move does not remove sensitive values; state remains sensitive. Use remote backends with encryption and restrict access.

  • Cross-workspace moves: not supported directly; use separate state files with -state-out.

Best Practices

  • Prefer moved blocks for tracked, reviewable migrations; reserve terraform state mv for ad-hoc or emergency fixes.

  • Always back up state (terraform state pull > backup.tfstate) before manual edits.

  • Run terraform plan immediately after and require a clean plan before merging.

  • Never edit the state JSON by hand; use terraform state subcommands or moved blocks.

Code Example

# Back up current state first
terraform state pull > state-backup.json

# Move a resource to a new address
terraform state mv aws_instance.web aws_instance.app

# Verify no diff
terraform plan
42

What does terraform state rm remove from Terraform state?

terraform state rm removes a resource instance from Terraform’s state without destroying the corresponding cloud resource. It is a state-only “forget” operation for situations such as removing an invalid state binding or handing an existing object to another management process.

Read full answer

Applies toTerraform 1.x and OpenTofu 1.x

What the Command Removes

terraform state rm RESOURCE_ADDRESS removes the state object identified by the resource address from the current backend and workspace. It does not:

  • Call the cloud provider’s delete API.

  • Remove the resource from Terraform configuration.

  • Prevent Terraform from proposing the resource again when its configuration remains present.

  • Securely erase the data from historical state versions, backend backups, or logs.

The updated state is written according to the backend’s normal persistence and locking behavior. A local backend updates its local state file. A remote backend writes updated state to its configured storage; historical versions exist only when supported by the backend or underlying storage service.

After removal, Terraform no longer tracks that object. If its configuration remains, the next plan normally proposes creating it again. The apply might fail because the object already exists, or it might create a duplicate depending on the resource and provider.

When to Use It

Common scenarios include:

  • Removing an invalid state entry: A corrupted or incorrectly recorded binding can be removed after verifying the real infrastructure and provider behavior.

  • Handing off an object: An existing object can be forgotten by Terraform before another tool or workflow adopts and manages it.

  • Manual state repair: An entry that prevents correct planning may need to be removed after investigation.

If an object was simply deleted outside Terraform, terraform state rm is normally unnecessary. A refresh normally detects that the object is absent, and Terraform can plan its recreation. If an existing object should become managed by Terraform, use terraform import rather than removing and recreating it.

Production and State Safety

State changes should be treated as production operations:

  • Backend and workspace: Confirm the active backend, workspace, provider account, and region before removing an entry. A mistake in the workspace can modify the wrong state.

  • Remote state: Use a supported remote backend with encryption, least-privilege access, locking, and tested recovery. Configure versioning and backups in the backend or its storage layer where supported.

  • Locking: Use locking to prevent concurrent Terraform operations from corrupting or overwriting state. Investigate abandoned locks instead of routinely forcing them.

  • Drift review: Run a refresh-only plan and inspect the provider inventory before removing state. This can reveal that the object was already destroyed or that its identity does not match the recorded binding.

  • Plan review: After removal, review a normal plan carefully, especially for unintended creation, replacement, or destruction of dependent resources.

  • Secrets: State can contain credentials, tokens, private keys, and sensitive attributes. Removing an entry from current state does not guarantee secure deletion from previous versions, backups, replicas, or logs.

  • Dependencies: Removing one resource does not remove dependent resources from state. A later plan may expose cascading replacements, invalid references, or provider errors.

Alternatives and Common Pitfalls

Goal Preferred approach
Stop managing an existing resource Remove its configuration and use a Terraform 1.7+ removed block with lifecycle { destroy = false }
Adopt an existing resource terraform import
Rename or relocate a resource A moved block, or terraform state mv when appropriate
Delete managed infrastructure terraform destroy or a carefully reviewed targeted apply
Remove an invalid state entry terraform state rm, followed by plan review

For a resource that must remain in service but stop being managed declaratively, removing its configuration and using a removed block is generally safer than manually editing state because the intent is reviewable in configuration. The older terraform state rm workflow remains valid when no declarative removal mechanism fits the situation.

OpenTofu provides the equivalent tofu state rm command and follows the same fundamental state-safety considerations.

43

What is Terraform drift and how is it detected?

Drift is a difference between real infrastructure and the configuration Terraform uses as its desired baseline. Terraform detects drift by refreshing state from the cloud provider during planning and comparing the refreshed values with both the stored state and the desired configuration.

Read full answer

Applies toTerraform 1.x and OpenTofu 1.x

Drift Types

Type Meaning Typical example
Infrastructure drift A managed resource changed outside Terraform, leaving its live configuration different from the recorded state An engineer edits a security-group rule in the AWS console
Configuration drift Terraform configuration changed but the change has not been applied A developer updates an instance type in HCL and commits it without running terraform apply

A mismatch between refreshed infrastructure and stored state is the signal that infrastructure drift exists, rather than a separate standard drift category. Only resources tracked in Terraform state can be evaluated for drift. Unmanaged resources are invisible unless they are explicitly imported.

How Detection Works

During a normal terraform plan, Terraform performs these operations:

  1. Reads the backend configuration and obtains the state lock.

  2. Calls provider APIs to read the current remote objects.

  3. Builds a refreshed working state from the observed values.

  4. Compares that state with the stored state and HCL configuration.

  5. Produces a plan describing the changes required to reach the desired configuration.

A normal plan can propose remediation for infrastructure drift along with any pending configuration changes. A refresh-only plan reports differences between the recorded state and reality without proposing remote infrastructure actions. Detection can be disabled with -refresh=false, so production checks should not use that option when drift visibility is required.

Detection Commands

Initialize the configured backend and providers with terraform init, then use terraform plan -refresh-only -no-color to report differences without modifying infrastructure. A normal terraform plan -out=tfplan produces a remediation plan, and terraform show -json tfplan can expose it in a machine-readable format for CI processing.

The equivalent OpenTofu 1.x refresh-only command is tofu plan -refresh-only -no-color.

For scheduled monitoring, use terraform plan -refresh-only -detailed-exitcode -no-color:

  • Exit code 0: no changes were detected.

  • Exit code 1: an error occurred.

  • Exit code 2: changes are present, indicating detected discrepancies.

Remote State and CI/CD

Production teams should use a remote backend with encryption at rest and in transit, state versioning where supported, restricted access, audit logging, and locking. Locking prevents concurrent Terraform operations from writing conflicting state. CI should not rely on local state because separate runners may observe different baselines.

A typical pipeline authenticates with short-lived OIDC credentials, initializes the backend, and runs terraform init -input=false followed by terraform plan -refresh-only -detailed-exitcode -no-color. Exit code 2 should trigger an alert or approval workflow rather than an automatic remediation.

For deployment approval, save and review the plan with terraform plan -out=tfplan and terraform show tfplan, then apply that exact artifact with terraform apply tfplan. A saved plan applies the changes captured during planning rather than creating a fresh plan.

Security and Operational Risks

  • Secrets can exist in state: Resource attributes and provider-returned credentials may be stored in state, even when marked sensitive. Encrypt the backend, restrict access, enable audit logs, and never commit state files to source control.

  • Provider errors can hide drift: An inaccessible or unavailable API response is not evidence that no drift exists. Fail the pipeline and investigate partial refreshes or inconsistent provider errors.

  • Unexpected deletions matter: If a resource disappears outside Terraform, a plan may propose recreating it. Review replacement risk for data loss, duplicate systems, and conflicting ownership.

  • Manual changes remain a process problem: Detect and alert on drift, then reconcile changes through Terraform or formally import the resource.

  • Review every remediation plan: Drift can trigger destructive replacement, including database replacement or network-boundary changes. Use approval gates and, where appropriate, lifecycle safeguards such as prevent_destroy.

44

What replaced Terraform refresh, and why was the command deprecated?

Terraform refresh was the legacy command for reconciling Terraform state with the current state of remote infrastructure. It has been replaced by the refresh-only workflow: terraform plan -refresh-only followed by terraform apply -refresh-only.

Read full answer

Applies toTerraform 1.x

What the Legacy Command Did

terraform refresh performed a refresh operation by reading managed resources and data sources from their providers and comparing the results with the values recorded in state.

It could update state to reflect:

  • Changes made to remote resources outside Terraform

  • Resources that had been deleted or recreated

  • Changed remote attributes, such as tags, security-group rules, or automatically assigned identifiers

  • New values returned by data sources

The command did not create, update, or delete remote infrastructure to match the configuration. Its purpose was primarily to update Terraform state so that a later plan could reason about the current world.

Why It Was Deprecated

The command combined two operations that should be reviewed separately:

  1. Reading and reconciling remote objects

  2. Writing the resulting information into state

Because terraform refresh could update state directly, it was easy to run it in automation without first reviewing exactly what would change. That could obscure drift, overwrite useful state history, or make it harder to understand whether a subsequent plan represented a real infrastructure change or merely a state reconciliation.

Terraform now exposes the refresh operation through explicit plan and apply workflows. Run terraform init, then terraform plan -refresh-only to review the proposed state changes. After review, run terraform apply -refresh-only to persist the refreshed state. A refresh-only apply updates state but does not propose or perform infrastructure changes needed to make remote objects match the configuration.

Refresh-Only Versus a Normal Plan

Operation Reads remote objects Updates state Changes infrastructure
terraform refresh Yes Yes No
terraform plan -refresh-only Yes No, until applied No
terraform apply -refresh-only Yes Yes No
terraform plan Yes, by default No as the primary operation No
terraform apply Yes, by default Yes Yes, when required

A normal terraform plan and terraform apply also perform an internal refresh phase before calculating configuration changes. Use -refresh-only when the goal is specifically to reconcile state without changing infrastructure.

For example, if a database was deleted outside Terraform, a refresh-only operation can remove it from state. A subsequent normal plan can then propose recreating the database. The refresh-only workflow itself will not recreate it.

Production and CI/CD Practices

  • Use remote state: Store state in a backend with encryption, access controls, versioning, and locking. Protect state files because they may contain sensitive values.

  • Review every plan: Treat refresh-only state changes as operational changes, especially when they remove resources from state.

  • Back up state: Retain versioned state history so an incorrect refresh can be investigated and recovered.

  • Run in controlled automation: A typical CI job initializes the backend, produces a refresh-only plan, and requires approval before applying it. Do not automatically apply unexplained state changes.

  • Monitor drift: Schedule refresh-only plans or use Terraform Cloud-style policy checks to detect out-of-band changes. Treat provider API errors, authentication failures, and lock contention as failed checks rather than assuming no drift exists.

  • Keep configuration changes separate: If the intent is to modify infrastructure, use a normal plan and apply rather than apply -refresh-only.

OpenTofu follows the same model; use tofu plan -refresh-only and tofu apply -refresh-only with the corresponding OpenTofu backend and provider versions.

45

How do you target one Terraform resource during apply, and why is it risky?

A targeted apply uses Terraform’s -target option to limit an operation to a specific resource and the dependencies Terraform calculates for it. It is useful for emergency recovery, but it is risky because it can leave the realized configuration and dependent infrastructure only partially updated.

Read full answer

Applies toTerraform 1.x with AWS provider 5.x

How It Works

Terraform normally builds a complete resource graph and applies the changes required to reach the desired state in the configuration. With -target, Terraform:

  • Selects the specified resource address.

  • Includes resources that the target depends on.

  • Excludes resources that depend on the target.

  • Applies changes to the selected resources and dependencies and writes the resulting state.

Resource addresses are used instead of physical IDs. Common forms include:

aws_instance.web
module.network.aws_subnet.private
aws_instance.web["api"]

Use terraform state list to discover the exact resource addresses in the current state.

Why It Is Risky

  • Incomplete dependency updates: Dependencies of the target are included, but dependents are not. For example, targeting an EC2 instance may update its subnet or security group and refresh its AMI data source without updating a load balancer, DNS record, or autoscaling configuration that relies on it.

  • Shared dependencies can still change: If the target uses a shared security group, VPC, or subnet, Terraform may modify that dependency and affect resources outside the intended target.

  • Configuration can become inconsistent: The target may be updated successfully while downstream resources retain old assumptions, causing failed deployments, traffic problems, or security exposure.

  • Refresh is not reconciliation: A targeted operation can refresh resources outside the target, but it does not apply their configuration changes. A later full plan can still expose omitted pending changes; do not assume the targeted operation reconciled the configuration.

  • Lifecycle behavior can be surprising: A target may require replacement, triggering deletion or recreation and affecting availability. Check the plan carefully for replace actions and infrastructure dependencies.

  • It is not a substitute for normal planning: A full plan can reveal required changes that a targeted plan omits. -target is intended for exceptional situations, not routine deployments.

Code Example

The following is a typical reviewed emergency workflow:

# Initialize the configured directory and backend
terraform init

# Confirm the production workspace
terraform workspace show
terraform workspace select production

# Review only the targeted operation and save the plan
terraform plan -target='aws_instance.web' -out=targeted.tfplan

# Inspect the saved plan before applying it
terraform show targeted.tfplan

# Apply exactly the reviewed targeted plan
terraform apply targeted.tfplan

The equivalent direct command is:

terraform apply -target='aws_instance.web'

Do not use -auto-approve for a production targeted apply unless an approved emergency procedure explicitly requires it. A saved plan is preferable because it separates planning from execution and ensures that the applied plan matches the reviewed plan.

Production and CI/CD Guidance

Use a remote backend with locking for production, and ensure that only authorized automation can update the state. Keep state encrypted and access-controlled because Terraform state commonly contains sensitive values, including passwords, private keys, tokens, and generated credentials.

In CI/CD:

  1. Run terraform init -backend-config=backend.hcl with the production backend configuration.

  2. Run a full terraform plan -out=plan.tfplan.

  3. Review the plan and policy checks.

  4. Apply the saved plan with terraform apply plan.tfplan.

Avoid using -target in routine pipelines. If it is necessary during an incident:

  • Confirm the exact resource address and all dependencies.

  • Review the targeted plan in detail.

  • Check the provider and Terraform logs for replacement or destructive actions.

  • Verify that backups, snapshots, rollback procedures, and monitoring are active.

  • Run a complete plan immediately afterward and reconcile any remaining changes.

  • Record the reason for the targeted operation and notify the team responsible for the affected service.

State locking prevents concurrent Terraform operations from writing the same state, but it does not make a targeted apply complete or safe. The safest recovery path is still a reviewed full plan unless the incident requires a narrowly scoped emergency change.

46

What are Terraform provisioners and why are they a last resort?

Provisioners are blocks that execute commands or copy files during a resource’s lifecycle. They are a last resort because their side effects are not modeled as declarative infrastructure, are not guaranteed to be idempotent, and are not represented by terraform plan.

Read full answer

Applies toTerraform 1.x and OpenTofu 1.x

What Provisioners Are

Terraform provides three built-in provisioner types:

  • local-exec: Runs a command on the machine executing Terraform.

  • remote-exec: Runs commands on a target through a configured connection, commonly SSH or WinRM.

  • file: Copies a file or inline content to the target.

A provisioner normally runs after its resource is created. With when = destroy, it runs before the resource is destroyed. A successful creation-time provisioner is not normally rerun on later applies unless the resource is replaced.

Why They Are a Last Resort

  • Not modeled in state: Terraform records the resource’s managed attributes, not what a script installed or changed.

  • No idempotency guarantee: Provisioner commands must be safe to rerun, but Terraform does not enforce that property.

  • Drift is hidden: A script can modify infrastructure outside Terraform’s model, so terraform plan cannot detect or represent those changes.

  • Lifecycle coupling: Provisioner failures can leave a resource only partially configured and interfere with later applies.

  • Operational fragility: remote-exec depends on networking, credentials, operating-system tools, and readiness conditions that Terraform does not fully manage.

  • Security exposure: Scripts may require broad administrative access or expose credentials in configuration, command arguments, logs, or downstream systems.

Failure Modes in Production

A failed creation-time provisioner commonly leaves the resource tainted, so a subsequent apply may destroy and recreate it. A failed destroy-time provisioner can leave destruction incomplete and requires careful recovery. Other common failures include SSH or WinRM connectivity problems, readiness races, unavailable package repositories, incompatible commands after an AMI or image change, and timeouts.

Provisioner failures should therefore be treated as incidents: inspect the resource, determine whether replacement is safe, and verify the service before allowing automated cleanup to proceed.

State and Production Safety

Use an encrypted remote backend for production state, enable locking, and prevent concurrent applies from corrupting state. Protect backend access with least privilege and audit logging, and never commit state files to source control.

Terraform state can contain sensitive resource attributes, outputs, and values passed through resource arguments; marking an output as sensitive only redacts CLI output and does not encrypt state. Avoid secrets in provisioner scripts and use instance profiles, workload identity, or a secret manager instead.

Because terraform plan does not show arbitrary script side effects, review provisioner scripts and their version changes alongside the plan. Run applies through CI/CD with approval gates, capture logs, monitor the resulting service, and test script upgrades before production use.

Preferred Alternatives

  • Native provider resources and data sources: Model the desired infrastructure directly and let Terraform manage its lifecycle.

  • Cloud-init or instance user data: Appropriate for some first-boot configuration, although secrets must not be embedded and later drift still requires monitoring.

  • Packer images: Bake stable dependencies into a versioned machine image before deployment.

  • Configuration management: Use Ansible, Chef, or Salt from a controlled automation workflow for repeatable configuration.

  • null_resource with triggers: Useful for some standalone actions, but it does not solve idempotency, state, or drift concerns.

Best Practices

Use a provisioner only when no native resource or better-managed alternative exists. Keep commands idempotent, add bounded retries where appropriate, and avoid on_failure = continue unless partial configuration is explicitly acceptable. Store scripts in version control, review them as application code, and test them against the exact operating-system image. After apply, verify both the resource and the service it was intended to configure, and monitor for drift and failed automation.

47

What are null_resource and terraform_data in Terraform?

null_resource and terraform_data are Terraform resources for managing work that does not correspond to a real cloud object. They are useful for executing scripts, representing configuration revisions, or forcing replacement when a value changes.

Read full answer

Applies toTerraform 1.4+ and OpenTofu 1.6+; HashiCorp Null provider 3.x

What They Are

  • null_resource: A resource implemented by the hashicorp/null provider. It creates no infrastructure but can run provisioners such as local-exec or remote-exec.

  • terraform_data: A built-in Terraform resource that stores an arbitrary value in input and supports replacement through triggers_replace. It requires no additional provider and is generally the preferred choice in current Terraform versions.

  • Neither resource manages an actual cloud API object. Their purpose is orchestration, scripting, or tracking a logical change.

Key Differences

Capability null_resource terraform_data
Provider hashicorp/null Built into Terraform
Replacement trigger triggers triggers_replace
General-purpose value attribute None; triggers is a map of strings input accepts a dynamic value
Provisioners Supported Supported
Typical use Existing workflows and script execution Change tracking and script execution
Preferred today When compatibility requires it Usually yes

terraform_data separates ordinary state updates from replacement behavior. Changing input updates the resource in place, while changing triggers_replace causes Terraform to replace it.

How Lifecycle Works

Terraform compares the configuration with prior state and adds the required create, update, replace, or destroy operations to its dependency graph.

  • A local-exec provisioner normally runs during creation, not during an ordinary update.

  • Changing a null_resource trigger or a terraform_data replacement trigger causes replacement, which normally runs creation provisioners again.

  • Destroy-time provisioners can perform cleanup, but a failure can prevent or complicate destruction.

  • terraform plan refreshes provider-managed objects. It generally cannot detect drift in a local file, installed package, or other side effect created by a provisioner.

Production Considerations

  • Prefer native resources: Use AWS, Azure, Google Cloud, Kubernetes, or other provider resources for real infrastructure. These two resources do not reconcile or validate the objects they act upon.

  • Make scripts idempotent: A provisioner may run again after an apply failure. Safe scripts should verify the current state before making changes.

  • Expect partial failures: Terraform does not roll back external side effects. If local-exec fails, the resource can become tainted and the same command may run again.

  • Protect state: Use a remote backend with locking, encrypted storage, restricted access, backups, and reviewed plans. Values in terraform_data.input, terraform_data.triggers_replace, and null_resource.triggers are stored in state.

  • Do not store secrets casually: Marking a value sensitive redacts it from CLI output but does not remove it from Terraform state. Prefer secret managers or narrowly scoped environment variables.

  • Review drift limitations: Terraform tracks these resources, not the files, packages, or external systems changed by provisioners. Monitoring and reconciliation scripts may be necessary.

  • OpenTofu: OpenTofu 1.6+ supports the built-in terraform_data resource and follows the same distinction; null_resource remains available through the hashicorp/null provider.

48

How do you manage secrets securely in Terraform?

Secrets should be handled through short-lived identity, runtime secret retrieval, or resource-native managed credentials rather than committed Terraform configuration. Terraform variables and outputs marked sensitive only hide values in CLI output; they do not remove them from state or plan files.

Read full answer

Applies toTerraform 1.10 or later in the 1.x line, with AWS provider 5.x

Secure Design

  • Never commit credentials: Do not place access keys, database passwords, API tokens, or private keys in .tf files, .tfvars, CI variables, or Git history.

  • Prefer workload identity: Use GitHub Actions OIDC, IAM roles for service accounts, or instance/task roles to obtain temporary AWS credentials.

  • Retrieve secrets at runtime: Applications should use IAM permissions to read AWS Secrets Manager or SSM Parameter Store directly instead of passing secret values through Terraform.

  • Use managed credentials where available: Services such as Amazon RDS can create and rotate the master password in AWS Secrets Manager.

  • Treat state as a secret store: Any value read by Terraform may persist in state, including values from Secrets Manager data sources.

Provider Authentication

In CI, authenticate before running terraform init by using GitHub OIDC with aws-actions/configure-aws-credentials@v4. Configure role-to-assume and omit aws-access-key-id and aws-secret-access-key.

The IAM role trust policy should restrict the GitHub repository, branch, environment, and OIDC audience. CI receives temporary credentials that automatically expire, reducing exposure from long-lived secrets.

Avoid putting the token or credential file path in Terraform state. Where direct OIDC provider configuration is necessary, AWS provider 5.x supports assume_role.web_identity_token_file.

State and Remote Backends

  • Remote state: Store state in an encrypted S3-compatible backend rather than locally or in a repository.

  • Encryption: Enable backend encryption, preferably with a dedicated KMS key, and restrict key access to the CI role.

  • Locking: Use S3 native locking through use_lockfile = true for Terraform 1.10+. Older Terraform 1.x releases can use the S3 backend’s dynamodb_table, although DynamoDB locking is deprecated in newer Terraform releases.

  • Versioning: Enable state bucket versioning to recover from accidental state corruption or deletion.

  • Least privilege: Separate plan, apply, state-read, and break-glass roles. Audit state access and role assumptions.

  • Secret awareness: sensitive = true redacts normal output but does not encrypt or remove the value from state, a saved plan, crash logs, or CI artifacts.

Code Example

This configuration uses S3 native locking and lets Amazon RDS manage its master password in AWS Secrets Manager. Terraform never receives the generated password.

terraform {
  required_version = ">= 1.10.0, < 2.0.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }

  backend "s3" {
    bucket       = "example-terraform-state-us-east-1"
    key          = "production/application/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    kms_key_id   = "arn:aws:kms:us-east-1:111122223333:key/example-key-id"
    use_lockfile = true
  }
}

provider "aws" {
  region = "us-east-1"
}

variable "db_subnet_group_name" {
  type        = string
  description = "Subnet group used by the RDS instance."
}

resource "aws_db_instance" "application" {
  identifier     = "example-application"
  engine         = "postgres"
  instance_class = "db.t3.micro"
  allocated_storage = 20

  username = "application_admin"

  # Amazon RDS creates and stores the password in AWS Secrets Manager.
  manage_master_user_password = true

  db_subnet_group_name = var.db_subnet_group_name

  skip_final_snapshot       = false
  final_snapshot_identifier = "example-application-final"
}

output "master_user_secret_arn" {
  description = "ARN of the RDS-managed secret for runtime consumers."
  value       = aws_db_instance.application.master_user_secret[0].secret_arn
}

Bootstrap the state bucket and KMS key separately using a tightly controlled process. Then run:

terraform init -input=false
terraform plan -input=false -out=tfplan
terraform show -no-color tfplan
terraform apply -input=false tfplan

Treat tfplan as sensitive even when outputs are marked sensitive; do not upload it to an unprotected artifact store.

Production Operations

  • Rotation: Rotate secrets outside Terraform when the application fetches them at runtime. For RDS-managed passwords, configure Secrets Manager rotation and ensure applications refresh cached credentials.

  • Drift: Run scheduled plans to detect configuration changes. A secret changed directly in Secrets Manager is generally runtime state, not Terraform drift, unless Terraform reads it through a data source.

  • Monitoring: Alert on failed Secrets Manager reads, KMS access failures, unexpected role assumptions, state deletion, and lock contention.

  • Backups: Version and back up state, but manage secret backups and recovery procedures separately under AWS Secrets Manager controls.

  • Incident response: Revoke temporary roles and sessions, rotate affected credentials, preserve CloudTrail and state-access logs, and restore state only from a reviewed snapshot.

  • Upgrades: Commit the provider lock file, review provider changes, and test plans against a recent state snapshot before upgrading production.

OpenTofu follows the same security model: use tofu init, tofu plan, and tofu apply, verify backend compatibility, and never allow Terraform and OpenTofu to write the same state concurrently.

49

How do you integrate Terraform with Vault or secrets managers?

Terraform integrates with secret stores through provider data sources, resources, and workload access policies. The safest production pattern is to keep secret values out of Terraform state and let applications retrieve them at runtime using short-lived credentials.

Read full answer

Applies toTerraform 1.x (Terraform 1.10+ for native S3 locking and this example; Terraform 1.7+ for mocked-provider tests), HashiCorp Vault provider 4.x, and HashiCorp AWS provider 5.x

Integration Patterns

  • Consume the value in Terraform: A provider data source reads the secret, and Terraform passes it to another resource. This is convenient but places the value in state.

  • Manage metadata and access only: Terraform creates the secret container, IAM policy, Vault policy, or workload role without reading the secret value.

  • Runtime retrieval: The application authenticates to Vault or AWS Secrets Manager and obtains the secret or dynamic credentials directly. This is generally preferred for production.

  • Temporary bootstrapping: A sensitive pipeline or break-glass process can create the initial secret, after which Terraform manages only its lifecycle and permissions.

Requirement Vault AWS Secrets Manager
Dynamic credentials Database, cloud, and PKI secret engines Primarily static secrets with managed rotation
Authentication Vault token, JWT/OIDC, AWS IAM, Kubernetes auth IAM roles and workload identities
Terraform integration hashicorp/vault provider hashicorp/aws provider
Preferred Terraform responsibility Roles, policies, paths, and access Secret metadata, rotation settings, and IAM access

Code Example

This configuration references an existing AWS Secrets Manager secret and grants an existing ECS task role permission to read it. The secret value is not retrieved; secret metadata and the IAM policy are stored in state.

terraform {
  required_version = ">= 1.10.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
    vault = {
      source  = "hashicorp/vault"
      version = "~> 4.0"
    }
  }

  # Native S3 state locking requires Terraform 1.10 or later.
  backend "s3" {
    bucket       = "acme-terraform-state"
    key          = "production/app/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    use_lockfile = true
  }
}

provider "aws" {
  region = var.aws_region
}

provider "vault" {
  address = var.vault_addr
}

variable "aws_region" {
  type = string
}

variable "vault_addr" {
  type = string
}

variable "app_secret_name" {
  type = string
}

variable "task_role_name" {
  type = string
}

# Reads secret metadata only, not the secret value.
data "aws_secretsmanager_secret" "app" {
  name = var.app_secret_name
}

data "aws_iam_policy_document" "read_app_secret" {
  statement {
    sid       = "ReadAppSecret"
    effect    = "Allow"
    actions   = ["secretsmanager:GetSecretValue"]
    resources = [data.aws_secretsmanager_secret.app.arn]
  }
}

# Allows the ECS task role to retrieve the secret at runtime.
resource "aws_iam_role_policy" "read_app_secret" {
  name   = "read-app-secret"
  role   = var.task_role_name
  policy = data.aws_iam_policy_document.read_app_secret.json
}

The backend bucket must already exist, have versioning enabled, and restrict access to the Terraform execution role. If the secret uses a customer-managed KMS key, its key policy must also allow the task role to decrypt it. For Terraform older than 1.10, use a supported locking mechanism such as the legacy DynamoDB backend lock rather than native S3 locking.

Vault Integration

When Terraform must consume a KV v2 value, use the Vault provider:

data "vault_generic_secret" "app" {
  path = "secret/data/production/app"
}

The /data/ segment is required for KV v2. The provider can obtain VAULT_TOKEN from the environment, so CI should authenticate with a short-lived OIDC or JWT rather than store a static Vault token. Configure the Vault role’s token TTL, maximum TTL, and policies so the resulting Vault token is short-lived and least-privileged.

For dynamic database credentials, have the application request database/creds/app-role directly. Vault issues credentials with a TTL and can revoke them; Terraform should not persist those credentials in state.

State and Security

  • Secrets in state: sensitive = true only redacts CLI output. It does not encrypt state. Avoid vault_generic_secret, aws_secretsmanager_secret_version, and other resources that contain secret values.

  • Outputs and modules: Pass only nonsecret identifiers and policy configuration through module inputs and outputs. A sensitive module output is still stored in state, so do not export secret values.

  • Remote state: Use an encrypted remote backend with locking, restricted IAM, versioning, and access logging. Treat state backups as sensitive because they may contain historical secrets.

  • Workspaces: A workspace is not an authorization boundary. Use separate state keys and least-privilege backend, Vault, or cloud permissions where production isolation is required.

  • Lifecycle and import: Use prevent_destroy for critical secret containers and ignore_changes only for fields deliberately rotated outside Terraform. Import metadata or container resources using provider-documented identifiers; avoid importing value-bearing versions unless accepting state exposure.

  • Plan review: Run terraform plan -out=tfplan, inspect it with terraform show tfplan, require approval, and apply the reviewed file with terraform apply tfplan. Protect plan files because they can contain sensitive values.

  • Drift: Run terraform plan -refresh-only regularly to identify out-of-band changes. Distinguish configuration drift from expected secret rotation.

  • Authentication: Use CI OIDC, workload identity, or instance roles. Never commit .tfvars, provider tokens, or cloud credentials.

  • Testing: Use terraform test with .tftest.hcl and mocked providers to validate policy wiring without live secrets; test authentication and authorization separately in staging.

CI/CD and Production Operations

A Vault-enabled CI job can authenticate and run a reviewed plan:

export VAULT_ADDR="https://vault.example.com:8200"

# The JWT must satisfy the Vault role's audience and claim constraints.
export VAULT_TOKEN="$(vault write -field=token auth/jwt/login \
  role=terraform-ci jwt="$CI_JWT")"

terraform init -input=false
terraform plan -out=tfplan
terraform show tfplan
terraform apply tfplan

Monitor failed provider authentication, denied secret access, state-lock conflicts, failed rotation jobs, expired dynamic credentials, and unusual read volume. Back up state, audit secret access separately, and stage provider upgrades before updating committed lock files. OpenTofu 1.x supports similar provider patterns, but backend locking must match the installed OpenTofu version.

Common Failure Modes

  • Wrong Vault KV v2 path or missing VAULT_NAMESPACE causes lookup failures.

  • An expired token, incorrect Vault role binding, or missing IAM role policy causes access denial.

  • Long-running applications can fail after rotation if they do not refresh cached credentials.

  • Applying an unreviewed plan can modify infrastructure or expose new secret paths.

50

What do terraform fmt and terraform validate do?

terraform fmt is Terraform’s built-in formatter that rewrites HCL files to a canonical style, while terraform validate checks configuration syntax and internal consistency without contacting cloud APIs or reading state.

Read full answer

Applies toTerraform 1.x (OpenTofu 1.x compatible)

How terraform fmt Works

  • Rewrites .tf and .tfvars files in place to canonical formatting: consistent indentation, aligned = signs, normalized spacing and block layout.

  • Operates on the current directory by default; use -recursive to format subdirectories such as modules.

  • -check exits non-zero if any file would change, making it a CI gate; -diff prints the proposed changes.

  • Never changes semantics, resource names, or values; it only touches whitespace and layout, so it is safe to run automatically.

  • Does not validate providers, types, or references, and does not need terraform init.

How terraform validate Works

  • Parses configuration and checks syntax plus internal consistency: required provider blocks, variable and output types, resource references, module inputs/outputs, and lifecycle arguments.

  • Requires an initialized working directory (terraform init) so provider schemas are available for type checking; it does not download anything new.

  • Does not read remote state, call cloud APIs, or verify credentials, so it cannot detect drift, missing resources, or permission errors.

  • Reports errors and warnings with file/line context and returns a non-zero exit code on failure.

  • Run it after terraform fmt and before terraform plan in CI.

Comparison

Aspect terraform fmt terraform validate
Primary purpose Canonical formatting Syntax and consistency checks
Modifies files Yes No
Needs terraform init No Yes (for provider schemas)
Network / cloud access No No
Catches drift or missing resources No No
Typical CI use terraform fmt -check -recursive terraform validate

Best Practices and Common Pitfalls

  • Run terraform fmt -check -recursive and terraform validate as separate CI steps so formatting failures are distinct from logic errors.

  • Add a pre-commit hook or IDE format-on-save so fmt never blocks a pull request.

  • Do not treat a passing validate as proof of a safe apply: it will not catch invalid AMI IDs, wrong CIDRs, or IAM permission gaps, which only surface during terraform plan or apply.

  • Keep provider versions pinned in required_providers; validate checks against the installed schema, so stale provider caches can hide version-specific errors.

  • In OpenTofu environments, use tofu fmt and tofu validate with identical flags and behavior.

51

How do you test Terraform modules and configurations?

Testing Terraform combines static validation, mocked plan/apply tests, and isolated integration tests against real infrastructure. The most effective approach is a testing pyramid: fast unit tests for most modules, followed by fewer integration tests that verify provider and cloud behavior.

Read full answer

Applies toTerraform 1.9 or later in the 1.x series with AWS provider 5.x; OpenTofu 1.9 or later with equivalent native test features

Test Layers and Commands

Use several complementary checks in CI and locally:

  • Formatting and syntax: terraform fmt -check -recursive checks formatting across .tf and .tftest.hcl files.

  • Configuration validation: terraform init -backend=false installs providers without configuring a backend, and terraform validate checks references, types, and configuration structure.

  • Plan tests: terraform plan exercises provider schemas and reveals changes before applying them.

  • Native tests: terraform test -verbose runs test files, supports mocked providers, and verifies assertions.

  • Static analysis: Tools such as TFLint, Checkov, and tfsec can detect style issues, insecure settings, and policy violations before deployment.

terraform validate does not prove that a cloud API will accept a resource, that IAM permissions are correct, or that the resulting infrastructure is operationally sound.

Native Test Example

The following test verifies both a valid bucket configuration and a rejected variable. The mocked AWS provider avoids making real API calls. Provider mocking requires Terraform 1.7+, while the variable-validation expect_failures form shown here requires Terraform 1.9+.

main.tf:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

variable "bucket_name" {
  type = string

  validation {
    # Reject names that violate the module's naming policy.
    condition     = can(regex("^[a-z0-9][a-z0-9.-]{1,61}[a-z0-9]$", var.bucket_name))
    error_message = "bucket_name must be 3-63 characters and use only lowercase letters, digits, dots, or hyphens."
  }
}

resource "aws_s3_bucket" "example" {
  bucket = var.bucket_name
}

output "bucket_arn" {
  value = aws_s3_bucket.example.arn
}

tests/bucket.tftest.hcl:

# Supply computed values locally without calling AWS.
mock_provider "aws" {
  mock_resource "aws_s3_bucket" {
    defaults = {
      arn = "arn:aws:s3:::example-bucket"
    }
  }
}

run "create_bucket" {
  command = plan

  variables {
    bucket_name = "example-bucket"
  }

  assert {
    condition     = aws_s3_bucket.example.bucket == "example-bucket"
    error_message = "The bucket name was not passed to the S3 resource."
  }
}

run "reject_invalid_bucket_name" {
  command = plan

  variables {
    bucket_name = "Invalid_Bucket"
  }

  # The plan must fail because input validation rejects this value.
  expect_failures = [var.bucket_name]
}

Mocked tests are fast and deterministic, but they do not validate AWS-side behavior such as IAM behavior, eventual consistency, quotas, service-specific validation, or API throttling.

Integration Tests, Modules, and State

  • Test reusable modules with representative inputs and assert their outputs, resources, and expected failures.

  • Test data sources and provider configuration separately. A mocked provider can validate Terraform wiring, but real integration tests are needed to verify permissions, remote API responses, and cross-service behavior.

  • Run real apply tests only in a dedicated AWS account, project, or disposable environment. Never use production credentials for tests.

  • Keep remote state in an encrypted backend with locking enabled. Use separate state keys or separate accounts for test environments; Terraform workspaces are not a security boundary.

  • Remember that state may contain secrets. sensitive = true hides a value in normal output but does not remove it from state.

  • Test imports and drift detection by importing an existing resource, running terraform plan, and confirming that the expected resources are managed without destructive changes.

  • Exercise lifecycle behavior such as prevent_destroy, create_before_destroy, and ignore_changes deliberately. These rules can block cleanup or create replacement-ordering failures.

  • OpenTofu 1.9+ can be used with tofu test where equivalent native test and mocking capabilities are required.

CI/CD and Production Practices

For pull requests, run formatting, validation, native tests, security scanning, and a plan using read-only credentials. For example:

terraform fmt -check -recursive
terraform init -backend=false
terraform validate
terraform test -verbose

For deployment, create a saved plan against the intended backend:

terraform plan -out=tfplan
terraform show -json tfplan > tfplan.json

Review tfplan.json and the human-readable plan before approval. Apply the exact saved plan in a protected job:

terraform apply tfplan

The plan artifact and state must be protected because they can contain sensitive values. Keep backend locking enabled and ensure only the deployment role can modify production state.

After deployment, monitor provider-side metrics, drift, failed CloudTrail events, backup status, and quota or throttling alarms. Test backup and disaster-recovery resources as code—for example, S3 versioning or RDS backup settings—and verify that recovery procedures work in a separate environment.

Common Failure Modes

  • Mock-only coverage: Terraform expressions pass while real AWS permissions or APIs fail.

  • Shared test state: tests accidentally read or modify production resources.

  • Non-idempotent assertions: tests depend on fixed resource IDs, timestamps, or prior run order.

  • Missing cleanup: failed integration tests leave resources behind; use isolated accounts and verify teardown.

  • Unreviewed plans: automated applies bypass human review or use different variables than the reviewed plan.

  • Provider upgrades: pin and test provider versions, review deprecation warnings, and roll back through a reviewed plan rather than editing state manually.

52

How does the Terraform 1.x test command work?

terraform test runs Terraform’s native integration-test harness against *.tftest.hcl files. It executes ordered test scenarios, evaluates assertions against the configuration under test, and returns a nonzero exit code when a run or assertion fails.

Read full answer

Applies toTerraform 1.6+; `mock_provider`, `override_resource`, and `override_data` require Terraform 1.7+

How It Works

  1. terraform init initializes the configuration and installs providers required by the configuration and test files.

  2. terraform test discovers test files, normally in the tests directory.

  3. Each file contains one or more run blocks. Terraform executes them sequentially, and later runs can use state and outputs produced by earlier runs.

  4. Each run executes a Terraform operation, after which its assertions are evaluated.

  5. Terraform reports each test result and exits unsuccessfully if a command fails or an assertion evaluates to false.

The execution mode is selected with the run block’s command attribute:

  • command = apply: Applies the configuration and can create real infrastructure. This is the default when command is omitted.

  • command = plan: Produces a plan without modifying managed resources. It can still contact providers to refresh state or read data.

Useful command-line options include:

  • -filter=tests/example.tftest.hcl: Run only the selected test file.

  • -test-directory=path: Use a directory other than tests.

  • -verbose: Produce detailed test output.

  • -json: Emit machine-readable output for CI systems.

Assertions and Test Scope

An assertion compares a test expression with an expected result. Test expressions can refer to variables, module outputs, resource attributes, data-source results, and outputs from earlier runs. Conditions must have known values; an unknown planned value cannot be meaningfully compared.

A run block may also use expect_failures to declare that particular resource or variable operations are expected to fail. The test fails if the expected failure does not occur.

Assertions should not embed credentials, tokens, or sensitive customer data in expected values or error messages. Test output, CI logs, and state may expose such material.

Provider Isolation and Cleanup

Because apply is the default mode, a test can call real provider APIs and create billable resources unless the configuration or provider behavior prevents it. Run such tests in a dedicated cloud account, project, or subscription with least-privilege credentials.

Terraform 1.7 introduced mock providers and resource/data overrides. Mocks can simulate provider responses without making cloud API calls, making them useful for fast unit-style tests. They do not validate IAM permissions, quotas, networking, service consistency, or other cloud-side behavior, so they should complement rather than replace isolated real-cloud integration tests.

After a test file completes, Terraform attempts to destroy resources created by its apply runs. Cleanup is best-effort, and an interrupted process or provider failure can leave resources behind, so production test environments still need inventory and reconciliation.

Code Example

Create a minimal module:

# main.tf
variable "environment" {
  type = string
}

output "service_name" {
  value = "${var.environment}-service"
}

Create its test file:

# tests/service_name.tftest.hcl
run "service_name" {
  command = plan

  variables {
    environment = "staging"
  }

  assert {
    condition     = output.service_name == "staging-service"
    error_message = "The service name was not derived correctly."
  }
}

Run the tests:

# Initialize providers without initializing a remote backend
terraform init -backend=false

# Run every discovered test
terraform test

# Produce detailed or machine-readable output
terraform test -verbose
terraform test -json

# Run a specific test file
terraform test -filter=tests/service_name.tftest.hcl

Production and CI/CD Safety

  • Isolate real tests: Use a dedicated environment, restricted credentials, quotas, budgets, and alerts for billable resources.

  • Protect and recover state: Production workflows should use an encrypted remote backend with access controls, versioning, locking, and tested restoration procedures.

  • Treat state as sensitive: sensitive = true redacts values in normal Terraform output, but it does not encrypt plaintext in state. Avoid passing secrets as variables or resource arguments when a secret manager can supply them at runtime.

  • Use tests as one CI gate: Parse terraform test -json or check its exit code, but do not treat passing tests as a replacement for state refresh, drift detection, a reviewed terraform plan, approval, and a locked apply.

  • Separate workspaces deliberately: Terraform workspaces help organize state but are not strong security boundaries; enforce isolation through backend permissions and cloud IAM.

  • Reconcile cleanup failures: Alert on resources left behind by interrupted or failed tests and clean them up through a controlled process.

  • Account for OpenTofu: OpenTofu provides a similar tofu test command and test-file format for teams standardizing on OpenTofu.

53

How do you use TFLint, Checkov, and tfsec in Terraform workflows?

TFLint, Checkov, and tfsec are complementary Terraform analysis tools: TFLint applies Terraform and provider-specific lint rules, while Checkov and tfsec evaluate security policies. For new pipelines, use Checkov and Trivy Configuration Scanning; tfsec is archived and should be retained only for legacy migrations.

Read full answer

Applies toTerraform 1.6+, OpenTofu 1.6+, TFLint 0.50+, Checkov 3.x, Trivy 0.50+, and tfsec 1.28.x (legacy, archived)

How the Tools Differ

Tool Primary purpose Typical findings
TFLint Terraform linter with built-in and provider-specific rulesets Deprecated syntax, invalid instance types, unused declarations
Checkov Policy-based infrastructure-as-code scanner Public exposure, unencrypted storage, missing logging, custom organizational policies
Trivy Configuration Scanning Security scanner incorporating tfsec-style checks Insecure defaults, exposed services, cloud misconfigurations
tfsec Archived security scanner Similar to Trivy; use only while maintaining or migrating existing pipelines

In source-directory mode, these tools inspect .tf and .tf.json files without authenticating to a cloud account or reading Terraform state. Plan-file scanning is a separate mode.

Recommended Workflow

  • TFLint: Run tflint --init in each Terraform root module before linting. Put provider rulesets in that module’s .tflint.hcl and pin exact ruleset versions; use immutable versions or digests for the scanner binary and CI action or container.

  • Checkov: Run it against the Terraform directory with --framework terraform. Use --check or --skip-check with specific policy IDs, and add organizational Python policies with --external-checks-dir.

  • Trivy: Prefer trivy config for new pipelines. Use --exit-code 1 when findings should fail CI and use severity filtering when introducing the tool to an established repository.

  • tfsec: Keep existing jobs temporarily, but migrate them to Trivy rather than adding new dependencies on the archived project.

Terraform and OpenTofu Coverage

Source scanners parse provider, resource, data source, variable, output, module, lifecycle, and import declarations, although policy coverage varies. Lifecycle and import blocks do not prove runtime safety, and unresolved variables or data-source values can hide insecure effective configurations.

Run TFLint against every root module and keep local child modules available to scanners that follow them. Static analysis does not select a Terraform workspace, so CI matrices for multiple workspaces should use isolated backend paths or state keys. Run scanners over test fixtures and run terraform test separately on Terraform 1.6+. Checkov and Trivy can also scan Terraform plan JSON to evaluate resolved values.

Code Example

Run these as separate CI jobs so one failed scanner does not hide results from the others:

# Validate Terraform without configuring or accessing its remote backend
(
  cd terraform
  terraform fmt -check -recursive
  terraform init -backend=false
  terraform validate
)

# Initialize TFLint rulesets from the module's .tflint.hcl, then lint
(
  cd terraform
  tflint --init
  tflint --format=json --output-file=../tflint.json
)

# Evaluate security policies and retain machine-readable results
checkov -d terraform --framework terraform \
  --output json --output-file-path checkov.json

trivy config --severity HIGH,CRITICAL --exit-code 1 \
  --format json --output trivy.json terraform/

# Existing legacy pipeline only
tfsec terraform/ --format=json --out=tfsec.json

With OpenTofu, use tofu init -backend=false and tofu validate; the source scanners can analyze the same HCL.

CI/CD and Production Behavior

  • Scan before planning: Run formatting, validation, TFLint, and source-policy scans before generating a plan. Then generate a saved plan, scan its JSON representation where supported, review it, and apply that same reviewed plan.

  • Keep checks separate from apply: Static analysis cannot prove that terraform apply will succeed. Protect production with plan review, approval gates, and narrowly scoped apply credentials.

  • Manage false positives: Record exceptions with an owner, reason, scope, and expiration date rather than globally disabling a policy.

  • Control sensitive output: Findings can expose resource names, source lines, hardcoded secrets, or resolved plan values. Keep complete output in trusted security systems and avoid public artifacts.

  • Pin dependencies: Pin TFLint ruleset versions, scanner executables, CI actions by commit SHA, and container images by digest.

State Safety and Drift

Static scanners do not replace state management. Use a supported remote backend with locking, restrict state access, and enable encryption and versioning where the backend supports them. Terraform state can contain sensitive values even when outputs are marked sensitive, so never commit *.tfstate, saved plans, or artifacts containing secrets.

Static analysis cannot detect drift between source and live infrastructure. Review terraform plan -refresh-only, apply state refreshes deliberately, and use an ordinary reviewed plan before making changes. A CI planning identity still needs state-read access and may need backend lock permissions; refresh also requires cloud API read permissions. Concurrent jobs targeting the same state can contend on locks and should not disable locking merely to avoid waiting.

54

How does policy as code work with Sentinel or OPA in Terraform?

Policy as code means encoding infrastructure requirements as version-controlled rules that are evaluated automatically against a Terraform plan before production changes are applied. Sentinel provides native governance in HCP Terraform and Terraform Enterprise, while OPA evaluates exported plan data in an external CI/CD or service integration.

Read full answer

Applies toTerraform 1.x, OPA 1.x, and Sentinel in current HCP Terraform and Terraform Enterprise releases

How Enforcement Works

Terraform produces a plan containing the proposed resource changes. A policy engine evaluates that plan and produces one of three outcomes:

  • Allow: The plan satisfies the policy and can continue.

  • Deny: The plan contains a prohibited change and must not be applied.

  • Advisory warning: The violation is reported but does not block the workflow.

Policies should live in Git, undergo peer review, and be tested against accepted and rejected plans. Production promotion should use the exact saved plan that passed policy evaluation rather than generating a new plan after approval.

Terraform expands reusable module calls into concrete planned resources before policy evaluation. Policies therefore inspect the resulting resource-change model, including resource types, addresses, proposed actions, and before/after values, rather than directly parsing module source code.

Sentinel and OPA

Area Sentinel OPA
Ownership HashiCorp CNCF Open Policy Agent project
Policy language Sentinel Rego
Terraform integration Native policy sets attached to HCP Terraform or Terraform Enterprise workspaces External evaluation through the OPA CLI, API, or CI/CD integration
Enforcement modes Advisory, soft-mandatory, and hard-mandatory Determined by the integration and the result returned by the policy
Scope Optimized for HashiCorp Terraform governance Usable across Terraform, Kubernetes, CI/CD, APIs, and other systems
Portability Strongest within the HashiCorp platform Broader portability across policy consumers

Sentinel is usually the simplest choice when HCP Terraform or Terraform Enterprise is already the deployment platform. OPA is attractive when the same policies must govern multiple systems or when the organization wants a policy service independent of Terraform.

CI/CD Workflow

A typical external OPA workflow is:

  1. Commit Terraform configuration and policy files to version-controlled repositories or directories.

  2. Run terraform init and terraform validate in CI.

  3. Create a saved plan with terraform plan -out=tfplan.

  4. Export the plan as JSON with terraform show -json tfplan for policy evaluation.

  5. Evaluate the JSON with OPA and fail the CI job when the policy denies it.

  6. Require approval for production changes.

  7. Apply the exact reviewed plan with terraform apply tfplan.

For Sentinel, the equivalent enforcement occurs inside the HCP Terraform or Terraform Enterprise workflow, where policy sets are associated with workspaces and evaluated during the plan/apply governance process. OpenTofu 1.x can use an equivalent external OPA gate in CI, but teams should not assume that HCP Terraform’s native Sentinel attachment is available to their OpenTofu workflow.

State, Security, and Failure Modes

  • State safety: Use a remote backend with encryption, access controls, versioning, backups, and locking where the backend supports it. Treat state as sensitive because sensitive variables and provider credentials can still be present in state.

  • Plan confidentiality: Saved plan files and exported plan JSON can contain sensitive values in clear text. Store them in protected temporary storage, restrict access, and delete them according to the retention policy.

  • Plan integrity: Bind policy results to the reviewed plan and apply that exact saved plan. Do not regenerate it after approval.

  • Drift detection: Run scheduled plans, including refresh-only plans where appropriate, to identify changes made outside Terraform.

  • Policy availability: Decide whether an unavailable policy service fails open or closed. Production controls generally favor failing closed, with a controlled break-glass procedure.

  • Incomplete context: A plan does not contain every runtime condition. Combine policy checks with IAM, AWS Organizations controls, cloud-native preventive controls, monitoring, and incident response.

  • Operational impact: Introduce new rules in advisory mode, measure violations and false positives, and then enable blocking enforcement for mature, high-confidence policies.

Production Best Practices

  • Store policies in Git and require pull-request review for both policy and Terraform changes.

  • Pin Terraform, OpenTofu, OPA, providers, and policy versions; test upgrades before promotion.

  • Use Terraform tests for Terraform behavior and separate OPA tests against known-good and known-bad plan fixtures.

  • Prefer narrow, explainable policies with actionable violation messages.

  • Log the policy version, decision, plan identifier, and remediation guidance for auditability.

  • Retrieve credentials from a secret manager or protected CI identity rather than hard-coding them in configuration or policies.

  • Coordinate policy rollout with provisioning, state backup and restoration tests, monitoring, and incident-response procedures so blocked changes do not create unnoticed configuration gaps.

55

How do you run Terraform in CI/CD pipelines?

Running Terraform in CI/CD means automating init, validate, plan, and apply against a remote state backend with locking, so infrastructure changes are reviewed before merge and applied only from trusted pipelines.

Read full answer

Applies toTerraform 1.x (and OpenTofu 1.x) with AWS provider 5.x.

Pipeline Stages

A typical pipeline runs these steps in order:

  1. terraform init — download providers and configure the remote backend.

  2. terraform fmt -check and terraform validate — catch formatting and syntax errors early.

  3. terraform plan -out=tfplan — compute the diff and save it to a plan file (in a multi-job pipeline, upload it as a protected artifact for the apply job).

  4. Post the plan output to the pull request for human review.

  5. On merge to the default branch, plan again and terraform apply -input=false tfplan — apply that saved plan, ideally behind an approval gate so a person reviews it first.

Never run apply automatically on pull requests; only on merge. Use -input=false so a missing variable fails the job instead of hanging.

State Safety

  • Use a remote backend (S3 + DynamoDB lock table on AWS, or Terraform Cloud/Enterprise) so state is shared and locked.

  • Enable encryption at rest on the backend; state files contain secrets and resource attributes.

  • Mark sensitive outputs with sensitive = true to reduce accidental leakage in logs.

  • Locking prevents two concurrent applies from corrupting state; if a lock is stuck, investigate before force-unlocking.

Authentication and Secrets

  • Prefer OIDC federation from the CI runner to the cloud provider instead of long-lived access keys.

  • Grant the CI role least-privilege permissions scoped to the state bucket, lock table, and managed resources.

  • Mask plan output in logs where it may contain secrets, and avoid echoing variable values.

Drift and Review

  • Schedule a periodic terraform plan (nightly or weekly) to detect drift from manual changes.

  • Require plan review and approval gates for production workspaces.

  • Pin Terraform and provider versions in CI to make runs reproducible.

Code Example

Backend configuration:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }

  backend "s3" {
    bucket         = "example-tf-state"
    key            = "prod/terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "terraform-locks"
    encrypt        = true
  }
}

GitHub Actions workflow:

name: Terraform
on:
  pull_request:
  push:
    branches: [main]

permissions:
  id-token: write
  contents: read

jobs:
  terraform:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: hashicorp/setup-terraform@v3
        with:
          terraform_version: 1.9.0
      - uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/terraform-ci
          aws-region: us-east-1
      - run: terraform init
      - run: terraform fmt -check
      - run: terraform validate
      - run: terraform plan -out=tfplan -input=false
      - if: github.event_name == 'push'
        run: terraform apply -input=false tfplan

Best Practices and Pitfalls

  • Save the plan file and apply that exact file; do not re-plan before apply.

  • Use separate workspaces or directories per environment with distinct state keys.

  • Fail the pipeline on any plan error rather than continuing.

  • OpenTofu is a drop-in alternative for most workflows; verify provider compatibility before switching.

56

How does the Terraform plan-review-apply pull request workflow work?

The plan-review-apply pull request workflow separates permission to preview infrastructure changes from permission to modify production resources. A pull-request pipeline creates and publishes a Terraform plan, reviewers inspect the proposed operations, and a trusted post-merge pipeline applies the approved plan.

Read full answer

Applies toTerraform 1.10-1.x; OpenTofu 1.x only for the analogous `tofu` workflow

Workflow Stages

Stage Actions Recommended permissions
Pull request Initialize, format-check, validate, generate a plan, and publish its human-readable representation Read state and cloud APIs; no production mutation
Review Inspect the HCL diff, planned operations, replacements, destroys, policy results, and generated plan summary Human approval and policy-engine approval
Merge Merge the reviewed branch into the protected main branch Repository write access only
Apply Apply the exact reviewed plan from the trusted post-merge workflow and write the resulting state State write and cloud mutation permissions

A common implementation saves the plan file as a CI artifact during pull-request validation and applies that exact artifact after merge. Terraform rejects the saved plan if the relevant state or configuration has changed, preventing a stale plan from silently applying different operations. An alternative is to generate a fresh plan after merging and compare it with the reviewed output; any material difference requires another approval.

Reviewers should examine more than the HCL diff. The plan shows the actual provider-level create, update, replace, and destroy operations, including destructive changes to databases, load balancers, and other stateful resources.

What Happens Under the Hood

  1. terraform init installs the required providers and initializes the configured remote backend.

  2. terraform validate checks the configuration’s syntax, internal references, and provider schemas.

  3. terraform plan reads the prior state, refreshes relevant remote objects, and computes the operations required to reach the desired configuration.

  4. terraform show renders the machine-readable saved plan in a review-friendly format.

  5. terraform apply verifies that the saved plan remains valid, executes its provider operations, and writes the new state.

A saved plan includes planned resource attributes and may contain sensitive values in plaintext. Human-readable plan output is a review aid, not a substitute for controlling access to the binary plan artifact.

State Safety and Security

  • Remote state: Store production state in an encrypted remote backend with least-privilege access, audit logging, versioning, and tested restoration procedures.

  • Locking: Use backend locking for state-changing operations. Terraform 1.10 and later support native S3 lock files through use_lockfile = true; plans and applies both require appropriate locking.

  • IAM permissions: For the S3 backend, grant the necessary bucket-level s3:ListBucket permission and object permissions for the state and .tflock file. Apply identities should be separate from plan-only identities.

  • Credentials: Use workload identity, such as GitHub OIDC with AWS IAM roles, instead of static access keys. Never commit credentials or provider credentials into HCL.

  • Secrets: Treat state, saved plans, plan artifacts, and CI logs as sensitive. Marking an input as sensitive only suppresses normal CLI output; it does not encrypt the value in state.

  • Drift: A normal plan includes refresh operations and detects out-of-band changes. Use terraform plan -refresh-only when diagnosing drift without proposing infrastructure changes.

  • Untrusted pull requests: Do not expose production state or broad cloud credentials to arbitrary fork pull requests. Use a sanitized plan or a trusted planning service where necessary.

Production Practices and Pitfalls

  • Protect the main branch, require production-infrastructure reviewers through CODEOWNERS, and make approvals apply to the final merge commit.

  • Store the plan artifact immutably, restrict its retention, record its digest, and verify that it corresponds to the approved merge commit before applying it.

  • Add policy checks for destructive operations, public exposure, encryption requirements, and unapproved regions.

  • Pin provider versions with required_providers, commit .terraform.lock.hcl, and test provider upgrades separately.

  • Distinguish a no-change plan from an execution error: terraform plan -detailed-exitcode returns 0 for no changes, 2 for changes, and 1 for an error.

  • Monitor failed applies, lock timeouts, stale plans, unexpected destroys, and state-restore events. Preserve CI logs and state revisions for incident analysis.

  • Use a documented break-glass procedure with separate approval and auditability instead of bypassing review silently.

  • OpenTofu 1.x can implement the same high-level review pattern with tofu commands, but backend options and locking behavior must be verified against the selected OpenTofu release.

57

What is HCP Terraform (formerly Terraform Cloud)?

HCP Terraform (formerly Terraform Cloud) is HashiCorp’s managed SaaS for running Terraform workflows (it does not run OpenTofu), storing remote state, and governing infrastructure changes. It centralizes execution, permissions, approvals, policy checks, and auditability without requiring teams to operate a remote-state backend themselves.

Read full answer

Applies toHCP Terraform (current SaaS offering) and Terraform Enterprise (current release), using currently supported Terraform 1.x releases.

How It Works

  • A run can originate from a connected VCS repository, the UI, API, CLI, or a schedule. VCS-driven runs clone the repository; CLI-driven runs upload a configuration archive.

  • Execution occurs in HCP Terraform’s isolated remote environment or on a configured agent. Agents poll for work, allowing private resources to be reached without inbound connectivity to the HCP control plane.

  • A normal run produces a plan before apply. Pull requests can generate speculative plans, while approval requirements and automatic-apply behavior depend on workspace and organization settings.

  • The configuration remains standard Terraform: providers, resources, data sources, variables, outputs, lifecycle rules, modules, CLI imports, and supported import blocks behave as they do elsewhere.

Core Capabilities

  • Remote state: Each workspace has a logical state snapshot with locking and version history. Other configurations can read it through the terraform_remote_state data source.

  • Workspaces: Workspace-scoped state, variables, VCS connections, execution settings, and access policies separate environments and teams.

  • Private registry: Teams can publish and consume private modules with semantic-version tags.

  • Governance: Sentinel and OPA policy sets can block noncompliant plans; run tasks integrate scanners and other tools around plan and apply stages.

  • Cost and drift analysis: Cost estimation supports major cloud providers, while scheduled drift and health assessments detect divergence and resource-health issues.

State and Security

  • State is encrypted in transit and at rest, with retention and available recovery operations governed by the service tier.

  • State frequently contains credentials and other sensitive values. Marking a variable sensitive hides it from normal UI output but does not remove it from state or provider configuration; prefer injecting secrets through a suitable secret-management mechanism.

  • Restoring an older state version is not an automatic undo of infrastructure changes. Treat restoration as a deliberate reconciliation: inspect the live environment, create a new state version as appropriate, and avoid blindly overwriting current state.

  • Organization, project, and workspace permissions support least-privilege access. SSO/SAML and audit logs strengthen identity and administrative controls, but audit logs should not expose sensitive variable values.

Deployment Models

Capability HCP Terraform Terraform Enterprise Local Terraform CLI
Hosting HashiCorp-managed SaaS Self-hosted installation Workstation or CI runner
Execution HCP remote or agent execution Enterprise or agent execution Local process
State Managed remote backend Self-hosted managed backend Local or backend-dependent
Governance Built-in RBAC, approvals, policies, and audit Comparable platform controls Requires external CI, policy, and access tooling
Private connectivity Agents available Agents available Depends on runner network access

Terraform Enterprise is appropriate when an organization requires self-hosted operation, disconnected deployment, or specific regulatory controls.

CI/CD, Testing, and Operations

  • Keep formatting, validation, and tests as CI gates before requesting a remote plan. For Terraform 1.6+, a typical sequence is terraform init -backend=false, terraform fmt -check -recursive, terraform validate, and terraform test when test files exist; HCP’s remote plan then provides an additional environment-specific check.

  • Developers can authenticate with terraform login. CI should instead provide a protected token such as TF_TOKEN_app_terraform_io, stored as a masked secret.

  • Review pull-request plans and enforce approvals and policy checks for production workspaces. Pin the Terraform version, provider versions, and the committed .terraform.lock.hcl before upgrading them.

  • Long operations can hit execution timeouts, and runs queue when the organization’s concurrency limit is reached. Agents improve network reachability but do not remove timeout limits; splitting large stacks is the more reliable remedy.

Production Best Practices and Pitfalls

  • Use VCS-driven workflows, separate workspaces per environment, and separate workspaces or configurations across account and trust boundaries.

  • Keep policies, approvals, and least-privilege permissions enabled for production; do not treat workspace separation as a substitute for cloud-account isolation.

  • Do not place secrets in outputs or expect sensitive variables to be absent from state.

  • Prefer importing existing infrastructure over recreating it, keep state focused by splitting large configurations, and review drift notifications and state-version history as part of incident response.

58

What is Atlantis for Terraform pull requests?

Atlantis is an open-source automation server that runs Terraform (and OpenTofu) plans and applies through pull request comments, turning infrastructure changes into a reviewable, auditable workflow instead of ad-hoc local runs.

Read full answer

Applies toAtlantis 0.x with Terraform 1.x / OpenTofu and a VCS provider (GitHub, GitLab, Bitbucket, Azure DevOps).

How It Works

  • A VCS webhook notifies Atlantis when a pull request is opened or updated.

  • Atlantis checks out the repository, runs terraform init and terraform plan, then posts the plan output as a PR comment.

  • A maintainer comments atlantis apply (or auto-apply is enabled) to execute the change; Atlantis runs terraform apply and reports the result back to the PR.

  • Atlantis acquires its own per-project and per-workspace lock to serialize concurrent runs, while Terraform’s backend lock still protects state during apply.

Key Features

  • Plan and apply driven entirely by PR comments, keeping an audit trail in version control.

  • Per-project and per-workspace locking to avoid concurrent modifications.

  • Support for multiple repositories and monorepos via atlantis.yaml.

  • Custom workflows with pre- and post-steps (linting, policy checks, notifications).

  • Policy enforcement through tools like Conftest/OPA before apply.

  • Apply requirements such as required approvals or successful status checks.

Security and State Safety

  • Validate VCS webhooks with a shared secret and restrict which users can trigger plans and applies.

  • Always use a remote state backend with locking and encryption (for example S3 with DynamoDB locking and KMS, or GCS); Atlantis itself does not store or encrypt state.

  • Because state can contain secrets, avoid committing .tfvars with credentials and prefer secret managers plus least-privilege execution roles (IRSA, Workload Identity, or instance profiles) instead of long-lived keys.

  • Gate applies behind PR approval and branch protection so unreviewed changes cannot reach production.

Production Considerations

  • Atlantis runs as a single instance by default and is not highly available; plan maintenance windows and run it on a managed platform (Kubernetes or a VM with restart policies).

  • It keeps working directories on disk, so provide persistent storage or accept re-cloning on restart; state itself lives in the backend.

  • Manual out-of-band changes cause drift; run periodic plans or use drift-detection tooling to catch them.

  • Pin Atlantis, Terraform, and provider versions, and test upgrades in a non-production environment first.

  • Export logs and metrics and alert on failed plans or applies.

Common Pitfalls

  • Allowing atlantis apply from anyone without approval requirements.

  • Granting the execution role broad cloud permissions instead of least privilege.

  • Disabling backend locking, which can corrupt state under concurrent runs.

  • Storing plaintext secrets in repository files or state without backend encryption.

Best Practices

  • Use remote state with locking and server-side encryption.

  • Require approvals and protected branches before apply.

  • Scope cloud credentials to the minimum needed per project.

  • Define projects explicitly in atlantis.yaml rather than relying on auto-detection in large repos.

  • Review plan output carefully, including resource replacements, before applying.

Approach Trigger Audit Trail Best For
Atlantis PR comments via VCS webhook Full PR history Self-hosted, GitOps-style teams
Terraform Cloud / Enterprise UI, API, VCS runs Platform-managed Managed SaaS, policy sets, remote runs
59

How should Terraform provider authentication work securely in CI?

Use workload identity federation so CI receives short-lived cloud credentials through OIDC instead of storing long-lived access keys. For AWS, the GitHub Actions OIDC token is exchanged for temporary AWS STS credentials, which the Terraform AWS provider uses automatically through environment variables.

Read full answer

Applies toTerraform 1.10+ and AWS provider 5.x

Preferred Authentication Model

  • OIDC federation: Preferred when the cloud provider supports it. The CI system proves its workload identity, and the cloud issues narrowly scoped, short-lived credentials.

  • Managed CI identities: Use platform-native identities such as GitHub Actions OIDC, GitLab workload identity, Azure managed identities, or Google Workload Identity.

  • Static access keys: Use only when federation is unavailable. Store them in the CI secret manager, restrict their IAM permissions, rotate them frequently, and never commit them.

  • Provider configuration: Keep credentials out of HCL, .tfvars, backend arguments, and Terraform state. The AWS provider normally discovers credentials from AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, and AWS_SESSION_TOKEN or from the configured AWS credential chain.

Provider API authorization and state-backend authorization are separate permission checks, even when the same OIDC role supplies credentials for both. Authentication can therefore succeed while terraform init fails because the role cannot read state or create the lock file.

How OIDC Works

  1. GitHub creates a signed OIDC JWT for the workflow because the job has id-token: write.

  2. The JWT identifies the repository, environment, branch, or workflow.

  3. The CI AWS action sends that token to AWS STS through AssumeRoleWithWebIdentity.

  4. AWS validates the token’s signature, audience, expiration, and trust-policy conditions.

  5. STS returns temporary AWS credentials that the AWS provider uses to sign API requests.

The IAM role trust policy should constrain both token.actions.githubusercontent.com:aud and token.actions.githubusercontent.com:sub. Avoid wildcard subjects because they allow unrelated workflows to request credentials.

State and Provider Boundaries

  • Remote state: Store state in an access-controlled S3 backend. Enable encryption, bucket versioning, and public-access blocking. Use S3 Object Lock or a Terraform prevent_destroy lifecycle rule where deletion protection is required.

  • Locking: Use S3 native lockfiles with Terraform 1.10+. The role needs narrowly scoped s3:PutObject and s3:DeleteObject permissions on the lock object, in addition to state-read permissions.

  • State secrets: Terraform state can contain resource secrets even when variables are marked sensitive; sensitive only suppresses CLI output. Avoid putting credentials in resource arguments and use an external secret manager where possible.

  • Drift: Run periodic terraform plan -refresh-only jobs and alert when the exit code is 2, indicating detected changes.

  • Plan review: Give the plan role read-only infrastructure permissions, but allow the required state-lock operations. Require protected environments and human approval before an apply role can modify infrastructure.

Failure Modes and Trade-offs

Failure mode Impact Mitigation
Incorrect OIDC subject or audience STS rejects the role assumption Match the GitHub environment or branch exactly in the trust policy
Missing backend permissions terraform init cannot read state or create the lock file Grant scoped S3 read and lock-object permissions
Overprivileged CI role A compromised workflow can modify production Separate plan and apply roles and scope state access
Static keys in repository settings Credential theft through source access or logs Migrate to OIDC and rotate exposed keys
Applying an untrusted plan artifact Arbitrary infrastructure changes may be applied Apply only trusted workflows and re-plan from the reviewed commit

Code Example

The Terraform configuration contains no credentials:

terraform {
  required_version = ">= 1.10.0, < 2.0.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }

  backend "s3" {
    bucket       = "example-terraform-state-123456789012"
    key          = "production/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    use_lockfile = true
  }
}

provider "aws" {
  region = "us-east-1"
}

data "aws_caller_identity" "current" {}

A GitHub Actions workflow can assume a short-lived role without storing AWS keys:

name: Terraform Plan

on:
  pull_request:
    branches: [main]

permissions:
  contents: read
  id-token: write

concurrency:
  group: terraform-plan-${{ github.ref }}
  cancel-in-progress: true

jobs:
  plan:
    runs-on: ubuntu-24.04
    environment: terraform-plan
    steps:
      - name: Check out repository
        uses: actions/checkout@v4

      - name: Configure AWS credentials with OIDC
        uses: aws-actions/configure-aws-credentials@v4
        with:
          role-to-assume: arn:aws:iam::123456789012:role/terraform-plan
          aws-region: us-east-1
          role-duration-seconds: 900
          role-session-name: terraform-plan-${{ github.run_id }}

      - name: Initialize Terraform
        run: terraform init -input=false

      - name: Create plan
        run: terraform plan -input=false -no-color

The corresponding IAM role trust policy can be constrained to the plan environment:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "Federated": "arn:aws:iam::123456789012:oidc-provider/token.actions.githubusercontent.com"
      },
      "Action": "sts:AssumeRoleWithWebIdentity",
      "Condition": {
        "StringEquals": {
          "token.actions.githubusercontent.com:aud": "sts.amazonaws.com",
          "token.actions.githubusercontent.com:sub": "repo:example-org/example-repo:environment:terraform-plan"
        }
      }
    }
  ]
}

Production Best Practices

  • Give the plan role read-only infrastructure permissions and only the state-read and lock-object permissions required by the S3 backend.

  • Give the apply role write permissions, but run it only from a protected environment after approval.

  • Do not print plans containing sensitive values or upload them to broadly accessible artifacts.

  • Use GitHub environment protection rules, least-privilege IAM conditions, audit logs, and CloudTrail events for role assumptions and infrastructure changes.

  • Monitor failed AssumeRoleWithWebIdentity calls, state-lock failures, drift, and unexpected apply activity.

  • Pin third-party CI actions to reviewed commit SHAs when supply-chain risk is significant.

  • Keep a documented break-glass process for credential or CI incidents, and regularly test the federation path.

60

How do you structure and operate large Terraform codebases?

Large Terraform codebases are managed through modular architecture and controlled state workflows: domain-specific root modules compose reusable modules, while remote state, locking, review, and testing protect production. The goal is to make changes small, repeatable, observable, and recoverable.

Read full answer

Applies toTerraform 1.10+ within 1.x and AWS provider 5.x; OpenTofu 1.8+ for equivalent workflows

Architecture and Module Boundaries

  • Root modules: Organize production code by ownership boundary, such as networking, databases, Kubernetes, and observability. Avoid creating a state file for every resource; split only when a component has a distinct owner, lifecycle, or access policy.

  • Child modules: Package reusable infrastructure with typed variables, validated inputs, and explicit outputs. Keep modules focused rather than creating one “infrastructure” module containing everything.

  • Provider configuration: Configure providers in root modules and pass them to child modules. Child modules should generally avoid hard-coded regions, account IDs, credentials, or backend settings.

  • Variables and data sources: Use variables for deployment-specific inputs and data sources for discovery. Validate CIDRs, names, and mutually exclusive settings before planning.

  • Version control: Commit HCL, module versions, and .terraform.lock.hcl. Pin external modules to released tags or commit hashes rather than moving branches.

State, Locking, and Secrets

  • Remote state: Store state outside the repository with encryption, versioning, restricted access, audit logging, and tested restoration procedures. The backend must exist before terraform init; it is not normally created by Terraform itself.

  • Locking: Use the S3 backend’s native use_lockfile = true for Terraform 1.10+. Locking prevents concurrent applies from corrupting state or applying conflicting changes.

  • Secrets: Do not commit credentials or place secret values in variables. Prefer workload identity and references to AWS Secrets Manager or SSM Parameter Store. Remember that sensitive values, provider arguments, and data-source results can still be recorded in state, so protect and audit the state backend accordingly.

  • Environment isolation: Use separate state keys, buckets, or accounts for production and other environments. Treat workspaces as temporary operational tools, not a substitute for deliberate environment separation.

  • Drift: Run terraform plan -refresh-only regularly. Investigates unexpected differences before reconciling them; do not routinely use refresh-only mode to conceal drift.

Plan, Apply, and Lifecycle

  • Lifecycle rules: Use prevent_destroy for critical databases, create_before_destroy where replacement ordering permits it, and ignore_changes sparingly because ignored fields can conceal operational mistakes.

  • Import: Terraform 1.5+ import blocks are preferable to the older terraform import command for adopting existing resources. Generate and review the resulting plan before applying.

  • Testing: Run formatting, validation, static analysis, and terraform test. Terraform tests can use mock providers to verify module behavior without creating real infrastructure.

  • CI/CD separation: Pull requests should run read-only plans; a protected deployment identity should perform applies. If plan and apply run in separate jobs, securely transfer the saved plan, use the same commit and Terraform version, and protect it because saved plans may contain sensitive values.

  • Change control: Require reviewed plans and prohibit unattended production applies. Database or networking changes should include rollback, backup, and recovery procedures rather than relying only on Terraform state.

Code Example

A minimal root module and reusable network module:

# main.tf
terraform {
  required_version = ">= 1.10, < 2.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }

  backend "s3" {
    bucket       = "company-terraform-state"
    key          = "production/network/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    use_lockfile = true
  }
}

provider "aws" {
  region = "us-east-1"
}

module "network" {
  source     = "./modules/network"
  name       = "production"
  vpc_cidr   = "10.0.0.0/16"
}

output "vpc_id" {
  value = module.network.vpc_id
}
# modules/network/main.tf
terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

variable "name" {
  type = string
}

variable "vpc_cidr" {
  type = string

  validation {
    condition     = can(cidrnetmask(var.vpc_cidr))
    error_message = "vpc_cidr must be a valid IPv4 CIDR."
  }
}

resource "aws_vpc" "this" {
  cidr_block = var.vpc_cidr

  tags = {
    Name = var.name
  }
}

output "vpc_id" {
  value = aws_vpc.this.id
}

Use the following delivery sequence:

terraform init -input=false
terraform fmt -recursive -check
terraform validate
terraform test
terraform plan -out=tfplan
terraform show tfplan
terraform apply tfplan

Production Practices and Pitfalls

  • Partial failures: A failed apply can leave resources created but not recorded correctly. Review state, provider logs, and tainted resources before retrying; never rerun a broad command without understanding the prior result.

  • Monitoring: Monitor Terraform pipeline duration, plan failures, drift, and infrastructure alarms. For AWS, retain CloudTrail events to identify changes made outside Terraform.

  • Backups and recovery: Enable backend versioning and periodically test state restoration. A state backup does not replace database snapshots or other workload backups.

  • Provider upgrades: Upgrade providers in a separate pull request, review generated plan changes carefully, and deploy first to non-production environments.

  • Common mistakes: Avoid hard-coded credentials, overly fragmented state, unreviewed ignore_changes, and automatic state migration during CI. OpenTofu can run much of this workflow with the tofu command, but release, provider, and backend compatibility should be validated separately.

61

How to split Terraform state files to reduce blast radius?

Splitting Terraform state means dividing infrastructure into separate state files (and often separate root modules) so a single terraform apply or a corrupted state file cannot take down unrelated resources. The goal is to limit the blast radius of mistakes, drift, and concurrent changes.

Read full answer

Applies toTerraform 1.x with AWS provider 5.x (concepts apply to OpenTofu 1.x as well).

Why Split State

A single monolithic state file couples unrelated resources: a typo in a VPC change can force a plan that touches databases, and a state lock or corruption blocks every team. Splitting state gives independent plan/apply cycles, separate permissions, and smaller, reviewable diffs.

Common Splitting Strategies

  • By lifecycle: network (rarely changes) vs compute (frequent) vs data (sensitive, slow).

  • By ownership/team: platform team owns networking, app teams own services.

  • By environment: separate state per dev, staging, prod (often separate accounts).

  • By component: vpc, eks, rds, dns each in its own directory.

How It Works in Practice

Each component is its own root module with its own backend configuration, typically in a directory like infra/network/ or infra/compute/. Cross-component references use terraform_remote_state data sources or, better, publish values via outputs consumed through a shared store (SSM Parameter Store, Consul, or a small “outputs” module).

State Safety Considerations

  • Remote backend per component: each state file lives in its own S3 key (or Terraform Cloud workspace) with locking enabled.

  • Locking: a single DynamoDB table can be shared across states because lock IDs are unique per state key; use separate tables only when you need stronger isolation or different IAM boundaries.

  • Secrets in state: split sensitive resources (RDS passwords, IAM keys) into a dedicated state with stricter access; mark outputs sensitive = true.

  • Drift: run terraform plan per component in CI; smaller states make drift detection faster and cheaper.

  • Plan review: smaller plans are reviewable; require approval per component.

Workspaces vs Separate Directories

Workspaces share one codebase and one backend config with different state keys — good for identical environments (dev/staging/prod of the same app). Separate directories with separate backends are better for genuinely different components or teams. Do not use workspaces to separate unrelated infrastructure; that recreates the monolith problem.

Code Example

# infra/network/main.tf
terraform {
  backend "s3" {
    bucket         = "example-tfstate"
    key            = "network/terraform.tfstate"
    region         = "us-east-1"
    dynamodb_table = "tf-locks"
    encrypt        = true
  }
}

# infra/compute/main.tf consumes network outputs
data "terraform_remote_state" "network" {
  backend = "s3"
  config = {
    bucket = "example-tfstate"
    key    = "network/terraform.tfstate"
    region = "us-east-1"
  }
}

resource "aws_instance" "app" {
  subnet_id = data.terraform_remote_state.network.outputs.private_subnet_id
}

Best Practices and Pitfalls

  • Prefer explicit dependencies over implicit coupling: terraform_remote_state creates tight coupling; prefer publishing values to SSM/Consul and reading them with data sources.

  • Keep state files small: aim for plans that finish in seconds, not minutes.

  • Version lock providers per component to avoid surprise upgrades.

  • Avoid cross-state cycles: never have two states reference each other’s outputs.

  • Migration path: use terraform state mv and terraform import when splitting an existing monolith; do it incrementally, one component at a time, with backups.

  • OpenTofu: same patterns apply; tofu state mv and tofu import work identically.

  • Pitfall: splitting too finely creates dozens of states that are hard to orchestrate; group by change frequency and ownership, not by resource type alone.

62

How do you use terraform_remote_state to read outputs?

terraform_remote_state is a data source that reads the output values of another Terraform configuration whose state is stored in a remote backend, letting stacks share values without duplicating resources.

Read full answer

Applies toTerraform 1.x with any supported remote backend (S3, GCS, Azure Blob, etc.); examples use AWS provider 5.x and S3.

How It Works

  • The data source points at a backend and a state key (and workspace, if applicable) belonging to the producing stack.

  • It exposes only that stack’s declared output values under data.terraform_remote_state.<name>.outputs.<output_name>.

  • It reads state at plan/apply time, so the producing stack must have been applied at least once and its outputs must exist.

  • It does not import or manage the remote resources; it only consumes their exported values.

Configuration

data "terraform_remote_state" "network" {
  backend = "s3"
  config = {
    bucket = "example-tf-state"
    key    = "network/terraform.tfstate"
    region = "us-east-1"
  }
}

resource "aws_instance" "app" {
  ami           = "ami-0123456789abcdef0"
  instance_type = "t3.micro"
  subnet_id     = data.terraform_remote_state.network.outputs.subnet_id
}

The producing stack must declare a matching output:

output "subnet_id" {
  value = aws_subnet.main.id
}

State Safety and Limitations

  • Secrets in state: Outputs containing secrets are still stored in plaintext in both state files. Mark them sensitive = true to redact CLI output, but prefer a secrets manager over remote state for credentials.

  • Coupling and ordering: Consumers depend on the producer’s output contract; renaming or removing an output breaks downstream plans. Treat outputs as a stable API.

  • Drift: If the producer changes, consumers must re-run terraform plan/apply to pick up new values; nothing propagates automatically.

  • Access control: Grant consumers read-only access to the state bucket/key; never give write access to another stack’s state.

  • Locking: Reading state does not modify it, but the backend must be reachable and credentials valid; keep the lock table (e.g., DynamoDB for S3) available.

  • Workspaces: If the producer uses workspaces, point the data source at the correct state key/workspace so you do not accidentally read the default workspace.

Code Example

Producing stack (network/main.tf):

resource "aws_vpc" "main" {
  cidr_block = "10.0.0.0/16"
}

resource "aws_subnet" "main" {
  vpc_id     = aws_vpc.main.id
  cidr_block = "10.0.1.0/24"
}

output "vpc_id" {
  value = aws_vpc.main.id
}

output "subnet_id" {
  value = aws_subnet.main.id
}

Consuming stack (app/main.tf):

data "terraform_remote_state" "network" {
  backend = "s3"
  config = {
    bucket = "example-tf-state"
    key    = "network/terraform.tfstate"
    region = "us-east-1"
  }
}

resource "aws_instance" "app" {
  ami           = "ami-0123456789abcdef0"
  instance_type = "t3.micro"
  subnet_id     = data.terraform_remote_state.network.outputs.subnet_id
}

Best Practices and Common Pitfalls

  • Prefer module composition within a single state when stacks are tightly coupled; reserve remote state for genuinely separate lifecycle boundaries.

  • Version the state key path (e.g., network/v1/terraform.tfstate) when making breaking output changes.

  • Run terraform plan in consumers after any producer change to catch contract breaks early in CI.

  • Enable encryption at rest and in transit for the state bucket; restrict access with IAM least privilege.

  • Avoid exposing secrets via outputs; use a secrets manager and pass references instead.

  • OpenTofu supports the same terraform_remote_state data source, so cross-tool consumption works where state formats are compatible.

63

What alternatives replace terraform_remote_state for sharing infrastructure data?

Alternative data-sharing mechanisms can replace terraform_remote_state when a stack needs values owned by another system. The best choice depends on whether the source of truth is live infrastructure, an external service, a CI/CD contract, or another Terraform root module.

Read full answer

Applies toTerraform 1.x with AWS provider 5.x; OpenTofu 1.x with compatible provider versions

Main alternatives

Mechanism Source of truth Dependency tracking Typical use
Provider data source Live provider API Terraform tracks the data source VPCs, subnets, IAM roles, images, and other cloud resources
Built-in http data source HTTP API response Terraform tracks the data source Internal APIs that expose read-only configuration
external data source Local program using a CLI or API Terraform tracks the result Systems without a dedicated provider or HTTP integration
CI/CD output contract Outputs from an upstream pipeline Managed by the pipeline Passing non-sensitive values between independently deployed stacks
Terraform module Inputs and outputs in the module interface Native Terraform dependency graph Reusing infrastructure definitions under shared ownership

terraform_remote_state remains appropriate when the value is a Terraform-managed output and the consuming stack should react to changes recorded in another state. It reads outputs from a state backend; it does not copy or manage the resources represented by that state.

Provider-native and HTTP data sources

Provider data sources query a provider’s live API instead of reading another Terraform state. For example, an AWS data source can discover a VPC by name, ID, tags, or other supported attributes. This removes coupling to the producer’s state layout, but the consuming identity needs the relevant read permissions.

The built-in http data source can retrieve information directly from an HTTP endpoint. It is useful for internal read-only APIs, although production implementations should address authentication, TLS validation, timeouts, retries, pagination, and response validation. Sensitive values should not be requested through this mechanism because HTTP response data can be persisted in state.

Provider-backed discovery has an important semantic difference: it reflects current infrastructure, not necessarily the configuration last applied by the upstream stack.

External programs and custom integrations

The built-in external data source executes a local program and expects a JSON object whose values are strings. The program runs during planning when its inputs are known, or during apply when a dependency is still unknown.

It is appropriate for retrieving values through an internal CLI or API that has no dedicated provider integration. Treat the program as executable deployment code:

  • Use workload identity or a narrowly scoped CI role for API access.

  • Make the program deterministic and return a nonzero status when the source is unavailable.

  • Validate and normalize the returned value.

  • Do not use it for secret values: the protocol transmits the value through standard output, and Terraform persists data-source results in state.

Custom providers can provide a stronger typed interface for internal platforms, while ordinary API clients or scripts can implement simpler one-off integrations.

CI/CD and module contracts

For independently deployed stacks, CI/CD can pass non-sensitive values from an upstream job to a downstream job. The upstream stack exposes an output, and the pipeline reads it explicitly, validates it, and supplies it as a downstream input. terraform output -raw is suitable for one string output, while terraform output -json supports multiple outputs but may expose sensitive values and must be handled as sensitive.

CI/CD contracts are explicit and auditable, but they do not create Terraform’s dependency graph. A downstream pipeline must deliberately fetch the current input when it needs to detect an upstream change.

Modules are preferable when the configurations share ownership and a release lifecycle. Pass values through typed module variables and expose only required values as module outputs. This creates an explicit interface without shared mutable state.

Production safety and failure modes

  • State safety: If terraform_remote_state remains necessary, use an encrypted, versioned remote backend with its supported locking mechanism and restrict read access. The consuming configuration must use a compatible backend configuration and identify the same state object as the producer; it need not duplicate every producer setting.

  • Secrets: Remote state, data-source results, plan files, and CI artifacts can contain secrets. Prefer a secret manager and runtime injection rather than passing secret values through infrastructure outputs.

  • Drift: Provider data sources reflect live infrastructure, remote state reflects recorded outputs, and CI contracts reflect the last transferred deployment output. These sources can disagree, so teams must define which one is authoritative.

  • Failure behavior: APIs can be throttled or unavailable, and external programs can fail because of credentials, networking, or invalid responses. CI should stop before applying an incomplete plan and retry only operations known to be safe.

  • Reviewability: Review terraform plan output before approval, confirming the selected resource or endpoint, input values, permissions, and any detected drift.

  • OpenTofu: OpenTofu supports similar backend and data-source patterns, but exact provider compatibility and behavior must be checked against the OpenTofu and provider versions in use.

64

How do you safely upgrade Terraform and provider versions?

Safe upgrades combine version pinning, reproducible dependency resolution, isolated validation, and reviewed plans. Upgrade Terraform core and providers separately so that compatibility failures and infrastructure changes can be attributed and rolled back independently.

Read full answer

Applies toTerraform 1.11.0 and later 1.x releases, OpenTofu 1.x, AWS provider 5.x

Upgrade Model

  • Terraform core: Install an exact CLI version in CI, such as through hashicorp/setup-terraform@v3 with terraform_version. The required_version constraint is a compatibility check, not an exact pin.

  • Providers: required_providers specifies acceptable ranges, while .terraform.lock.hcl records exact versions and checksums. Commit the lock file and review every lock-file change.

  • A constraint such as ~> 5.40 permits >= 5.40.0, < 6.0.0; it does not select or pin one provider release.

  • Read both the Terraform changelog and provider release notes before changing versions. Provider upgrades may add arguments, deprecate fields, change defaults, or modify persisted state.

Safe Upgrade Procedure

  1. Record terraform version, terraform providers, the current lock file, and the backend location.

  2. Upgrade the core binary alone, run terraform init, and validate the configuration and state locally.

  3. Change only the intended provider constraint. Run terraform init -upgrade, then inspect the lock-file diff because it can update multiple providers whose constraints permit newer releases.

  4. Test with terraform test and run terraform plan against an isolated backend or state copy with representative variables. A staging workspace must not point at production state.

  5. Save a plan, require human approval, and apply that exact saved plan.

  6. Monitor provider logs, API errors, resource health, and subsequent drift immediately after production application.

Do not automatically bump the core and providers and apply them together in CI. If a provider upgrade modifies state during the apply, simply reinstalling the old provider may not reverse that migration.

State, Drift, and Security

  • Use an encrypted remote backend with locking. On Terraform 1.11 and later, the S3 backend supports native locking with use_lockfile = true; DynamoDB locking remains available for compatibility with older configurations.

  • Enable versioning for the state bucket and protect backend credentials with narrowly scoped IAM permissions. A newly installed provider may also require additional IAM permissions.

  • State can contain passwords, tokens, private keys, and sensitive outputs. sensitive = true masks CLI output but does not remove the value from state.

  • Prefer encrypted backend snapshots for backups. If a local copy is required, create it with restrictive permissions:

set -euo pipefail
umask 077
terraform state pull > backup.tfstate
  • Saved plans can also contain sensitive values. Store tfplan and rendered plan output in an access-controlled artifact store, and delete them according to policy.

  • Use terraform plan -refresh-only to investigate drift separately from intended configuration changes.

OpenTofu Compatibility

OpenTofu follows the same pinning, lock-file, reviewed-plan, and remote-locking principles, but it is not a drop-in replacement for every Terraform 1.x feature. Verify the corresponding OpenTofu release, configuration-language features, provider registry source, and lock-file behavior. Do not let Terraform and OpenTofu write the same state concurrently, and test any cross-tool state migration first.

Code Example

terraform {
  required_version = ">= 1.11.0, < 2.0.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.40"
    }
  }

  backend "s3" {
    bucket       = "example-tf-state"
    key          = "prod/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    use_lockfile = true
  }
}

Use the provider lock command when a targeted provider update is required, then initialize from the reviewed lock file:

set -euo pipefail
terraform version
terraform providers lock -platform=linux_amd64 hashicorp/aws
terraform init
terraform plan -out=tfplan
terraform show -no-color tfplan

After review and approval, apply the same plan:

terraform apply tfplan

Production Practices and Pitfalls

  • Pin the exact Terraform binary in CI and commit the provider lock file.

  • Review plan and lock-file diffs as separate approval artifacts.

  • Back up state, verify drift, and confirm rollback procedures before production upgrades.

  • Never use terraform state rm as a substitute for a planned migration; prefer moved blocks, import blocks, or provider-supported migration procedures.

  • Treat backup files, saved plans, CI logs, and state as sensitive data, and retain them only according to operational and incident-response policies.

65

What role does .terraform.lock.hcl play in Terraform dependency management?

.terraform.lock.hcl is Terraform’s dependency lock file. It records the exact provider versions selected during initialization, together with cryptographic checksums that allow Terraform to detect changes to provider packages.

Read full answer

Applies toTerraform 1.x and OpenTofu 1.x

How It Works

  • Required provider constraints: The configuration’s required_providers blocks define acceptable provider versions. These are constraints, not exact selections.

  • Version selection: During terraform init, Terraform chooses a provider version satisfying those constraints and writes the selection to .terraform.lock.hcl.

  • Subsequent initialization: Later terraform init runs prefer the locked provider version, provided it still satisfies the configuration. A newer available version is not selected automatically.

  • Integrity verification: Terraform compares downloaded provider packages against the checksums recorded in the lock file. A registry package that does not match an expected checksum causes initialization to fail.

  • Upgrades: terraform init -upgrade selects the newest permitted provider version and updates the lock file. If changed constraints exclude the locked version, normal initialization selects a compatible replacement.

The lock file applies to provider dependencies, including providers required by child modules. It does not lock Terraform CLI versions, module source revisions, infrastructure resources, or application dependencies.

What the File Contains

For each provider, the file records:

  • Provider source address: The fully qualified registry address, such as registry.terraform.io/hashicorp/aws.

  • Selected version: The exact provider version installed, such as 5.100.0.

  • Constraints: The version restrictions inherited from the configuration.

  • Hashes: Checksums used to verify provider package contents. Terraform can record h1: package-content hashes and zh: archive hashes.

The file contains dependency metadata rather than provider credentials or the infrastructure configuration itself. Nevertheless, it should be reviewed like other supply-chain artifacts because an attacker able to modify it might authorize a different package.

Production Workflow

The normal workflow is:

  1. Commit the configuration, including provider version constraints, to version control.

  2. Run terraform init locally or in CI.

  3. Commit the resulting .terraform.lock.hcl alongside the configuration.

  4. Review lock-file and provider-version changes during pull requests.

  5. Use terraform init -lockfile=readonly in CI to prevent silent dependency changes.

Additional checksums can be recorded for other supported platforms with commands such as terraform providers lock -platform=linux_amd64 -platform=darwin_arm64. A CI workflow can initialize with the committed lock file, create a saved plan with terraform plan -out=tfplan, and apply that exact plan with terraform apply tfplan. Saved plan files can contain sensitive values and must be protected and deleted securely.

The lock file is not Terraform state and provides no protection for state data. Production state should still use a remote backend with locking enabled, encryption, restrictive access controls, versioning, and tested recovery procedures. Provider credentials and infrastructure secrets are not normally stored in the lock file, but sensitive values can exist in Terraform state; use secure state storage and sensitive-output handling accordingly.

Security and Failure Modes

  • Checksum mismatch: Treat this as a failed integrity check. Verify the registry, mirror, network path, and provider package before changing the lock file; do not delete it merely to bypass the error.

  • Unexpected provider update: Inspect changes to .terraform.lock.hcl and required_providers during plan and pull-request review.

  • Backend locking is separate: Provider locking prevents dependency substitution; it does not prevent concurrent Terraform runs from corrupting remote state.

  • Drift detection: Run and review terraform plan regularly. The lock file does not detect infrastructure drift.

  • Manual editing: Avoid hand-editing checksums or version selections. Let Terraform update the file through supported commands.

  • OpenTofu compatibility: OpenTofu uses the same lock-file filename and a compatible HCL structure. Use tofu init and validate lock-file behavior when migrating, particularly if providers come from custom mirrors.

66

What happens when two engineers run Terraform apply concurrently?

State locking serializes Terraform operations that access the same state. When two engineers run terraform apply concurrently against the same workspace, one process acquires the lock and the other normally fails immediately with a lock-acquisition error; with -lock-timeout, the second process waits and proceeds only if the lock becomes available and its plan remains valid.

Read full answer

Applies toTerraform 1.10+; OpenTofu 1.x where noted

Concurrent Apply Behavior

  • Lock acquisition: Terraform asks the backend for an exclusive lock before accessing state that may be modified.

  • Default behavior: The default lock timeout is zero, so a competing command normally fails rather than waiting. The error is commonly reported as Error acquiring the state lock.

  • Configured wait: A command using -lock-timeout=5m can retry lock acquisition for up to five minutes. If the first operation finishes and releases the lock, the waiting operation can continue.

  • Plan freshness: A direct terraform apply refreshes and plans against the state obtained under the lock. A separately saved plan is different: terraform plan releases its lock when planning ends, and the later terraform apply tfplan reacquires the lock and verifies that the plan is still valid. If another apply changed state, Terraform rejects the saved plan as stale rather than silently replanning it.

  • Normal release: Terraform normally releases the lock after success or a handled failure. A process crash or forced termination can leave a stale lock.

Backend and State Scope

State locking is provided by the Terraform backend, not by the AWS provider.

Backend or option Concurrency behavior
S3 with use_lockfile = true Uses an S3 lock file to coordinate access; this native mechanism requires Terraform 1.10 or later
Terraform Cloud Provides remote state locking; workspace run concurrency is also governed by its concurrency settings
Local state Uses .terraform.tfstate.lock.info to coordinate processes sharing the same local state path, but is unsuitable for a multi-machine team
-lock=false Bypasses locking and is unsafe for production

The lock coordinates operations using the same backend and state workspace. It does not prevent console changes, changes made by another automation system, or operations in different workspaces from modifying the same underlying cloud resources.

Production Workflow

  • Use a shared remote backend that supports locking and restrict access to the smallest practical set of administrators and CI identities.

  • Protect state with encryption in transit and at rest, audit backend access, and enable state versioning where the backend supports it so previous versions remain recoverable.

  • State can contain database passwords, API tokens, private keys, and other secrets. Marking a variable as sensitive only redacts it from normal CLI output; it does not remove it from state.

  • Review saved plans before approval, especially for replacement, destruction, IAM changes, and changes to data stores.

  • Serialize Terraform jobs for the same state using a CI pipeline concurrency group, or use -lock-timeout=0s so a competing job fails fast instead of acting on stale assumptions.

  • Never use -lock=false to bypass a lock in production. Investigate the lock owner and the underlying operation instead.

Failure Modes and Recovery

  • Stale lock after a crash: Verify that no Terraform operation is still running, inspect backend audit information, and confirm that the recorded owner is no longer active before using terraform force-unlock.

  • Partial apply: A provider or cloud API failure can leave some resources created or changed. Terraform does not provide an automatic rollback; reconcile state with the cloud provider before retrying.

  • Resource drift: Use terraform plan -refresh-only to inspect out-of-band changes and terraform plan -detailed-exitcode for automated drift detection.

  • Overlapping workspaces: Separate workspaces are not isolated if they manage the same cloud resources. Establish explicit ownership boundaries.

  • State recovery: Preserve restorable state versions before destructive operations and Terraform or provider upgrades, then test recovery procedures rather than assuming versioning alone is sufficient.

OpenTofu and Version Notes

OpenTofu follows the same fundamental locking principle, but backend features and option names can differ between releases. Verify the backend documentation for the exact OpenTofu release before enabling native lock files or relying on a particular timeout or recovery command.

67

What happens when a Terraform apply fails halfway?

A Terraform apply is not atomic across resources. If it fails partway through, Terraform leaves successfully completed changes in place, records the partial result in state, exits with a nonzero status, and normally does not automatically roll back.

Read full answer

Applies toTerraform 1.x with remote-state backends; AWS provider 5.x where applicable

What Terraform Retains

Terraform executes the configuration’s dependency graph, potentially running independent resources in parallel. Each dependency relationship controls ordering; it does not create a transaction spanning multiple resources.

If an operation fails:

  • Completed resources remain: Earlier creations, updates, or deletions are not reversed.

  • Partial state is saved: Terraform records what it believes exists, including resources that failed during creation when applicable.

  • Downstream work is skipped: Resources that depend on the failed operation generally are not applied.

  • Parallel work may finish: Operations already running can complete after another branch reports an error.

  • The command exits unsuccessfully: CI/CD systems can detect the failure through the exit code and Terraform output.

Terraform also cannot reverse side effects that occurred outside its resource model, such as data written by a failed local-exec or remote-exec provisioner.

Why Automatic Rollback Does Not Occur

Cloud APIs and infrastructure providers generally do not offer a transaction that atomically rolls back an arbitrary set of changes. Even deleting a newly created resource can itself fail because of quotas, dependencies, IAM permissions, or provider errors.

Terraform therefore follows a converge toward desired state model rather than a rollback model. After a failure, the next operation is usually another plan based on the partially updated state.

A failed resource may be marked tainted, especially when creation only partially succeeded. On the next plan, Terraform normally proposes replacing a tainted resource, subject to refresh behavior and provider-recorded attributes.

Safe Recovery Workflow

First inspect the failed apply’s output and recorded state. Run terraform show to display the latest state snapshot, terraform state list to list resources Terraform believes it manages, and terraform state show ADDRESS to inspect one resource.

Then generate and review a new plan. With normal refresh enabled, terraform plan -out=tfplan saves the plan, and terraform show tfplan presents it for review. Apply that exact reviewed plan with terraform apply tfplan.

A new plan compares refreshed remote reality with the configuration, so check it carefully for unexpected replacement, recreation, or destruction.

If a successfully created external object exists remotely but was not tracked by the provider, import it instead of creating a duplicate; for an AWS instance, for example, use terraform import aws_instance.example i-0123456789abcdef0. Import requires the remote object to exist. If the object no longer exists, a refreshed plan will normally detect its absence and propose recreating it.

Do not manually edit state files. Use controlled Terraform state commands when reconciliation is necessary, and document any manual intervention.

State and Operational Safety

For production infrastructure:

  • Use a remote backend with locking, encryption, access controls, versioning, and backups.

  • Never rely on local state for production; each team or environment needs controlled state isolation.

  • Expect secrets in state. Provider arguments, generated values, and provisioner inputs may appear there even when variables are marked sensitive.

  • Keep credentials out of Terraform configuration and environment files committed to source control. Prefer workload identity or narrowly scoped, short-lived credentials.

  • Review plans rather than automatically approving every difference. A failed apply’s next plan should be checked for unexpected replacement or destruction.

  • Monitor provider logs, cloud audit events, resource health, quotas, and billing after partial failures.

  • During an incident, stop parallel automation that could modify the same state while operators investigate.

Saved plan files can also contain sensitive values, so treat them as confidential artifacts and delete them according to the CI/CD retention policy.

Workspaces, Modules, and OpenTofu

Workspaces are not rollback mechanisms: they select different state, not different versions of infrastructure, and switching workspaces does not undo an apply. Likewise, module boundaries do not provide transactional isolation.

OpenTofu follows similar partial-apply and state-management semantics. Use the corresponding OpenTofu CLI and backend procedures, and follow the same rule: inspect the recorded state, refresh reality, review a new plan, and apply incrementally rather than expecting rollback.

68

How do you recover corrupted or lost Terraform state?

State recovery means restoring a trusted backend snapshot, or rebuilding state with import when the infrastructure still exists. Deleting state and running terraform apply is unsafe because it can propose creating resources that already exist.

Read full answer

Applies toTerraform 1.10+; OpenTofu 1.x; AWS provider 5.x examples

How State Failure Manifests

Terraform state records resource identities, attributes, dependencies, and provider metadata. It also contains:

  • Serial: an integer incremented when state changes.

  • Lineage: identifies the state’s history and prevents incompatible state from being accepted accidentally.

  • Resource addresses: map configuration addresses to real infrastructure IDs.

Corruption can be physical, such as invalid JSON, or logical, such as missing resources, incorrect dependencies, or invalid lineage. During terraform plan, Terraform combines configuration, state, and current provider API responses. Restoring an older snapshot can therefore introduce drift that must be reviewed before applying a normal plan.

Recovery Strategy

Situation Recovery approach Important caution
Local state was deleted; remote backend is intact Run terraform init; Terraform retrieves the authoritative remote state Do not push a local empty state over the remote state
Remote state parses but is incorrect Restore a known-good object version with terraform state push -force Compare lineage and serial first
Remote state is unparseable but versioned Download a known-good version, quarantine the corrupt live key while writers are stopped, then push the recovered state state push may not be able to load an unparseable current state
Local backend only Recover terraform.tfstate or terraform.tfstate.backup Validate the file before using it
Remote state and backups are lost Import existing infrastructure into a new state Never apply the original configuration as if nothing existed
Backend retains historical versions Download a historical state version and review it before restoring Not every backend provides version history

Pause CI/CD deployments and other Terraform writers during recovery. Backend locking prevents concurrent Terraform operations, but it does not protect against out-of-band writes performed directly through cloud APIs.

Rebuilding State with Imports

If no trustworthy snapshot exists, treat the situation as lost state rather than a configuration problem. Declare each existing resource in configuration and import it using the provider-specific ID:

terraform import 'aws_instance.web[0]' 'i-0123456789abcdef0'
terraform plan

Importing records an existing object in state without recreating it. Repeat this for every resource that is missing from the new state. Terraform 1.5+ also supports import blocks, making larger migrations repeatable and reviewable.

Some resource types do not support import. For those, investigate provider-specific import tooling or redesign the configuration around importable resources rather than manually editing state.

Code Example

Initialize the correct backend and workspace, then preserve the current state if it is readable:

terraform init
terraform workspace show

if terraform state pull > current.tfstate; then
  chmod 600 current.tfstate
else
  rm -f current.tfstate
fi

For an S3 backend with object versioning, list and retrieve a candidate version:

aws s3api list-object-versions \
  --bucket acme-terraform-state \
  --prefix prod/terraform.tfstate

VERSION_ID="replace-with-a-known-good-version-id"

aws s3api get-object \
  --bucket acme-terraform-state \
  --key prod/terraform.tfstate \
  --version-id "$VERSION_ID" \
  recovered.tfstate

chmod 600 recovered.tfstate

Select a non-delete-marker version corresponding to a known-good deployment. Validate and inspect it:

terraform show -json recovered.tfstate >/dev/null

jq '{
  version,
  terraform_version,
  serial,
  lineage,
  resource_count: ((.resources // []) | length)
}' recovered.tfstate

If the current remote state is parseable, restore it through Terraform so the backend lock and state safeguards are used:

terraform state push -force recovered.tfstate
terraform state list

Use -force only for an intentional restore of an older or incompatible-lineage snapshot. It bypasses normal serial and lineage protections.

If the current remote state is unparseable, terraform state push may fail while loading it. After stopping every writer and verifying the exact backend key, quarantine the corrupt object and then push under Terraform’s backend lock:

aws s3api delete-object \
  --bucket acme-terraform-state \
  --key prod/terraform.tfstate

terraform state push -force recovered.tfstate

On a versioned bucket, deletion creates a delete marker while retaining the previous object versions. Direct object overwrites should not be used while other writers are active.

Next reconcile the restored state with current infrastructure:

terraform plan -refresh-only -out=refresh.tfplan
terraform apply refresh.tfplan
terraform plan

A refresh-only plan updates state without intentionally changing remote infrastructure. Review the normal plan afterward for drift or resources missing from the restored state.

For OpenTofu 1.x, use the equivalent tofu init, tofu state pull, tofu state push, and planning commands. Confirm state compatibility before moving state between Terraform and OpenTofu.

Production Best Practices

  • Remote state: Use an encrypted remote backend with versioning, retention, restricted IAM access, and backend-native locking.

  • Backups: Test restoration periodically; versioning alone does not guarantee that a recoverable version exists.

  • Secrets: State may contain sensitive values even when outputs are marked sensitive. Store secrets in a dedicated secret manager and reference them rather than embedding credentials in configuration.

  • CI/CD: Serialize plans and applies, prevent concurrent deployments, require reviewed plans, and pause automation during state incidents.

  • Drift: Compare backups, live resources, and the latest plan before applying changes.

  • Workspace safety: Verify terraform workspace show and the backend key before pushing state; restoring into the wrong workspace can overwrite unrelated state.

  • Monitoring: Alert on backend operation failures, unexpected state serial changes, lock contention, and failed refreshes.

69

How do you debug Terraform plans and applies with TF_LOG?

TF_LOG controls Terraform’s diagnostic logging. Use DEBUG for the first investigation and TRACE only for a small, reproducible failure because higher levels can produce very large logs containing credentials, tokens, request bodies, and other sensitive data.

Read full answer

Applies toTerraform 1.x and AWS provider 5.x

How TF_LOG Works

Terraform runs providers as separate go-plugin subprocesses. Providers inherit the parent environment, while Terraform captures plugin output and prefixes it with the source and severity.

Level Typical use Typical output
TRACE Reproducing a provider bug Core internals plus provider-specific trace messages; potentially enormous
DEBUG First-pass investigation Graph and state operations, plugin discovery, request metadata, and retries
INFO High-level diagnostics Initialization, graph, and plugin lifecycle messages
WARN Warning triage Deprecations and recoverable provider issues
ERROR Failure triage Error-level diagnostics

Levels are cumulative, so DEBUG includes INFO and WARN. With TF_LOG unset, no TF_LOG diagnostics are produced. TF_LOG=JSON is a special mode that writes JSON-formatted logs rather than selecting another severity.

Scoping and Capturing Logs

  • TF_LOG_CORE: Controls Terraform Core diagnostics such as graph execution and state operations.

  • TF_LOG_PROVIDER: Controls provider-plugin diagnostics and is often more useful than core TRACE.

  • TF_LOG_SDK: Controls logging from providers built with the Terraform Plugin SDK.

  • TF_LOG_SDK_PROTO: Enables SDK protocol logging, including HTTP request and response bodies for SDK-based providers. It can expose secrets in clear text.

  • TF_LOG_PATH: Writes logs to a file instead of standard error.

  • TF_LOG_APPEND: Set it to true to append to an existing TF_LOG_PATH file rather than overwrite it.

OpenTofu 1.x supports TF_LOG and TF_LOG_PATH; use its tofu command in place of terraform.

Code Example

#!/usr/bin/env bash
set -euo pipefail

# Keep core diagnostics at INFO while increasing provider detail.
export TF_LOG_CORE=INFO
export TF_LOG_PROVIDER=DEBUG
export TF_LOG_PATH="/tmp/tf-debug-$(date +%s).log"

# Generate a saved plan and inspect its non-no-op resource changes.
terraform plan -out=tfplan
terraform show -json tfplan |
  jq '.resource_changes[] | select(.change.actions != ["no-op"])'

# After separate human review, apply the exact saved plan:
# terraform apply tfplan

The same environment variables instrument terraform apply; apply only a reviewed saved plan. The plan file and terraform show -json output can contain sensitive values, so protect them like state.

Reading Common Failure Modes

  • Schema or version errors: Check the provider constraint and lock file. Run terraform init -upgrade only after reviewing the intended provider upgrade.

  • Authentication errors: Messages such as NoCredentialProviders, InvalidClientTokenId, or ExpiredToken usually indicate an invalid profile, role-assumption chain, or expired credentials.

  • Throttling: RequestLimitExceeded or retry messages generally indicate service-side throttling or quota exhaustion. Missing IAM permissions normally appear as AccessDenied.

  • Lock timeouts: Determine which process holds the state lock before considering lock removal.

  • Provider panics: Capture the provider version, Terraform version, configuration, and sanitized trace when reporting an upstream defect.

  • State errors: Version messages can reflect an older state format, while checksum mismatches can indicate corruption or external modification. Stop and compare versioned backups rather than editing state directly.

Security and State Safety

  • sensitive = true redacts values from normal CLI output, but state, saved plans, and verbose logs can contain their underlying values. Scrub logs before attaching them to tickets.

  • Store state in an encrypted remote backend such as S3 with SSE-KMS, versioning, and a restrictive bucket policy.

  • Use S3 native locking with use_lockfile = true on Terraform 1.10 and later. DynamoDB locking remains available for older configurations, but dynamodb_table is deprecated from Terraform 1.11.

  • Never publish TRACE logs or state publicly, and never commit them to Git.

Best Practices for CI/CD

  • Run CI with TF_LOG=INFO and TF_LOG_PATH; retain logs only on failure with appropriate access controls and retention limits.

  • Generate a saved plan, review it, and run terraform apply tfplan; do not apply an unreviewed plan with -auto-approve.

  • Use terraform plan -refresh-only -detailed-exitcode for scheduled drift checks. Exit code 0 means no changes, 1 means changes or drift were found, and 2 means an error occurred.

  • Use terraform test with .tftest.hcl files for focused module regression tests, escalating to TRACE only in a disposable environment.

70

What are the most common Terraform anti-patterns?

The most common Terraform anti-patterns are hard-coded configuration, duplicated resources, unsafe state management, exposed secrets, unreviewed applies, ignored drift, and overly broad lifecycle rules. These practices reduce reproducibility and can lead to outages, state corruption, or credential exposure.

Read full answer

Applies toTerraform 1.x with AWS provider 5.x; OpenTofu 1.x compatibility caveats noted

Common Anti-Patterns

Anti-pattern Why it causes problems Safer alternative
Hard-coded account IDs, regions, CIDRs, and sizes Promotes environment-specific code and accidental changes Use typed variables, validation, and environment-specific variable files
Copying similar resources Creates configuration drift and duplicated maintenance Use count for known instances or for_each for keyed resources
One enormous root configuration Makes reviews difficult and increases blast radius Split reusable infrastructure into versioned modules
Unpinned providers or module versions Builds can change unexpectedly when remote versions change Commit .terraform.lock.hcl and pin module source versions
Local state on a workstation Loses history, lacks shared locking, and exposes infrastructure data Use a durable remote backend with encryption and locking
Secrets in variables, outputs, or resource arguments Values are commonly persisted in state or CI logs Store secrets in a secret manager and inject short-lived credentials
Running terraform apply without review Applies unknown or destructive changes directly to production Generate a saved plan, inspect it, obtain approval, then apply it
Changing infrastructure manually Terraform state becomes inaccurate and future applies may overwrite changes Reconcile deliberately through import, refresh, or a reviewed apply
Using count for resources whose membership changes Removing one item can renumber unrelated resources and recreate them Prefer stable for_each keys
Broad ignore_changes Permanently hides real configuration drift Ignore only attributes that another system legitimately owns
Excessive depends_on Hides real dependencies and can expand update scope Model references through expressions so Terraform infers dependencies
Provisioners for routine configuration Shell operations are hard to review, track, and repeat reliably Prefer provider-native configuration or immutable deployment pipelines

State and Secret Safety

Treat remote state as a production database: it records resource identities, attributes, dependencies, and sometimes secret values. Marking an output or variable sensitive only controls Terraform’s normal display behavior; it does not remove the value from state.

  • Use remote state with encryption at rest, TLS, versioning, retention, and regular backups.

  • Enable backend locking so concurrent applies cannot corrupt state. Locking prevents races, but it does not make an unsafe plan safe.

  • Separate states by environment, account, region, or ownership boundary when access should differ.

  • Restrict state access with least-privilege IAM and audit downloads.

  • Never commit terraform.tfstate, state backups, .terraform/, or saved plan files to source control.

  • Do not assume state backups replace application-data backups. Database backups, object retention, and recovery testing remain separate responsibilities.

Drift, Lifecycle, and Existing Infrastructure

Manual console edits, external controllers, and provider-side defaults can cause drift. A normal plan refreshes provider data and proposes reconciliation; it does not automatically repair the remote system. Use terraform plan -refresh-only to review detected differences before updating state.

Import existing infrastructure before managing it. Terraform 1.5+ also supports configuration-driven import blocks, while the terraform import command remains available. Importing avoids Terraform attempting to create duplicate resources.

Use prevent_destroy selectively to block explicit destroy operations, and use create_before_destroy only when replacement ordering is required. prevent_destroy can complicate emergency teardown and migrations, while create_before_destroy can increase cost and create dependency cycles. Test replacements against production-like data because replacement may recreate databases, disks, or load balancers.

CI/CD and Testing

A production pipeline should use short-lived credentials—preferably OIDC—and separate plan and apply permissions. A typical sequence is terraform init with backend configuration supplied securely, followed by:

  1. terraform fmt -check -recursive

  2. terraform validate

  3. terraform plan -lock-timeout=5m -out=tfplan

  4. terraform show -no-color tfplan

  5. Approval against the exact reviewed plan

  6. terraform apply tfplan

Saved plans may contain sensitive data, so protect them like state. The apply job should use the same backend and locking configuration as the plan job. Run terraform test for module-level assertions; it requires Terraform 1.6+, while mock providers require Terraform 1.7+. Tests complement, rather than replace, a reviewed production plan. Schedule periodic read-only drift plans and monitor failed applies, lock timeouts, and unexpected resource replacements.

Modules, Workspaces, and OpenTofu

Keep provider configuration in the root module. Child modules should declare required_providers, accept explicit inputs, and expose only necessary outputs. Validate input types and business constraints with variable validation.

Terraform workspaces can separate state within a backend, but they are not a complete IAM boundary and are not a substitute for independently controlled backend states. Their backend support also varies.

OpenTofu is largely compatible with Terraform configuration, but do not assume that providers, backend behavior, lockfiles, state migration, or test tooling are interchangeable. Validate and plan with the exact OpenTofu and provider versions intended for use, and follow the tool’s state-migration procedure before switching a production backend.

71

How do I create public and private AWS VPC subnets with Terraform?

Public and private subnets are AWS routing patterns: public subnets send default IPv4 traffic through an Internet Gateway, while private subnets use controlled egress such as a zonal NAT Gateway. This example uses two Availability Zones and one NAT Gateway per private subnet.

Read full answer

Applies toTerraform 1.10+ and AWS provider 5.x

Architecture

Property Public subnet Private subnet
Default route Internet Gateway NAT Gateway
map_public_ip_on_launch true false
Inbound internet traffic Possible if security groups permit it None by default
Typical use Load balancer or bastion host Application servers or databases

How It Works

  • The VPC enables DNS support and DNS hostnames.

  • The Internet Gateway is attached to the VPC; public subnets use a shared route table whose default route targets it.

  • Each private subnet has its own route table and NAT Gateway in the corresponding Availability Zone.

  • A subnet is effectively public because its route table reaches the Internet Gateway, not merely because public-IP mapping is enabled.

  • Separate NAT gateways improve zonal availability but cost more than sharing one NAT gateway across Availability Zones.

Code Example

The following is a complete main.tf:

terraform {
  required_version = ">= 1.10, < 2.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = var.aws_region
}

variable "aws_region" {
  type    = string
  default = "us-east-1"
}

variable "vpc_cidr" {
  type    = string
  default = "10.0.0.0/16"
}

data "aws_availability_zones" "available" {
  state = "available"
}

locals {
  azs = slice(data.aws_availability_zones.available.names, 0, 2)

  subnets = {
    for index, az in local.azs : az => {
      public_cidr  = cidrsubnet(var.vpc_cidr, 8, index)
      private_cidr = cidrsubnet(var.vpc_cidr, 8, index + length(local.azs))
    }
  }
}

resource "aws_vpc" "this" {
  cidr_block           = var.vpc_cidr
  enable_dns_support   = true
  enable_dns_hostnames = true

  tags = {
    Name = "example-vpc"
  }
}

resource "aws_internet_gateway" "this" {
  vpc_id = aws_vpc.this.id
}

resource "aws_subnet" "public" {
  for_each = local.subnets

  vpc_id                  = aws_vpc.this.id
  cidr_block              = each.value.public_cidr
  availability_zone       = each.key
  map_public_ip_on_launch = true

  tags = {
    Name = "example-public-${each.key}"
  }
}

resource "aws_subnet" "private" {
  for_each = local.subnets

  vpc_id                  = aws_vpc.this.id
  cidr_block              = each.value.private_cidr
  availability_zone       = each.key
  map_public_ip_on_launch = false

  tags = {
    Name = "example-private-${each.key}"
  }
}

resource "aws_eip" "nat" {
  for_each = local.subnets
  domain  = "vpc"
}

resource "aws_nat_gateway" "nat" {
  for_each = local.subnets

  allocation_id = aws_eip.nat[each.key].id
  subnet_id     = aws_subnet.public[each.key].id

  depends_on = [aws_route_table_association.public]
}

resource "aws_route_table" "public" {
  vpc_id = aws_vpc.this.id

  route {
    cidr_block = "0.0.0.0/0"
    gateway_id = aws_internet_gateway.this.id
  }
}

resource "aws_route_table_association" "public" {
  for_each = local.subnets

  subnet_id      = aws_subnet.public[each.key].id
  route_table_id = aws_route_table.public.id
}

resource "aws_route_table" "private" {
  for_each = local.subnets
  vpc_id   = aws_vpc.this.id

  route {
    cidr_block     = "0.0.0.0/0"
    nat_gateway_id = aws_nat_gateway.nat[each.key].id
  }
}

resource "aws_route_table_association" "private" {
  for_each = local.subnets

  subnet_id      = aws_subnet.private[each.key].id
  route_table_id = aws_route_table.private[each.key].id
}

output "subnet_ids" {
  value = {
    public  = [for az in local.azs : aws_subnet.public[az].id]
    private = [for az in local.azs : aws_subnet.private[az].id]
  }
}

Initialize and deploy with:

terraform init
terraform fmt
terraform validate
terraform plan -out=tfplan
terraform show tfplan
terraform apply tfplan

Production Operations

  • State safety: Provision the S3 backend separately with versioning, encryption, retention, restricted IAM access, and CloudTrail auditing. For Terraform 1.10+, merge this backend configuration into the existing terraform block:

terraform {
  backend "s3" {
    bucket       = "example-terraform-state"
    key          = "example/vpc/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    use_lockfile = true
  }
}

The IAM policy must permit access to the lock file. Treat state as sensitive because it can contain infrastructure metadata and secrets. Migrate existing state with terraform init -migrate-state; avoid -force-copy.

  • Monitoring and failures: Enable VPC Flow Logs and alarm on NAT Gateway metrics such as ErrorPortAllocation, PacketsDropCount, and ActiveConnectionCount. A failed NAT Gateway removes egress from its associated private subnet; security groups and network ACLs can independently block traffic. Consider VPC endpoints for S3 and DynamoDB to reduce NAT dependence.

  • Capacity and cost: Check subnet, Elastic IP, and NAT Gateway quotas before applying. Each NAT Gateway has hourly and data-processing charges in addition to its Elastic IP allocation.

Best Practices

  • Modules and lifecycle: Put this pattern in a versioned module and pin released module versions. Use lifecycle.prevent_destroy selectively on state-critical resources. Import existing VPCs, subnets, and routes by their AWS IDs before reconciling them with configuration.

  • Testing and CI/CD: Commit .terraform.lock.hcl; CI should run terraform fmt -check, terraform validate, terraform test, and a read-only plan. Test module logic with mocked providers and AWS behavior in a sandbox. A protected release job should apply the exact reviewed plan using workload identity, and provider upgrades should follow the same workflow.

  • Drift and isolation: Review every plan and use terraform plan -refresh-only to investigate drift. Use separate backend keys or backends per environment; workspaces do not provide strong production isolation.

  • Security and OpenTofu: Prefer workload identity or environment-based credentials over static access keys. OpenTofu can consume this HCL, but validate the selected OpenTofu release, backend locking behavior, and provider compatibility before adoption.

72

How to create an S3 bucket with versioning and encryption in Terraform?

Create the bucket and configure versioning and default encryption with dedicated AWS provider resources. This keeps each S3 setting independently managed and visible in Terraform state and plan output.

Read full answer

Applies toTerraform 1.10+ or OpenTofu 1.8+, AWS provider 5.x

How It Works

  • aws_s3_bucket: Creates the bucket and manages common properties such as tags, force_destroy, and object-lock enablement.

  • aws_s3_bucket_versioning: Setting status = "Enabled" preserves object versions and delete markers until they are explicitly deleted or expired by lifecycle rules.

  • aws_s3_bucket_server_side_encryption_configuration: Establishes default encryption for newly written objects. It does not retroactively encrypt existing objects; copying an object to itself can trigger encryption.

  • aws_s3_bucket_ownership_controls: BucketOwnerEnforced disables ACLs. Access can still be granted through IAM identity policies and S3 bucket policies.

  • aws_s3_bucket_public_access_block: Blocks public ACLs and policies for this bucket. Use aws_s3_account_public_access_block for account-wide protection.

  • aws_s3_bucket_lifecycle_configuration: Expires noncurrent versions and removes incomplete multipart uploads to control storage costs.

Code Example

terraform {
  required_version = ">= 1.10.0" # use_lockfile needs 1.10+

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }

  backend "s3" {
    bucket       = "example-terraform-state"
    key          = "prod/s3-app/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    use_lockfile = true
  }
}

provider "aws" {
  region = var.aws_region
}

variable "aws_region" {
  type    = string
  default = "us-east-1"
}

variable "bucket_name" {
  type = string
}

resource "aws_s3_bucket" "app" {
  bucket        = var.bucket_name
  force_destroy = false # Never true in production: it deletes objects and versions.
  tags = {
    Name        = var.bucket_name
    Environment = "prod"
  }
}

resource "aws_s3_bucket_versioning" "app" {
  bucket = aws_s3_bucket.app.id

  versioning_configuration {
    status = "Enabled"
  }
}

resource "aws_s3_bucket_server_side_encryption_configuration" "app" {
  bucket = aws_s3_bucket.app.id

  rule {
    apply_server_side_encryption_by_default {
      sse_algorithm = "AES256"
    }
  }
}

resource "aws_s3_bucket_ownership_controls" "app" {
  bucket = aws_s3_bucket.app.id

  rule {
    object_ownership = "BucketOwnerEnforced"
  }
}

resource "aws_s3_bucket_public_access_block" "app" {
  bucket                  = aws_s3_bucket.app.id
  block_public_acls       = true
  block_public_policy     = true
  ignore_public_acls      = true
  restrict_public_buckets = true
}

resource "aws_s3_bucket_lifecycle_configuration" "app" {
  bucket = aws_s3_bucket.app.id

  rule {
    id     = "expire-noncurrent"
    status = "Enabled"
    filter {}

    noncurrent_version_expiration {
      noncurrent_days = 30
    }

    abort_incomplete_multipart_upload {
      days_after_initiation = 7
    }
  }
}

output "bucket_arn" {
  value = aws_s3_bucket.app.arn
}

Encryption and Access Choices

Option Behaviour Typical use
AES256 SSE-S3 with an AWS-managed key Simpler operations for standard workloads
aws:kms SSE-KMS with an AWS-managed or customer-managed KMS key and per-object data keys Regulated data, key-policy control, and audit requirements
aws:kms:dsse Dual-layer encryption with KMS customer-managed keys Highly sensitive workloads requiring two encryption layers

For SSE-KMS with AWS provider 5.x, set kms_master_key_id inside apply_server_side_encryption_by_default and bucket_key_enabled = true inside the enclosing rule. The key policy and relevant permissions must permit the required KMS operations, normally including kms:GenerateDataKey and kms:Decrypt.

Production Hardening

The following policy denies S3 requests made over plaintext HTTP:

data "aws_iam_policy_document" "app" {
  statement {
    sid       = "DenyInsecureTransport"
    effect    = "Deny"
    principals {
      type        = "*"
      identifiers = ["*"]
    }
    actions   = ["s3:*"]
    resources = [aws_s3_bucket.app.arn, "${aws_s3_bucket.app.arn}/*"]

    condition {
      test     = "Bool"
      variable = "aws:SecureTransport"
      values   = ["false"]
    }
  }
}

resource "aws_s3_bucket_policy" "app" {
  bucket = aws_s3_bucket.app.id
  policy = data.aws_iam_policy_document.app.json
}

This policy does not require SSE-KMS. To require it, add a s3:PutObject deny for requests whose s3:x-amz-server-side-encryption header is absent or is not aws:kms. That intentionally rejects clients relying only on bucket-default encryption.

  • prevent_destroy: A Terraform-side guard only. It does not prevent console or API deletion; an SCP or an explicit bucket-policy deny can provide stronger protection.

  • Deletion: With force_destroy = false, Terraform cannot delete a bucket while object versions remain. Purge versions and delete markers first.

  • Lifecycle ownership: Keep lifecycle rules in aws_s3_bucket_lifecycle_configuration; avoid legacy inline lifecycle arguments.

State Safety, Drift and CI/CD

  • Remote state: Pre-provision the state bucket, enable versioning on it, encrypt it, and restrict access to the CI workload. Native S3 locking uses use_lockfile = true; legacy DynamoDB locking is only relevant to older Terraform versions.

  • Secrets in state: Terraform generally does not store provider credentials, but it can store any values read into configuration, including secrets returned by data sources. Do not read secret values in Terraform when they must remain out of state; grant the application workload role runtime access to Secrets Manager or SSM Parameter Store.

  • Drift: Run terraform plan -refresh-only to inspect out-of-band changes. In CI, terraform plan -detailed-exitcode returns 0 for no changes, 1 for an error, and 2 when changes are present.

  • Reviewed applies: Save the plan as a protected artifact and apply that exact plan with terraform apply tfplan; do not re-plan between review and apply.

  • Import: Import the bucket with terraform import aws_s3_bucket.app example-bucket, then import each configured sub-resource separately to avoid the first plan showing them as missing.

73

How do I build a Terraform module for a configurable EC2 instance?

A reusable Terraform module for EC2 packages instance settings while exposing deployment-specific values as inputs and stable identifiers as outputs. The caller selects the AMI and network placement, while the module controls storage encryption and metadata security.

Read full answer

Applies toTerraform 1.10+ within the 1.x series and AWS provider 5.x

Module Design

  • Require ami_id, subnet_id, and security_group_ids; provide a default instance type.

  • Validate basic input syntax locally; AWS validates region-specific availability, quotas, and unsupported instance types.

  • Encrypt the root EBS volume and require IMDSv2.

  • Avoid hard-coding account, region, VPC, or availability-zone details.

  • Expose the instance ID, ARN, and private IP without embedding credentials in outputs.

How It Works

Terraform resolves the module inputs into an aws_instance resource and outputs. Planning refreshes existing managed objects and evaluates the proposed configuration; it does not normally read arbitrary AMI or network objects merely because their IDs were supplied.

Applying the plan calls EC2 to launch the instance and create its root EBS volume. Changing the instance type can update the instance in place, potentially with a stop and start. Changing replacement-only fields such as the AMI or subnet forces a new instance with a new ID and addresses. A single EC2 instance is not highly available; production services should use an Auto Scaling group and load balancer.

Code Example

Create modules/ec2/main.tf:

terraform {
  required_version = ">= 1.10.0, < 2.0.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

variable "name" {
  type    = string
  default = "example-ec2"
}

variable "instance_type" {
  type    = string
  default = "t3.micro"

  validation {
    condition     = length(trimspace(var.instance_type)) > 0
    error_message = "instance_type must not be empty."
  }
}

variable "ami_id" {
  type = string

  validation {
    condition     = can(regex("^ami-[0-9a-f]+$", var.ami_id))
    error_message = "ami_id must be a valid AMI ID."
  }
}

variable "subnet_id" {
  type = string
}

variable "security_group_ids" {
  type = list(string)
}

variable "iam_instance_profile" {
  type    = string
  default = null
}

variable "user_data" {
  type    = string
  default = null
}

variable "root_volume_size" {
  type    = number
  default = 20
}

variable "monitoring" {
  type    = bool
  default = true
}

variable "tags" {
  type    = map(string)
  default = {}
}

resource "aws_instance" "this" {
  ami                         = var.ami_id
  instance_type               = var.instance_type
  subnet_id                   = var.subnet_id
  vpc_security_group_ids      = var.security_group_ids
  iam_instance_profile        = var.iam_instance_profile
  user_data                   = var.user_data
  monitoring                  = var.monitoring
  associate_public_ip_address = false

  root_block_device {
    volume_type = "gp3"
    volume_size = var.root_volume_size
    encrypted   = true
  }

  metadata_options {
    http_endpoint               = "enabled"
    http_tokens                 = "required"
    http_put_response_hop_limit = 1
  }

  tags = merge(var.tags, {
    Name = var.name
  })
}

output "instance_id" {
  value = aws_instance.this.id
}

output "instance_arn" {
  value = aws_instance.this.arn
}

output "private_ip" {
  value = aws_instance.this.private_ip
}

Example root configuration:

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = var.aws_region
}

variable "aws_region" {
  type    = string
  default = "us-east-1"
}

variable "subnet_id" {
  type = string
}

variable "security_group_ids" {
  type = list(string)
}

variable "instance_type" {
  type    = string
  default = "t3.small"
}

data "aws_ssm_parameter" "ubuntu_ami" {
  name = "/aws/service/canonical/ubuntu/server/24.04/stable/current/amd64/hvm/ebs-gp3/ami-id"
}

module "ec2" {
  source = "./modules/ec2"

  name               = "example-web"
  instance_type      = var.instance_type
  ami_id             = data.aws_ssm_parameter.ubuntu_ami.value
  subnet_id          = var.subnet_id
  security_group_ids = var.security_group_ids
}

State, Testing, and CI/CD

Use a versioned, encrypted S3 backend. Terraform 1.10+ can use S3-native locking:

terraform {
  backend "s3" {
    bucket       = "example-terraform-state-prod"
    key          = "prod/ec2/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    use_lockfile = true
  }
}

Enable bucket versioning, server-side encryption, public-access blocking, and least-privilege policies. The identity using use_lockfile needs s3:GetObject, s3:PutObject, and s3:DeleteObject for the lock-file object. State and saved plans may contain credentials, user_data, or sensitive resource attributes; protect and expire them.

A typical CI sequence is:

terraform fmt -check -recursive
terraform init -backend=false
terraform validate
terraform init
terraform plan -lock-timeout=5m -out=tfplan
terraform show tfplan

After approval, a protected job runs terraform apply tfplan. Do not publish raw plan output because it can expose sensitive values. Use terraform plan -refresh-only to inspect drift. Non-default S3-backend workspaces use workspace_key_prefix; scope IAM access to the resulting key prefixes rather than treating workspace selection as authorization.

Test modules with .tftest.hcl files and terraform test; Terraform 1.10 supports mocked providers, while real acceptance tests should cover AWS behavior separately. To adopt an existing instance, run terraform import 'module.ec2.aws_instance.this' i-0123456789abcdef0 and verify the resulting plan.

Production Practices

  • Monitor status checks, CPU credits, EBS metrics, and CloudWatch Agent logs; detailed monitoring has additional cost.

  • Use Auto Scaling groups and load balancers for availability across instances and availability zones.

  • Back up persistent EBS volumes with snapshots and test restoration; an AMI does not protect later volume changes.

  • Diagnose subnet and security-group errors, unavailable instance types, quotas, invalid IAM profiles, bootstrap failures, and KMS permissions when using a customer-managed key.

  • Use prevent_destroy only when accidental replacement is worse than a blocked update, and use ignore_changes narrowly.

  • OpenTofu may consume compatible module and provider versions, but its version constraints and S3 locking behavior must be tested separately.

74

How should Terraform be structured across company teams and accounts?

Use small, isolated root modules and remote state per ownership and blast-radius boundary, with shared, versioned modules for reuse. Separate AWS accounts by security boundary and keep team, environment, and region stacks distinct rather than centralizing all infrastructure in one state.

Read full answer

Applies toTerraform 1.10+ (1.x) with AWS provider 5.x

Organization and Ownership

  • Deployment units: Create one root module for each independently deployed unit, typically a team or workload, environment, AWS account, and region. Shared platform infrastructure should have its own platform-owned root rather than being duplicated into every workload stack.

  • AWS accounts: Use separate accounts for production, development, security boundaries, and teams with different risk or compliance requirements. Each account should have narrowly scoped CI/CD roles and provider credentials.

  • Repository: A practical layout is infra/modules/ for reusable modules and infra/stacks/<team>/<environment>/<region>/ for root modules. Pin shared modules to reviewed Git tags or publish them through an internal registry.

  • Ownership: Assign every stack and module through CODEOWNERS, require qualified reviewers, and grant each team permissions only for its accounts, state prefixes, and deployed resources.

Module and Interface Boundaries

  • Modules: Root modules own provider configuration, backend selection, and deployment-specific resources. Child modules implement reusable patterns such as networking, databases, or services and should declare their required providers explicitly.

  • Contracts: Resources declare desired infrastructure, data sources read existing infrastructure, typed variables expose inputs, and outputs form the module interface. Sensitive outputs remain sensitive in CLI output but are still stored in state.

  • Provider configuration: Keep authentication and provider aliases in root modules. Pass those configurations implicitly or explicitly to child modules rather than copying provider blocks throughout the repository.

  • Workspaces: Do not use workspaces as the primary account-isolation mechanism. Workspace state shares the configured backend and depends on the currently selected CLI context, increasing the risk of applying against the wrong environment.

State Safety and Lifecycle

  • Remote state: Use a dedicated S3 backend bucket per organization or security boundary, with a separate key for each root module. Enable encryption, bucket versioning, public-access blocking, and tightly scoped state access. Bootstrap the backend outside the stack that manages it and maintain a tested recovery procedure.

  • Locking: Terraform 1.10 or later can use the native S3 state lock through use_lockfile = true; the backend identity must have the required permissions for the lock object. Locking prevents concurrent operations but does not protect against misuse of valid credentials.

  • Secrets in state: State contains resource attribute values in a form readable by Terraform. Backend encryption protects data at rest, but every principal able to read state may be able to recover sensitive values. Do not place credentials, private keys, or unnecessary secret outputs in variables or resources.

  • Drift: Schedule terraform plan -refresh-only to detect out-of-band changes, investigate them, and apply reviewed refresh-only plans when state needs updating. Drift detection identifies divergence; it does not decide whether live infrastructure or configuration is authoritative.

  • Import: Use config-driven import blocks when possible, followed by a reviewed plan. Reserve the explicit terraform import command for cases that cannot be expressed in configuration.

  • Plan review: Require approval for destructive changes and inspect replacements, IAM changes, networking modifications, and public exposure. Apply prevent_destroy and create_before_destroy deliberately because they can complicate recovery and replacement operations.

CI/CD, Testing, and Operations

  • Pull requests: Run terraform fmt -check -recursive, terraform init -backend=false, terraform validate, policy checks, and terraform test. Use .tftest.hcl files to test module behavior, preferably with mock providers where real infrastructure is unnecessary.

  • Planning: A credentialed plan stage should initialize the remote backend and produce a saved plan. Before production, enforce the expected AWS account and region in CI and require approval of the resulting changes.

  • Applying: Apply the exact reviewed saved plan with pinned Terraform and provider versions. Store plan artifacts in an encrypted, access-controlled CI artifact store because plans can contain sensitive values even when outputs are marked sensitive.

  • Identity: Use short-lived AWS credentials through OIDC federation rather than storing access keys. Restrict each deployment role to its target account, state prefix, and permitted actions.

  • Operations: Enable S3 access logging, CloudTrail, and relevant service logs. Test provider upgrades and Terraform upgrades in staging before promotion, retain state versions and selected plans, and monitor failed plans, drift, lock contention, and unexpected replacements.

Trade-offs

  • Too few root modules create slow plans, broad permissions, and dangerous shared dependencies. Too many increase provider setup and cross-stack orchestration overhead.

  • Central platform services should be consumed through published interfaces, not copied into every stack or administered through one highly privileged state.

  • Organizations may standardize on OpenTofu after validating provider compatibility, backend locking, test behavior, CI integrations, and state migration procedures rather than making an unreviewed production substitution.

75

How do you import manually created cloud resources into Terraform?

Use Terraform import to bring an existing cloud object into Terraform-managed state, then declare matching configuration and verify convergence with reviewed plans. Import updates Terraform state; it does not recreate or modify the cloud resource.

Read full answer

Applies toTerraform 1.10 or later in the 1.x series; AWS provider 5.x

Migration Workflow

  1. Inventory the resource: Capture its provider-specific ID, region, attributes, dependencies, tags, network or storage attachments, DNS records, and ownership requirements.

  2. Configure the provider and backend: Use an IAM role or workload identity rather than static credentials. Configure versioned, encrypted remote state with locking before importing.

  3. Write matching configuration: Model the existing object with resources such as aws_instance or aws_s3_bucket. Match attributes that trigger replacement, including AMI, availability zone, VPC, and subnet changes.

  4. Import one resource at a time: Use either the CLI terraform import ADDRESS ID command or a configuration-driven import block.

  5. Review the plan: The first plan should contain no unintended changes. A replacement, deletion, or unexplained in-place modification indicates that the configuration does not match the real resource.

  6. Apply and verify: Apply the reviewed plan, then check cloud monitoring, logs, backups, DNS, and application health.

Data sources are appropriate for reading external information, but a resource that Terraform should own should remain a managed resource after import.

What Import Does Under the Hood

terraform import aws_instance.web i-0123456789abcdef0 asks the AWS provider to read the existing EC2 instance and write its attributes into state. Terraform does not call the instance creation API during import.

The subsequent plan compares:

  • The HCL configuration.

  • Provider-refreshed remote API state.

  • The last recorded Terraform state.

Drift can be detected with terraform plan -refresh-only. Apply that plan only when the goal is to reconcile state with reality; configuration changes still require a normal reviewed plan.

For Terraform 1.5 and later, an import block provides configuration-driven import. Terraform plans the import operation, and terraform apply writes the imported object into state. If configuration is missing, terraform plan -generate-config-out=generated.tf can generate a draft that must be reviewed before use.

Code Example

The backend bucket must already exist, preferably with versioning, encryption, access logging, and restricted access enabled:

terraform {
  required_version = ">= 1.10, < 2.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }

  backend "s3" {
    bucket        = "example-terraform-state"
    key           = "production/web/terraform.tfstate"
  region        = "us-east-1"
    encrypt       = true
    use_lockfile = true
  }
}

provider "aws" {
  region = var.aws_region
}

variable "aws_region" {
  type    = string
  default = "us-east-1"
}

resource "aws_instance" "web" {
  ami           = "ami-0123456789abcdef0"
  instance_type = "t3.micro"

  tags = {
    Name = "web"
  }

  lifecycle {
    prevent_destroy = true
  }
}

import {
  to = aws_instance.web
  id = "i-0123456789abcdef0"
}

output "web_public_ip" {
  value = aws_instance.web.public_ip
}

Initialize the correct workspace and perform the configuration-driven import:

set -euo pipefail

terraform init -input=false

if ! terraform workspace select production; then
  terraform workspace new production
fi

terraform plan -out=tfplan
terraform show tfplan
terraform apply tfplan

For a one-off CLI import, omit the import block and run terraform import aws_instance.web i-0123456789abcdef0 before planning. Do not use both mechanisms for the same resource.

If the remote backend uses one state key per workspace, switching workspaces changes which state is operated on. Workspaces are not a strong security boundary; separate accounts or projects are preferable for strict environment isolation.

Production Failure Modes

  • Accidental replacement: Differences in immutable or replacement-triggering attributes can cause Terraform to destroy the original resource. Block production applies until the plan is reviewed.

  • Partial apply failures: Terraform can update some resources before an error. Use small, dependency-aware changes and ensure databases, disks, and persistent workloads have tested backups.

  • State loss or corruption: Enable backend versioning and tightly control state deletion. State backups can contain sensitive values, so encrypt and restrict them.

  • Lock contention: A stale Terraform process can retain the state lock. Verify ownership before removing a lock; never bypass locking in CI.

  • Secrets in state: sensitive = true only redacts a value in CLI output. Values passed to providers or returned by data sources can still be persisted. Retrieve secrets at runtime through an IAM-backed application integration rather than injecting secret values into Terraform inputs.

  • Drift: Schedule refresh-only plans and alert on unexpected infrastructure changes outside approved pipelines.

CI/CD and Best Practices

Use separate plan and apply jobs. The plan job runs terraform fmt -check -recursive, terraform init -input=false, terraform validate, and terraform plan -out=tfplan; the apply job receives the approved artifact and runs terraform init -input=false followed by terraform apply tfplan. Both jobs must select the same workspace, such as with TF_WORKSPACE=production.

  • Store and commit the provider dependency lock file. Use an immutable CI image and short-lived OIDC credentials.

  • Separate plan and apply permissions so CI cannot apply without an approved plan artifact.

  • Protect plan artifacts because they can contain sensitive values.

  • Keep state ownership and access boundaries explicit for versioned modules.

  • Use terraform test for isolated configuration tests and assertions; run OPA, Conftest, or another dedicated policy-as-code scanner separately.

  • Prefer additive migrations over replacement. A state rollback does not roll back cloud changes, so reconcile actual infrastructure with a new plan.

  • OpenTofu supports analogous import workflows, but verify backend and provider compatibility before switching state tools.

76

How do you prevent accidental deletion of a production database in Terraform?

Use defense in depth: Terraform’s prevent_destroy lifecycle rule rejects destructive plans, while Amazon RDS deletion_protection rejects deletion through the AWS API. For production, also use locked remote state, reviewed plan artifacts, least-privilege credentials, backups, and independent IAM or SCP controls.

Read full answer

Applies toTerraform 1.10+ within the 1.x series with AWS provider 5.x; OpenTofu 1.8+ for native state encryption

Core safeguards

Safeguard Enforcement point Protects against Important limitation
prevent_destroy = true Terraform planning Direct destroys and replacement plans A reviewed configuration can disable it
RDS deletion_protection = true RDS deletion APIs Console, CLI, SDK, and IaC deletion attempts A principal with modification permissions can disable it first
Final snapshot and automated backups RDS Data loss after an authorized deletion They do not prevent deletion
Locked remote state Terraform backend Concurrent state writes Locking does not replace backups or access controls
  • Terraform guard: prevent_destroy is configuration, not state. It rejects a plan containing a destroy action, including replacement of a resource. Changing identifier, for example, normally requires replacement and therefore fails while the rule remains enabled.

  • AWS guard: Set deletion_protection = true on aws_db_instance or aws_rds_cluster. For Aurora, configure protection on the cluster; member instances do not provide an independent deletion-protection setting.

  • Intentional decommissioning: use separate reviewed changes to temporarily relax the Terraform rule and RDS protection, complete the replacement, then restore both on the new resource.

  • Recovery: use skip_final_snapshot = false, an appropriate final_snapshot_identifier, and a tested backup_retention_period. Restore drills are still required.

State, secrets, and drift

  • Store production state in an encrypted, versioned S3 backend with public access blocked. Terraform 1.10+ supports native S3 locking through use_lockfile = true; DynamoDB locking remains an alternative. A remote backend alone is not a backup.

  • Terraform state may contain sensitive values even with backend encryption. Restrict backend access, enable audit logging, and protect plan artifacts because saved plans can also contain sensitive values.

  • With manage_master_user_password = true, AWS Secrets Manager holds the master password and Terraform state retains the secret ARN and metadata rather than the password value. Other sensitive attributes still require careful state handling.

  • Refresh and review plans regularly. If someone disables RDS deletion protection outside Terraform, terraform plan shows the difference from false back to the configured true; an apply restores the desired value.

  • terraform state rm does not delete the database, but it removes Terraform’s ownership and bypasses its lifecycle guard. Removed blocks requesting destruction still respect prevent_destroy.

CI/CD and IAM controls

  • Save a plan, require approval, and apply that exact plan file. Do not regenerate an apply-time plan after approval.

  • Use OIDC federation and short-lived CI roles. Scope permissions to the production account and resource set.

  • Deny rds:DeleteDBInstance and rds:DeleteDBCluster with IAM or an SCP as a hard deletion floor. A management-account root user is outside SCP enforcement, so account-level governance must also control that principal.

  • IAM cannot condition ModifyDBInstance or ModifyDBCluster specifically on the new value of deletion_protection. A blanket deny on those actions also prevents legitimate Terraform modifications and prevents the provider from enabling protection. If stronger separation is required, use a restricted routine role plus a separately approved break-glass modification process; clusters use rds:ModifyDBCluster and instances use rds:ModifyDBInstance.

  • Run a destroy-plan check in a protected environment. With prevent_destroy enabled, Terraform should fail before a destructive apply is possible.

Code Example

terraform {
  required_version = ">= 1.10, < 2.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }

  # The bucket must already exist with appropriate access controls.
  backend "s3" {
    bucket       = "acme-terraform-state-prod"
    key          = "prod/rds/terraform.tfstate"
    region       = "us-east-1"
    encrypt      = true
    use_lockfile = true
  }
}

provider "aws" {
  region = "us-east-1"
}

resource "aws_db_instance" "orders" {
  identifier     = "orders-prod"
  engine         = "postgres"
  instance_class = "db.r6g.xlarge"

  allocated_storage = 500
  storage_encrypted = true
  username          = "app_admin"

  # The password value is managed by AWS Secrets Manager.
  manage_master_user_password = true

  multi_az                = true
  backup_retention_period = 14

  # Server-side deletion guard.
  deletion_protection = true

  # Create a final snapshot if deletion is intentionally authorized later.
  skip_final_snapshot       = false
  final_snapshot_identifier = "orders-prod-final"

  lifecycle {
    # Terraform-side guard.
    prevent_destroy = true
  }
}

Common pitfalls

  • Configuration-only protection: anyone able to merge a change to prevent_destroy = false weakens it; require code-owner approval for production lifecycle rules.

  • Unreviewed apply: applying a newly generated plan can differ from the plan that was approved. Apply the saved plan file instead.

  • Blind unlocking: terraform force-unlock during an active operation can corrupt state; first verify that no apply is running.

  • Backup confusion: snapshots and backups aid recovery but do not stop accidental deletion.

  • OpenTofu encryption: native encrypted state is an OpenTofu 1.8+ feature and is not interchangeable with Terraform’s backend configuration.

77

How do you use Terraform check blocks and lifecycle preconditions?

Use a check block for advisory assertions that produce warnings, and use a precondition as a hard validation gate that stops the planned operation when its condition is false. Checks are useful for operational validation, while preconditions protect resource and data-source lifecycle operations.

Read full answer

Applies toTerraform 1.5+ for `check` blocks; AWS provider 5.x examples

Difference Between Checks and Preconditions

Feature check block precondition
Purpose Assert an invariant or operational expectation Prevent an unsafe or invalid operation
On failure Emits a warning Produces an error and stops the operation
Placement Top-level Terraform block Inside a resource or data source lifecycle block
Typical use API health checks, policy warnings, configuration advisories Validate inputs, resource relationships, and safety constraints
Enforcement Advisory only Enforced by Terraform

A check block is evaluated as part of Terraform’s normal evaluation process and can use variables, data sources, resources, and locals. A check block may also contain its own nested data source when it needs to perform a read specifically for the check.

A precondition is evaluated before the relevant resource creation or update operation, or before a data source read. If the condition is false, Terraform reports the error_message and aborts that operation. Terraform does not evaluate lifecycle preconditions and postconditions during resource destruction, so destroy-specific safeguards should be implemented separately where necessary.

Code Example

terraform {
  required_version = ">= 1.5.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

variable "vpc_id" {
  type = string
}

variable "allowed_cidrs" {
  type    = list(string)
  default = ["10.0.0.0/16"]
}

variable "instance_type" {
  type    = string
  default = "t3.micro"
}

data "aws_ami" "app" {
  owners      = ["amazon"]
  most_recent = true

  filter {
    name   = "name"
    values = ["amzn2-ami-hvm-*-x86_64-gp2"]
  }
}

resource "aws_security_group" "app" {
  name_prefix = "app-"
  vpc_id      = var.vpc_id

  ingress {
    description = "HTTPS"
    from_port   = 443
    to_port     = 443
    protocol    = "tcp"
    cidr_blocks = var.allowed_cidrs
  }

  lifecycle {
    precondition {
      condition = alltrue([
        for cidr in var.allowed_cidrs :
        can(cidrnetmask(cidr)) && cidr != "0.0.0.0/0"
      ])

      error_message = "allowed_cidrs must contain valid IPv4 CIDRs and must not include 0.0.0.0/0."
    }
  }
}

check "ami_is_available" {
  assert {
    condition     = data.aws_ami.app.id != ""
    error_message = "The selected AWS AMI could not be resolved."
  }
}

check "instance_type_is_approved" {
  assert {
    condition = contains(
      ["t3.micro", "t3.small", "t3.medium"],
      var.instance_type
    )

    error_message = "instance_type must be one of the approved instance types."
  }
}

The security-group precondition is a hard gate: an overly broad or invalid CIDR prevents the security-group operation. The two checks are advisory: failed assertions report warnings but do not stop the apply. Provider errors, such as an unavailable API or invalid AWS credentials, can still fail Terraform independently of a check assertion.

Evaluation and CI/CD Workflow

Conditions must evaluate to Boolean values. Use functions such as can() when an invalid value could cause an evaluation error, and use alltrue() to validate every item in a collection.

A production pipeline should generally run:

terraform fmt -check -recursive
terraform init -backend=false
terraform validate

terraform init
terraform plan -out=tfplan
terraform show tfplan
terraform apply tfplan

Review the saved plan before applying it. Applying the same reviewed plan avoids executing a different configuration than the one that was inspected. terraform validate checks syntax and static consistency, but it does not replace a real plan because provider reads and many runtime conditions happen during planning or applying.

OpenTofu is largely compatible with this HCL pattern, but provider versions, backend locking behavior, and OpenTofu releases should be verified independently.

State Safety and Operational Considerations

  • Store state in a remote backend with encryption, versioning, access control, backups, and locking. Never use a local state file for shared production infrastructure.

  • Remember that sensitive = true redacts output but does not remove a secret from state. Use an external secret manager and avoid placing credentials in Terraform configuration.

  • Run regular plans to detect drift, including terraform plan -refresh-only when diagnosing changes without proposing infrastructure updates.

  • Treat check warnings as signals for monitoring and policy review; use preconditions or separate policy-as-code controls for requirements that must be enforced.

  • Check blocks may make API calls, so they can add latency, consume cloud API quota, and require carefully scoped read-only permissions.

  • Keep lifecycle conditions deterministic and avoid checks that depend on unstable external responses when a hard gate is required.

Sign in to keep reading

You've opened 2 full answers. Sign in to read all 77 Terraform answers, mark what you know and pick up where you left off.

Report a mistake

What's wrong?

All Cloud, DevOps & Infrastructure subjects