Chapter 2. Infrastructure as Code and deployment automation (Intermediate: Terraform & IaC)

Learning objectives

  • Explain the limitations of manual console operations (ClickOps), and explain the declarative model of Terraform and the principles behind how the state file (terraform.tfstate) works.
  • Configure an S3 remote backend and state locking (use_lockfile and DynamoDB) to prevent state corruption caused by concurrent executions.
  • Design reusable modules, compare the trade-offs between directory-based environment separation and workspaces, and select a production isolation architecture.
  • Distinguish between in-place updates (~) and destroy and recreate (-/+, Replace) in terraform plan output, and refactor without data loss using lifecycle { prevent_destroy = true } as well as moved and import blocks.
  • Explain why sensitive = true or ephemeral resources cannot substitute for state file encryption, and design access controls for state files and secret injection architectures.
  • Identify the causes of infrastructure drift, and execute procedures to revert unauthorized manual changes or incorporate emergency hotfixes into code.
  • Build a secure Terraform deployment pipeline without long-term IAM access keys using GitHub Actions OIDC (AssumeRoleWithWebIdentity) and minimal conditions (sub, aud).

Introduction

When first starting with cloud services, anyone logs into the AWS, Cloudflare, or Supabase console with a web browser and clicks buttons with a mouse to create resources. Five minutes is enough to open a port in a security group, create an S3 bucket, and add a DNS record. This is known as ClickOps.

However, when a service grows and requires an identical staging environment to be created, or when another feature stops the next day due to a firewall setting that someone hurriedly changed during an early-morning outage, ClickOps instantly turns into a disaster. "Assistant Manager Kim supposedly checked a checkbox in the console last month, but where was it?", "Why does it work fine in staging but give a permission error only in production?", "Someone accidentally deleted a routing table, and no one knows what the original configuration value was." This is because mouse clicks leave behind no Git commit history, no code reviews (PRs), and no automated rollbacks.

Infrastructure as Code (IaC) and its standard tool, Terraform, transform infrastructure from the byproduct of mouse clicks into version-controlled declarative code (.tf). However, if Terraform is used without understanding how the tool works, it can cause accidents far more terrifying than mouse clicks. A single terraform apply may delete and recreate (-/+) a production database, causing data to vanish; two engineers running commands concurrently may corrupt the state file; or a database master password may leak in plaintext through a terraform.tfstate file committed to a Git repository. In this chapter, we will learn thirteen core concepts and practical CI/CD automation designs for managing Terraform safely and predictably.

Key concepts

Declarative model and core Terraform workflow

Approaches to automating infrastructure fall broadly into two categories:

  • Imperative (procedural) approach: Like shell scripts or the AWS CLI, it instructs in order "how" to do things. For example, one writes: "Create a security group -> open port 443 -> launch 2 servers." The problem arises when the script is executed twice. It may fail with an error stating that the security group already exists, or it may create 2 additional servers, resulting in a total of 4 servers.
  • Declarative approach: Like Terraform (HCL, HashiCorp Configuration Language), it records only "what the final state should be" (What). If one declares that "there must be 1 security group with port 443 open and 2 servers," it creates 2 new servers when there are currently 0 servers, does nothing when there are already 2 servers (idempotency), removes 1 server when there are 3 servers, and when the port number is changed to 8443, calculates and applies only that difference (diff).

The standard Terraform execution lifecycle operates in three steps:

  1. terraform init: Initializes the working directory, downloads declared cloud provider plugins (AWS, Cloudflare, Supabase, etc.) and modules, and connects to the backend where the state file is stored.
  2. terraform plan: Without touching actual cloud resources yet, it compares (a) the .tf code you wrote (desired state), (b) the state file (terraform.tfstate, last remembered state), and (c) the current state of actual infrastructure confirmed by calling cloud APIs, and shows an execution plan of "what to add (+), modify (~), destroy (-), and replace (-/+)".
  3. terraform apply: Calls cloud APIs based on the reviewed plan to actually apply the changes, and records the result in the state file.

Role and structure of the state file (terraform.tfstate)

The secret behind Terraform's declarative magic lies precisely in the state file (terraform.tfstate).

When code says resource "aws_instance" "web" { ... }, how does Terraform know which specific instance (i-0a1b2c3d4e5f) among hundreds of EC2 instances running in the AWS account this block refers to? It is because the actual cloud resource ID and attribute values created during the first apply are recorded like a ledger in the JSON-formatted terraform.tfstate file.

The state file serves three decisive roles:

Role Description What happens if the state file is damaged or lost
Mapping code to physical resources Connects the logical address in .tf (aws_db_instance.main) 1:1 with the cloud's physical ID (arn:aws:rds:...) Attempts to create a duplicate resource from scratch without knowing an operational DB already exists, resulting in collisions or duplicate creation
Preserving the dependency graph Records which resources reference other resources to calculate the exact order of deletion and replacement Unable to track what needs to be deleted in what order when a block is removed from code
Performance and change detection baseline Stores a snapshot of attributes last retrieved from cloud APIs Every cloud resource would need to be exhaustively scanned every time, or the drift reference baseline is lost

As such, because the state file is the heart of infrastructure, one must never open it by hand to edit the JSON text directly, nor should it be kept only on a local laptop disk and shared among team members via chat messengers.

Remote backend and state locking

When practicing alone, having terraform.tfstate created in a local folder is acceptable; however, the moment two or more people collaborate or a CI/CD pipeline runs, a remote backend and state locking become essential, not optional.

What would happen if Engineer A and Engineer B execute terraform apply concurrently on the same infrastructure from their respective laptops? As the state read by A's process and the state read by B's process overwrite each other (race condition), resources created by one side vanish from the state file (generating orphaned resources) or the state JSON itself becomes corrupted.

To prevent this, the state file is kept in a centralized remote storage with versioning and encryption enabled (e.g., AWS S3, Terraform Cloud, GCS), and state locking is applied so that while someone is running plan or apply, other executions cannot intervene.

terraform {
  backend "s3" {
    bucket       = "company-prod-tfstate-apne2"
    key          = "network/prod/terraform.tfstate"
    region       = "ap-northeast-2"
    encrypt      = true
    use_lockfile = true
  }
}

Both methods of state locking for the AWS S3 backend must be understood:

  1. Traditional method (dynamodb_table): Separately from the S3 bucket, a DynamoDB table with LockID (string partition key) was created to manage locks via conditional writes. It is still widely used in existing infrastructure and legacy code.
  2. Modern S3 native locking (use_lockfile = true): As S3 now supports conditional writes (atomic object creation via the If-None-Match header), modern Terraform allows state to be locked safely by atomically creating a .tflock lock file inside the S3 bucket using only the use_lockfile = true option, without creating a separate DynamoDB table.

In addition, bucket versioning, server-side encryption (SSE-S3 or SSE-KMS), and Block Public Access must be enabled on the S3 bucket. This ensures that even if state is accidentally overwritten, it can be immediately restored to an earlier version of the S3 object.

Caution

Occasionally, when a CI pipeline terminates abnormally and leaves a lock unreleased, people indiscriminately append the -lock=false option or overuse terraform force-unlock <LOCK_ID> without even checking whether a colleague is currently running apply. -lock=false is a dangerous option that disables the lock safeguard, and force-unlock should be used only as a last resort when it has been 100% verified that no other process is actually running.

Module design and version pinning

When infrastructure code grows to thousands of lines, identical patterns (e.g., VPC + subnets + security groups, or standard S3 bucket + encryption + log settings) repeat in multiple places. A Terraform module is an abstraction unit that packages related resource bundles into reusable packages like functions.

  • Input variables (variables.tf, variable block): Configuration values injected from outside the module. By using type and validation blocks, invalid CIDR formats or disallowed regions can be made to fail immediately during the plan phase.
  • Local values (locals block): Constants and combined expressions computed and used only within the module.
  • Output values (outputs.tf, output block): Result values to pass to parent (root) modules or other modules, such as IDs or domain names of resources created by the module.

When consuming modules from public registries or internal Git repositories, the most critical security and stability principle is version pinning.

module "vpc" {
  source  = "terraform-aws-modules/vpc/aws"
  version = "5.16.0"

  name = "prod-vpc"
  cidr = "10.20.0.0/16"
}

If a version is omitted or left open to an overly broad range, running terraform init -upgrade one day to deploy a minor fix could bump the module's major version, altering the underlying resource structure and causing production resources to be replaced (-/+) entirely. In production environments, external modules should be pinned to exact versions (or verified internal Git commit SHAs and tags), and the dependency lock file, .terraform.lock.hcl, must be committed to the Git repository to enforce that all developers and CI runners use provider binaries with identical hashes. However, note the distinction: the lock file records only providers and does not track remote module versions. Providers are pinned via version range constraints and the lock file, whereas external modules are pinned via an exact version in the version argument.

Environment isolation: directory-based state separation versus workspaces (Workspace)

When managing development (dev), staging (staging), and production (prod) environments with Terraform, how should the structure be divided? There are two approaches, and their differences and limitations must be clearly distinguished.

Comparison item Directory and backend separation (envs/dev, envs/prod) Single directory + CLI workspace (terraform workspace)
State file isolation Completely different S3 buckets/paths, with ability to grant different IAM permissions Only paths are divided under the same backend bucket as env:/dev/..., env:/prod/...
Accommodating code and version differences Can test new module versions in staging first and apply them to prod a few days later All workspaces share completely identical .tf code and module versions
Risk of operator error Impossible to touch prod resources while inside the envs/dev folder Risk of mistaking the currently selected workspace for dev when it is actually prod and executing destroy/apply
Recommended use Permanent environment isolation between production and non-production (standard practice) A single developer stamping out and tearing down temporary test environments per PR

In other words, the production (prod) environment must separate its physical and logical boundaries with a separate directory, a separate state file backend, and preferably a separate cloud account (AWS Account / project) and dedicated IAM role. The safest architecture is to extract shared code into reusable modules (modules/app-stack), and have envs/stage/main.tf and envs/prod/main.tf invoke that module independently while specifying their own backends and versions.

Precision decoding of terraform plan and blocking destructive changes (prevent_destroy)

Ninety percent of Infrastructure as Code incidents happen when someone habitually types yes or pushes through with -auto-approve without properly reading the warnings printed by terraform plan. The four symbols prefixed to resources in plan output must be memorized:

Symbol Meaning What actually happens in the cloud Risk level
+ (Create) Newly created Creates newly added resources in the cloud based on code Low (check costs and quotas)
- (Destroy) Completely destroyed Permanently deletes resources removed from code from the cloud Very high (data destruction)
~ (Update in-place) Update in-place Modifies only configuration values (e.g., tags, security group rules, capacity expansion) via API without deleting resources Medium (check for brief interruptions)
-/+ or +/- (Replace) Destroy and recreate (replace) Completely destroys the existing resource (-) and then creates a new resource (+). Resource IDs and internal data are reset! Critical (loss of DBs, volumes, static IPs)

Why does -/+ (destroy and recreate) appear instead of ~ (update in-place) when you modified only a single line in code? This is because the cloud vendor's API does not permit modifications to that attribute (immutable attribute). For example, modifying the identifier or encryption settings of an AWS RDS database, changing the subnet (subnet_id) or AMI of an EC2 instance, or changing the name (bucket) of an S3 bucket cannot be done while keeping the existing resource, so Terraform displays -/+ along with the comment # forces replacement.

The primary safeguard at the code level to prevent stateful core resources (production databases, persistent storage buckets, encryption KMS keys, core VPCs) from being deleted or replaced (-/+) even by mistake is prevent_destroy = true in the lifecycle block.

resource "aws_db_instance" "production" {
  identifier     = "aidan-prod-postgres"
  engine         = "postgres"
  instance_class = "db.r6g.large"

  lifecycle {
    prevent_destroy = true
  }
}

With this declared, if someone inadvertently touches an immutable attribute of the DB and triggers a replacement (-/+), Terraform immediately stops during the plan phase with an error (Instance cannot be destroyed). The situation is different if the resource block itself is deleted. Because the lifecycle configuration vanishes along with the block, prevent_destroy cannot stop the deletion. For resources supporting deletion protection (deletion_protection), such as RDS, cloud-side protection should be turned on as well. Furthermore, for resources where the new resource must be created before destroying the old one—such as web servers or certificates requiring zero-downtime replacement—use create_before_destroy = true; for attributes constantly modified by external autoscalers (e.g., current container count desired_capacity), specify ignore_changes = [desired_capacity] to prevent unnecessary overwrites.

Zero-downtime refactoring and importing existing resources: moved blocks and import blocks

While organizing infrastructure code, there are times when you want to rename a resource from aws_s3_bucket.old_name to aws_s3_bucket.assets, or move a resource from the root into a child module (module.storage.aws_s3_bucket.assets).

If you simply change the name in the code and run terraform plan, a shocking result appears. Not knowing that the name was changed, Terraform plans to "destroy (-) the old name (old_name) and newly create (+) the new name (assets)"! If applied as is, production S3 buckets or databases will be deleted.

In the past, engineers manually executed the terraform state mv command in the terminal to modify the state file, but this could not be verified through PR reviews and was difficult to synchronize with other team members or CI pipelines. In modern Terraform, we declare a moved block in code to refactor safely.

moved {
  from = aws_s3_bucket.old_name
  to   = module.storage.aws_s3_bucket.assets
}

When a moved block is committed, terraform plan displays a message indicating that only the address pointer in the state file is safely migrated instead of destroying and creating resources, and the physical cloud resource remains completely intact without even a single second of interruption.

Similarly, when bringing existing cloud resources created via mouse clicks in the console into Terraform management, the declarative import block is used.

import {
  to = aws_s3_bucket.legacy_uploads
  id = "company-legacy-uploads-prod"
}

After writing the import block and using terraform plan -generate-config-out=generated.tf or aligning the resource block, executing plan to align code until there are zero differences (~ or -/+, No changes) and then running apply allows the existing resource to be safely incorporated into the state file without touching it.

Plaintext secret exposure in state files and managing sensitive variables

There is one fact most commonly misunderstood in Terraform security: The belief that "adding sensitive = true to variables or outputs encrypts or hides them within the terraform.tfstate file as well" is completely false!

All that sensitive = true does is mask the value as (sensitive value) in terminal screens (console logs) when executing terraform plan and terraform apply. Because Terraform must know the original value to compare whether it changed in the next plan, database passwords, TLS private keys, and API tokens entered into general resource attributes are stored literally in plaintext within the terraform.tfstate JSON file.

Therefore, for state file security, the following four principles must be applied together:

  1. Under no circumstances should terraform.tfstate or the .terraform/ directory be committed to Git (mandatory entry in .gitignore).
  2. Encrypt the remote backend (such as S3) storage itself with KMS or similar (encrypt = true), and strictly restrict IAM permissions to read state files to the deployment pipeline and minimal administrator roles. Permission to read the state file is effectively equivalent to permission to read all secrets in the infrastructure.
  3. Instead of generating passwords directly in Terraform code or passing them as plaintext variables, use cloud-managed master password management features (e.g., manage_master_user_password = true in RDS) or design the application to read secrets directly from Secrets Manager / Parameter Store / Vault at runtime, ensuring that secret values themselves are never written to the state file.
  4. By using ephemeral variables and resources (ephemeral = true, ephemeral block) and write-only attributes (e.g., password_wo) supported by modern Terraform (1.10+), secret values can be read only during execution and passed to target APIs, ensuring they are not recorded in state files or plan files at all.

Drift detection and recovery procedures

Configuration drift refers to a state where the appearance of infrastructure remembered by code (.tf) and the state file diverges from the appearance of infrastructure actually running in the cloud.

Why does drift occur? The most common cause is when an on-call engineer, trying to extinguish an urgent fire during an early-morning incident, directly accesses the AWS or Cloudflare console to change security group ports, instance specifications, DNS records, or WAF rules with a mouse, and fails to reflect those changes in code.

If drift is left unattended, the moment someone runs terraform apply a month later to deploy an entirely different feature, Terraform overwrites (reverts) the hotfix settings manually changed in the console back to their original state because "they differ from the code," causing the incident to recur.

The proper procedure for addressing drift is as follows:

  1. Regular drift detection: Run terraform plan -detailed-exitcode (returns 0 for no changes, 1 for errors, 2 when drift/changes are detected) or terraform plan -refresh-only via a CI scheduler (e.g., every morning) to immediately send alerts to Slack or tickets if there are changes made in the cloud without corresponding code.
  2. Root cause determination and two-pronged recovery:
    • In the case of unauthorized changes or mistakes: Execute terraform apply based on current .tf code to return the cloud state back to the definition in code (convergence to code).
    • In the case of legitimate emergency hotfixes that must be kept: First modify .tf code to match exactly the actual configuration changed in the console, then run terraform plan to confirm no additional changes (No changes. Your infrastructure matches the configuration.), and commit.

Keyless CI/CD pipeline via GitHub Actions OIDC

In the past, to deploy AWS infrastructure with Terraform from GitHub Actions, an IAM user was created, long-term access keys (AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY) were issued, and they were stored in GitHub Secrets. This approach has fatal weaknesses. Once issued, static keys never expire; if a key is leaked even once due to a CI log misconfiguration or a third-party Action supply-chain attack, an attacker can seize control of our entire cloud anytime from anywhere, and rotating keys periodically is cumbersome.

The modern cloud security standard is to completely eliminate long-term static keys and use OIDC (OpenID Connect)-based short-term token exchange (AssumeRoleWithWebIdentity).

The operational flow is as follows:

  1. Register GitHub's OIDC issuer (https://token.actions.githubusercontent.com) in AWS IAM as a trusted identity provider.
  2. When granting permissions: { id-token: write, contents: read } to a GitHub Actions workflow, GitHub issues a digitally signed short-term OIDC JWT when the job executes, stating "this request is indeed from a workflow running on the main branch of the org/repo repository."
  3. When the workflow presents this JWT to AWS STS (AssumeRoleWithWebIdentity), AWS checks the conditions in the IAM role's trust policy and issues temporary credentials valid for only about one hour. There is no long-term secret key to store at all!

The most important key point here in exams and at work is how narrowly the Condition clause of the IAM role trust policy is configured.

{
  "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:acme-corp/infra-live:ref:refs/heads/main"
        }
      }
    }
  ]
}

The sub value in the example above is in repository name-based format. Tokens for repositories created, renamed, or transferred after July 15, 2026, or opted into immutable formats, use a sub containing immutable IDs. Before writing trust policies, verify the actual sub format of your repository's token first. If the sub (Subject) condition is omitted, any repository of any GitHub user across the entire world can assume our AWS role! Furthermore, if a role with production apply privileges is opened to all branches via StringLike such as "repo:acme-corp/infra-live:*", any developer can obtain production administrator privileges simply by modifying the workflow file (.github/workflows/deploy.yml) on a feature branch and opening a PR. Therefore, the following principle of separating PR plan and post-main-merge apply must be observed:

Pipeline stage Trigger point IAM role and sub condition used Permission scope
PR verification (plan) Pull Request created or updated terraform-planner role (restricted to pull_request or dedicated plan environment) Read-Only + state locking and query permissions. Posts only plan results to PR comments
Production deployment (apply) Merge to main branch following code review approval terraform-applier role (strictly restricted to ref:refs/heads/main or approval-protected environment:production) Permissions for actual resource creation, modification, deletion, and state file write

Using variables in module and provider versions (Terraform 1.15 and 1.17)

Previously, only string literals were allowed for source and version in a module block. Neither variables nor locals could be inserted, so teams with multiple environment directories had to manually modify the same version string in every file. Starting with Terraform 1.15, variables and locals can be used for a module's source and version, and 1.17 expanded this same approach to provider requirements (required_providers).

As it became more convenient, code review habits must also adapt. In the days when versions were literals, the line changing 5.16.0 to 6.0.0 was printed directly inside the module block. Today, modifying just a single line of locals can move all modules that read that value at once, but the affected module blocks do not appear in the PR diff. Reviewers must locate the places referencing that value and check the blast radius themselves.

source must be handled with even greater caution. Because a single value changes the very repository from which the module is downloaded, it is safer to leave source as a literal in production directories.

The infrastructure team at logistics startup Steadfast Logistics had envs/stage and envs/prod each define local.vpc_module_version. Because this flow updated the staging value first, observed it for a few days, and then updated the production value, it aligned directly with the directory separation principle. If both environments had read a single shared variable file, production would also have received the new version on the day the value was changed. This team created a Module Version Being Changed field in their PR template so reviewers would not have to trace values individually.

Even when moving to variables, the pinning principle remains the same. Exact versions are entered into module version variables. The distinction that providers are pinned via range constraints and .terraform.lock.hcl also remains intact.

Changes to plan in 1.17: -minimal-refresh and Terraform Policy

Terraform 1.17, released in October 2026, added two options to the plan phase.

One is the -minimal-refresh option. Default plan queries all resources in the state file again before calculating differences, but adding this option refreshes only resources for which changes are proposed. For a PR modifying a single CDN cache rule in a state file containing 600 resources, the query targets are reduced to just a few. This proportionally alleviates API rate limit issues experienced by teams managing large state files.

The trade-off is drift detection. Because resources whose code was not touched are excluded from querying, security group rules changed in the console by an on-call engineer last night will not appear in this plan. If this option is inserted into the plan -detailed-exitcode monitoring job running every morning, an exit code of 0 does not mean there is no drift.

Key point

Separate plan for PR verification and plan for drift monitoring into distinct jobs, and attach -minimal-refresh only to the PR side. For monitoring jobs, exhaustive querying is their primary duty.

The other is the general availability of Terraform Policy. Previously, one had to download experimental builds or enable experimental feature flags, but starting from 1.17.0, the -policies flag can be directly attached to plan, apply, and query in standard builds. If you decide to include policy checks in your pipeline, align Terraform across both CI runners and team members' laptops to 1.17.0 or higher. In older versions, -policies does not run without experimental builds, causing developers to overlook policy violations until pushing to CI.

Choosing licenses and distributions: Terraform BSL and OpenTofu 1.13

Terraform versions 1.6.0 and above are distributed under the Business Source License 1.1 (BSL). The BSL has a change date, meaning each version converts to MPL 2.0 four years after its release date. For instance, a version released in October 2026 converts to MPL 2.0 only in October 2030. OpenTofu uses the MPL 2.0 license.

Whether a company's use case conflicts with BSL terms is determined by the legal team reviewing the original license text. The engineer's responsibility is to provide the grounds for that determination. Keep an inventory of which tools and which versions are running across each repository and CI runner.

Teams using or intending to migrate to OpenTofu should first compare the changes in 1.13, released in late September 2026, against their own environments. While the convert function was added and Windows ARM64 became officially supported, some features were also removed.

Item Changes in 1.13 Check before upgrading
Provisioners Deprecation of winrm connection type Search for usages of type = "winrm"
macOS Requires 13 or higher OS versions of Mac runners and laptops
32-bit Last release series offering official 32-bit builds Schedule for migrating to 64-bit environments
providers lock Supports -oci-mirror argument Lock procedures for teams using OCI mirrors

If a team running Windows server bootstrapping with winrm connection provisioners merely upgrades the version, that step will no longer function. Change the connection method first before upgrading. If a team runs an internal build server on a macOS 12 Mac mini, upgrading the OS comes first.

Going deeper

Attack surface of PR-based infrastructure automation (Atlantis pattern) and plan file integrity

The workflow where "opening a PR automatically runs terraform plan, displays the output as a comment, and runs apply once a reviewer approves" is extremely convenient, but from an attacker's perspective, a very dangerous trap lies hidden.

terraform plan is not a simple syntax checker. Even during the plan phase, it downloads and executes external modules and provider code, evaluates data "external" data sources and local expressions, and reads the entire remote state file into memory.

What happens if you allow terraform plan to run automatically with production credentials attached on a PR submitted from an external fork or on branch code that has not yet undergone code review? With just a single line in a .tf file where a malicious PR author adds a data source that reads secrets from the state file and sends them to an external webhook, all secrets inside the production state file are already exfiltrated at the plan phase, even before running apply!

Therefore, a secure PR automation pipeline establishes three lines of defense:

  1. Do not automatically run workflows requiring cloud credentials on PRs submitted from external fork repositories.
  2. The plan role for a PR must possess only minimum read-only permissions that cannot modify actual resources, and PRs that change workflow files (.github/workflows/*) or backend configurations themselves must be protected so that they run only after review by an infrastructure administrator (utilizing Required Reviewers in GitHub Environments).
  3. To prevent other changes from intervening between the time the plan was reviewed and the time apply is actually executed (TOCTOU), verify the hash of the binary plan artifact generated by terraform plan -out=tfplan.binary so that terraform apply tfplan.binary applies only the precisely reviewed changes (at this time, because the tfplan.binary file also contains plaintext secrets just like the state file, it must never be uploaded to a public artifact repository).

Reducing the state file blast radius in large-scale infrastructure

In the early stages, it is easy to lump the network (VPC), database (RDS), Kubernetes/application cluster, and DNS/Cloudflare configurations into a single directory and a single terraform.tfstate file (monolithic state).

However, when resources grow into the hundreds, a single state file causes three major problems:

  • Slower plan speed and API rate limits: Every time a single plan runs, querying the current state of hundreds of resources via cloud APIs takes over 10 minutes and hits API call limits.
  • Lock bottleneck: While a frontend engineer runs a plan to modify a single CDN cache rule, a database engineer is blocked by the state lock and cannot perform any work.
  • Expanded blast radius: If someone mistakenly touches an application configuration and corrupts the state, the VPC and the production database are exposed to risk all at once.

The solution is state segmentation—splitting state files into layers according to change cadence, lifecycle, and owning team. For example, separate directories and state files into (1) 01-network (VPC, subnets, ZTNA connectors), which changes only a few times a year, (2) 02-data (RDS, S3, KMS), where data retention is the top priority, and (3) 03-app-edge (Cloudflare rules, application routing, workers), which changes multiple times a day. When lower layers need to reference a VPC ID or subnet ID from an upper layer, connecting only read-only references via the terraform_remote_state data source (or SSM Parameter Store / tag-based data lookups) instead of hardcoding completely confines the blast radius within each layer.

At work

Pine Light Mobility: DB deletion crisis caused by resource renaming and moved · prevent_destroy

A DevOps engineer at Pine Light Mobility, a company operating a logistics dispatch AI platform, took on a refactoring task to clean up Terraform code that had been hastily written in the early stages. He changed the plain resource name aws_db_instance.db1 in the root module to aws_db_instance.logistics_primary and submitted a PR that increased the storage size from 100GB to 200GB.

The final line of the terraform plan summary output by the CI pipeline read Plan: 1 to add, 0 to change, 1 to destroy. Thinking it was merely a minor change to increase storage capacity, the reviewer clicked the approve button without looking closely. Fortunately, right before the manual apply, a senior engineer skimmed the plan log once more and felt a chill down their spine. Terraform had interpreted the name change as "completely destroying (-) the existing production DB (db1) and creating (+) an empty new DB (logistics_primary)"! If it had been applied as-is, the production database containing hundreds of thousands of recent dispatch records would have vanished into thin air.

The team immediately halted the deployment and applied three measures:

  1. Zero-downtime address change with a moved block: They added moved { from = aws_db_instance.db1, to = aws_db_instance.logistics_primary } to the code. Running terraform plan again eliminated 1 to destroy, 1 to add, outputting a safe plan where the address moved inside the state file and only the storage size was modified in-place (~, 1 to change).
  2. Mandating prevent_destroy: They added lifecycle { prevent_destroy = true } to all production database, S3 bucket, and KMS key resources. Now, if someone touches an immutable attribute causing a replace (-/+), the build fails immediately with an error at the plan phase. If someone renames a resource or deletes the block, the lifecycle setting disappears with it, rendering this mechanism ineffective. Such changes are caught by the PR warnings in item 3.
  3. CI PR comment highlight: They modified the pipeline so that if even one to destroy or must be replaced (-/+) was included, the PR comment bot displayed a red warning banner and required separate approval from the infrastructure lead.

All Good Fintech: GitHub OIDC migration and drift normalization that ended the threat of leaked static AWS keys from former employees

Financial data analytics company All Good Fintech received two findings in a security audit. First, the AWS_SECRET_ACCESS_KEY registered in GitHub Actions was a long-term IAM user key issued in the name of an engineer who had left the company two years earlier, with no record of its last rotation. Second, 12 WAF and security group rules modified directly in the AWS console by the security team during the DDoS response last quarter were not reflected in the Terraform code, leaving the development team too afraid to run terraform apply for two months.

The infrastructure team resolved both problems in order over the course of one week:

Task Execution procedure Verification result
1. Absorbing drift Exhaustively inventoried all 12 manual console changes with terraform plan → Reviewed with the security team, wrote the 10 rules to be retained into .tf code identically, incorporated newly created resources via import blocks, and removed 2 unnecessary temporary rules Reached No changes when running terraform plan; thereafter monitored with plan -detailed-exitcode via a scheduled workflow every day at 09:00
2. Reorganizing S3 state locking Consolidated existing local/manual backends into an S3 backend with versioning and KMS encryption enabled (use_lockfile = true), and restricted state file read permissions to minimal roles Confirmed immediate queuing and blocking via .tflock upon concurrent execution
3. Transition to secretless OIDC Registered GitHub OIDC provider in AWS IAM → Created separate read role for PRs (plan) and apply role dedicated to ref:refs/heads/main (apply) → Deactivated and deleted existing long-term IAM user keys 0 long-term cloud secret keys stored in GitHub Secrets; all deployments operate exclusively with 1-hour expiring temporary tokens

Common mistakes

  1. "Because sensitive = true was added, passwords will not be visible even if the terraform.tfstate file is uploaded to an internal company shared folder or to Git." This is the most dangerous misconception. sensitive = true merely hides values in the terminal output, while the actual value is written in plain text inside the state file. You must never upload state files to Git, and you must protect them with strict access controls inside an encrypted remote backend.
  2. "The -/+ symbol in terraform plan means that the configuration is only being slightly modified, so you can run apply with peace of mind." In-place modification is indicated by the ~ symbol. -/+ means completely destroying the existing resource and creating a new one (Replace); therefore, if it appears on a database or storage resource, it is directly tied to catastrophic data loss.
  3. "When renaming a resource, if you simply change the name in the .tf file and execute apply, Terraform will take care of renaming it automatically." If you only change the resource identifier in code, Terraform deletes (-) the existing resource and creates (+) a new resource. You must write a moved block alongside it without fail to migrate the mapping in the state file.
  4. "Simply separating workspaces (terraform workspace new prod) will completely isolate the development environment and the production environment." CLI workspaces share the exact same code and the same backend storage configuration, making it very easy for an operator to mistake which workspace is currently active. For production environments, it is safe to separate directories, backends, and IAM roles.
  5. "When configuring GitHub Actions OIDC, it is secure as long as you only include aud: sts.amazonaws.com in the IAM trust policy." If you do not validate the sub (repository name and branch/environment) condition, workflows originating from other GitHub repositories can also intercept and assume (AssumeRole) your IAM role to use it.
  6. "Settings hurriedly changed in the console will be automatically detected and preserved by Terraform during the next deployment." Terraform treats the code (.tf) as the single source of truth (Source of Truth). If settings manually modified in the console (drift) are not reflected in the code, they will be mercilessly overwritten and lost upon the next apply.

Summary at a glance

Core topic Key sentences to remember for exams and practice
Declarative model and State .tf code declares the desired final state, and terraform.tfstate maps the code to actual cloud resource id values
Remote backends and locking State files are stored in a remote backend such as S3 with versioning and encryption enabled, and concurrent executions are locked using use_lockfile = true (or DynamoDB)
Distinguishing plan symbols + create, - destroy, ~ in-place modification (In-place), -/+ destroy and recreate (Replace, risk of data loss)
Accidental deletion safeguards Attach lifecycle { prevent_destroy = true } to core databases, buckets, and keys to block accidental deletion and replace in plan. However, if the resource block itself is deleted, this protection disappears along with it
Zero-downtime refactoring and incorporation Modifying names and module paths within code is handled with moved blocks, while incorporating manually created resources into code is handled with import blocks
State file security sensitive = true masks console output only. Because plain text remains in the state file, prohibit Git commits, utilize backend KMS encryption, and leverage Ephemeral and write-only attributes
Environment isolation For production, isolate the blast radius using separate directories, state files, and cloud accounts / IAM roles instead of sharing workspaces
Drift response Detect drift through regular plan -detailed-exitcode executions, revert unauthorized modifications with apply, and match No changes by reflecting legitimate hotfixes into code first
CI/CD OIDC Use AssumeRoleWithWebIdentity instead of long-term access keys, and validate aud as well as the exact sub (repository, main branch, and environment) in the trust policy

Check the official docs

Self-check

2-1. Explain the problems that can occur when two team members execute terraform apply simultaneously against the same infrastructure from their respective laptops, and state the two features (for locking and recovery readiness) that must be enabled in the AWS S3 backend to prevent them.

2-2. Explain the difference between the ~ symbol and the -/+ symbol prefixed to resources in the terraform plan output, and write the configuration block that must be placed inside the HCL code to prevent accidental execution of -/+ or - on an operational production database resource.

2-3. Explain what occurs if you rename an active production resource in the .tf code from aws_instance.app to aws_instance.api_server and run apply immediately afterward, and write the block that must be added to safely change only the name without any service interruption.

2-4. Explain why all secret values are leaked if the terraform.tfstate file is committed to a public Git repository even though sensitive = true was configured on variables, and write two or more security countermeasures to prevent the exposure of secrets from the state file.

2-5. During an early-morning outage, an on-call engineer directly added (hotfixed) a port rule to a security group in the AWS console, and the team decided to maintain this rule permanently going forward. Explain in sequential order how the Terraform code must be handled and what must be verified to ensure that this rule does not disappear during the next deployment.

2-6. Design task: You intend to run Terraform in GitHub Actions without long-term AWS access keys. Explain why the IAM roles must be separated between (1) the workflow that runs when a PR is opened and (2) the workflow that runs when merged into the main branch, and state the two claims that must be validated in the OIDC trust policy (Condition) of the production apply (apply) role.

Hands-on tasks

Exercise

Interpreting terraform plan risks and writing zero-downtime refactoring code (45 minutes)

  1. Assume that an operational database resource "aws_db_instance" "legacy_db" and an S3 bucket resource "aws_s3_bucket" "legacy_bucket" are currently declared in the root module.
  2. Write two moved blocks to relocate the names of the two resources to aws_db_instance.prod_primary and module.storage.aws_s3_bucket.prod_assets respectively, without deleting or recreating (-/+) them.
  3. Add lifecycle settings that prevent accidental deletion to both resource definitions, and write an S3 backend block (encrypt = true, use_lockfile = true) alongside them.
  4. List three checklist items to verify if aws_db_instance.prod_primary must be replaced (-/+) appears in a colleague's PR.

Done when: The from and to addresses of the moved blocks are exact, both prevent_destroy = true and the S3 locking settings are included, and the review criteria for identifying attributes that trigger replace (-/+) are explicitly specified.

Exercise

Designing a GitHub Actions OIDC least-privilege trust policy (Trust Policy) (45 minutes)

  1. Write the trust policy JSON documents respectively for two AWS IAM roles (tf-pr-plan-role, tf-main-apply-role) intended for the internal company repository trappist-org/cloud-infra that uses the name-based sub format.
  2. For both roles, specify the Action as sts:AssumeRoleWithWebIdentity, and check whether the aud condition is sts.amazonaws.com.
  3. Restrict the sub condition of tf-main-apply-role so that it matches only the main branch (repo:trappist-org/cloud-infra:ref:refs/heads/main) or the protected production environment (repo:trappist-org/cloud-infra:environment:production).
  4. Write an attack scenario in three sentences explaining why wildcards such as "repo:trappist-org/cloud-infra:*" must not be used in tf-main-apply-role.

Done when: The aud and sub conditions are accurately included in both IAM trust policy JSON documents, and the privilege hijacking scenario through a feature branch PR as well as the defense principles are explained.