DevOps, CI/CD and IaCVol. 8 · Part VIII
0 / 0

Shelves / DevOps, CI/CD and IaC

DL·94

Infrastructure as Code

Managing infrastructure as versioned, reviewed code: declarative versus imperative approaches, resources, providers, state, modules, variables, outputs, dependencies and drift; Terraform and OpenTofu in depth (configuration language, providers, resources and data sources, the dependency graph, plan/apply, state and remote backends with locking, modules and registries, import and refactoring, workspaces and environment layouts, testing, policy as code, secrets in state); then Ansible for configuration management, Packer for images, Pulumi for general-purpose languages, and CloudFormation, CDK and Bicep.

30 topics · ~23 min read · 32-question quiz
Updated Suggest a correction

Start here: plan, apply, and the state in between

Declare, plan, apply

Infrastructure as code (IaC) means describing infrastructure in files that are reviewed and versioned like application code, and letting a tool make reality match them. With Terraform/OpenTofu you write resources in HCL:

HCL
variable "env" { default = "dev" }

resource "aws_vpc" "main" {
  cidr_block = "10.40.0.0/16"
  tags       = { Name = "tiffin-${var.env}", owner = "platform" }
}

resource "aws_subnet" "app" {
  vpc_id            = aws_vpc.main.id              # a reference creates a dependency
  cidr_block        = "10.40.1.0/24"
  availability_zone = "ap-south-1a"
}

resource "aws_security_group" "web" { … ingress tcp/443 from 0.0.0.0/0 … }
resource "aws_s3_bucket" "menus" { bucket = "tiffin-menus-${var.env}" }
resource "aws_s3_bucket_versioning" "menus" { … Enabled … }

Then you ask for a plan (what would change) before an apply (make the changes):

Text
$ tofu plan
  # aws_s3_bucket.menus will be created
  # aws_s3_bucket_versioning.menus will be created
  # aws_security_group.web will be created
  # aws_subnet.app will be created
  # aws_vpc.main will be created
Plan: 5 to add, 0 to change, 0 to destroy.
$ tofu apply -auto-approve
aws_vpc.main: Creation complete after 0s [id=vpc-916031e2c01640e50]
aws_subnet.app: Creation complete after 0s [id=subnet-b9b81a043e97b5134]
aws_s3_bucket.menus: Creation complete after 1s [id=tiffin-menus-dev]
aws_security_group.web: Creation complete after 1s [id=sg-f1cd37924470d3b1b]
aws_s3_bucket_versioning.menus: Creation complete after 1s [id=tiffin-menus-dev]
Apply complete! Resources: 5 added, 0 changed, 0 destroyed.
$ tofu plan   # again
No changes. Your infrastructure matches the configuration.

OpenTofu built a dependency graph from the references (the subnet and security group needed the VPC's ID, so it came first; independent resources were created in parallel), and recorded what it created in a state file. Running the plan again showed no changes: applying the same code is idempotent.

Changes: in place or replace

Text
# change a tag
  # aws_vpc.main will be updated in-place
          ~ "owner" = "platform" -> "orders-team"
Plan: 0 to add, 1 to change, 0 to destroy.
# change the subnet range
  # aws_subnet.app must be replaced
      ~ cidr_block = "10.40.1.0/24" -> "10.40.2.0/24" # forces replacement
Plan: 1 to add, 1 to change, 1 to destroy.

A tag can be updated in place; a subnet's address range can't, so the plan says the subnet must be replaced (destroyed and recreated, taking anything inside it along). This is why the plan exists and why it's reviewed in pull requests: "1 to destroy" on a database is the line that saves your weekend.

The state

The state file maps each resource in your code to a real object (aws_vpc.main ↔ vpc-916031e2…) and records their attributes, so the tool knows what exists and what to change. On a team it lives in a shared backend (S3 with locking, GCS, Azure Blob, Terraform Cloud or another service) so two people can't apply at once, and it must be protected: it often contains secrets (the lab shows a database password inside it).

Tool Language Notes
Terraform / OpenTofu HCL Multi-cloud, huge provider ecosystem; OpenTofu adds state encryption
AWS CDK / CDKTF TypeScript, Python, Java, Go… Generates CloudFormation (or Terraform) from code
Pulumi General-purpose languages Its own engine and state
CloudFormation / Bicep / ARM YAML/JSON, Bicep Provider-native, state kept by the cloud
Crossplane Kubernetes resources Infrastructure reconciled by Kubernetes controllers
Ansible YAML playbooks Configuration of machines, procedural

How deep to go in infrastructure as code

Volume 17 defines six mastery levels. For this chapter they look like this; the chapter aims at L3 everywhere, and its lab at L4.

Level What you can do
L1 Explain declarative IaC, plan/apply and state
L2 Write modules with variables and outputs; use remote state with locking; review plans
L3 Explain the dependency graph, replacement rules, for_each vs count, import and refactoring
L4 Diagnose drift, state problems, unexpected replacements and provider errors
L5 Design module boundaries, environments, state layout and pipelines for IaC
L6 Run IaC across many teams: policy-as-code, drift detection, upgrades and governance

Why infrastructure as code

Infrastructure as code (IaC) means describing infrastructure (networks, clusters, databases, DNS, IAM, monitoring) in files that are versioned, reviewed and applied by tools, instead of clicking in consoles or running ad-hoc scripts. Benefits:

  • Reproducibility: create identical environments (dev, staging, prod, a new region) from the same code.
  • Review and audit: changes go through pull requests; history shows who changed what and why.
  • Speed and safety: a plan shows exactly what will change before it happens.
  • Disaster recovery: rebuild from code instead of memory.
  • Documentation: the code is the inventory.

Declarative versus imperative

Declarative Imperative
You write The desired end state ("a bucket named X with versioning on") The steps ("call CreateBucket, then PutBucketVersioning")
The tool Compares desired with actual, computes and executes a plan Executes your steps in order
Re-running Idempotent: no changes if already in the desired state Steps may fail or duplicate unless written carefully
Examples Terraform/OpenTofu, CloudFormation, Bicep, Kubernetes manifests, Pulumi (declarative model in imperative languages) Shell scripts, SDK scripts; Ansible tasks are imperative steps made idempotent by modules

Declarative tools are built around reconciliation, the same idea as Kubernetes controllers and GitOps (chapter 95): describe what you want; let the engine work out how.

Core vocabulary

Concept Meaning
Resource A managed infrastructure object (VPC, bucket, DNS record, IAM role)
Provider A plugin that knows how to talk to an API (AWS, Azure, GCP, Kubernetes, GitHub, Cloudflare, Datadog…)
State The tool's record of which real objects correspond to which resources in code, plus their last-known attributes
Module A reusable package of resources with inputs and outputs
Variable / input Parameters to a configuration or module
Output Values exported from a configuration or module (IDs, endpoints)
Dependency Ordering between resources, implicit (through references) or explicit
Drift Differences between real infrastructure and what the code and state say, caused by manual changes or external processes

Terraform and OpenTofu

Terraform (HashiCorp, 2014; now part of IBM) is the most widely used multi-cloud IaC tool. In 2023 HashiCorp changed its licence to the Business Source License; the community fork OpenTofu (Linux Foundation, MPL-2.0) followed. They share the language and most providers; by late 2026 Terraform is at 1.14 and OpenTofu at 1.12, and they have diverged in some features (OpenTofu: client-side state encryption, -exclude, provider for_each, early variable evaluation, OCI registry distribution; Terraform: terraform query / resource discovery, HCP Terraform Stacks). Everything in this chapter applies to both unless noted (tofu replaces terraform as the command).

The language (HCL)

Configurations are .tf files in a directory (a root module), written in HCL (HashiCorp Configuration Language):

HCL
terraform {
  required_version = ">= 1.10"
  required_providers {
    aws = { source = "hashicorp/aws", version = "~> 6.0" }   # pin provider major versions
  }
  backend "s3" {                                            # remote state (below)
    bucket       = "acme-tfstate-prod"
    key          = "network/terraform.tfstate"
    region       = "ap-south-1"
    use_lockfile = true                                     # native S3 locking (no DynamoDB table needed)
    encrypt      = true
  }
}

provider "aws" {
  region = var.region
  default_tags { tags = { managed_by = "terraform", team = "platform" } }
}

variable "region" {
  type    = string
  default = "ap-south-1"
}

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

locals {
  name = "shop-${var.environment}"
  azs  = slice(data.aws_availability_zones.available.names, 0, 3)
}

data "aws_availability_zones" "available" {               # data source: read existing information
  state = "available"
}

resource "aws_s3_bucket" "artifacts" {                    # resource: create and manage
  bucket = "${local.name}-artifacts"
}

resource "aws_s3_bucket_versioning" "artifacts" {
  bucket = aws_s3_bucket.artifacts.id                       # reference → implicit dependency
  versioning_configuration { status = "Enabled" }
}

output "artifacts_bucket" {
  value = aws_s3_bucket.artifacts.bucket
}

Language features:

  • Types: string, number, bool, list(...), map(...), set(...), object({...}), tuple, any; optional() attributes in objects.
  • Expressions: references (aws_vpc.main.id), conditionals (var.ha ? 3 : 1), for expressions ([for s in var.subnets : s.cidr]), splat (aws_instance.web[*].id), many built-in functions (cidrsubnet, jsonencode, templatefile, merge, lookup), and provider-defined functions.
  • Meta-arguments: count (N copies), for_each (one per map/set key; preferred, because stable keys mean adding or removing an item doesn't shift the others), depends_on (explicit dependency when no reference exists), provider (alias, e.g. a second region), and lifecycle:
HCL
resource "aws_db_instance" "main" {
  # …
  lifecycle {
    prevent_destroy       = true                  # plan fails if this would be destroyed
    create_before_destroy = true                  # replacement without gaps (where names allow)
    ignore_changes        = [password]            # managed elsewhere (e.g. rotation)
  }
}

resource "aws_iam_role" "service" {
  for_each           = toset(["orders", "payments", "catalog"])
  name               = "${each.key}-task"
  assume_role_policy = data.aws_iam_policy_document.ecs_assume.json
}
  • Validation: validation blocks on variables, precondition/postcondition on resources and data sources, and check blocks (assertions evaluated on every plan/apply, e.g. "the health endpoint returns 200") that warn without blocking.
  • Sensitive values: sensitive = true hides values in plan output; ephemeral values and resources (Terraform 1.10+) are never written to state or plan files, and write-only arguments let you pass secrets to providers without storing them.

Providers

A provider is a separate binary (written in Go with the plugin framework) that maps resource types to API calls: create, read, update, delete. Providers are downloaded from a registry (registry.terraform.io, registry.opentofu.org) and their exact versions and checksums are recorded in .terraform.lock.hcl, which you commit, so every machine uses the same provider builds.

There are thousands: clouds (AWS, AzureRM/AzAPI, Google), platforms (Kubernetes, Helm), SaaS (GitHub, Cloudflare, Datadog, PagerDuty, Okta, Snowflake), and utilities (random, tls, http). Anything with an API can be managed the same way.

The dependency graph and plan/apply

Terraform builds a directed acyclic graph of resources from references (and depends_on), then walks it, creating independent resources in parallel and dependent ones in order. Destroy order is the reverse.

configuration*.tf (desired) statelast known mapping real infrastructurevia provider APIs terraform plan① refresh actual② diff desired vs actual③ ordered action set plan (reviewed)+ create~ update in place-/+ replace- destroy terraform applygraph walk, parallel writes new state
Terraform's workflow. The configuration, the state file and the real infrastructure are compared; refresh reads actual attributes; plan computes the differences as a set of create, update, replace and destroy actions; apply executes them in dependency order and records the new state.
Shell
terraform init                  # download providers and modules, configure the backend
terraform fmt -recursive        # canonical formatting
terraform validate              # syntax and type checks
terraform plan -out=tfplan      # compute changes; save the exact plan
terraform show tfplan           # review (also -json for tooling)
terraform apply tfplan          # apply exactly what was reviewed
terraform plan -refresh-only    # show drift without proposing config changes
terraform destroy               # remove everything in this configuration (carefully!)

Read plans carefully: the dangerous lines are -/+ (replace: destroy and recreate, often because an immutable attribute changed: the database's identifier, a subnet's AZ) and - (destroy). In CI, post the plan to the pull request, require approval, and apply the saved plan file so what's applied is exactly what was reviewed.

State

State (terraform.tfstate, JSON) maps each resource address (aws_s3_bucket.artifacts) to a real object ID and its attributes. Terraform needs it to know what it manages, to compute diffs efficiently, to track dependencies for destroy, and to map renamed resources.

Rules for state:

  • Use a remote backend in any team setting: S3 (with native lockfiles), Azure Storage, GCS, HCP Terraform / Terraform Enterprise, Spacelift, env0, Scalr, or the pg and http backends. Never keep state only on a laptop or commit it to Git.
  • Locking prevents two applies at once from corrupting state: S3 use_lockfile (Terraform 1.11+ and OpenTofu), the older DynamoDB lock table, blob leases on Azure, built-in locks on GCS and HCP Terraform. terraform force-unlock only when you're sure no apply is running.
  • State contains secrets (database passwords, private keys generated by tls_private_key, any sensitive attribute) in plain text. Encrypt the backend at rest, restrict access tightly, enable versioning (to recover from corruption), or use OpenTofu's client-side state encryption; prefer ephemeral values and write-only arguments so secrets never land in state.
  • Split state by blast radius and ownership: network, shared platform, data stores, and each service separately. Huge single states are slow and risky (one bad plan touches everything). Share values between states via outputs read with terraform_remote_state data sources, or better, via lookups (data sources by tag/name) or a parameter store.
  • State commands for surgery: terraform state list, state show, state mv (now usually replaced by moved blocks), state rm (stop managing without destroying; or removed blocks).

Modules

A module is a directory of .tf files with variables (inputs) and outputs. The root configuration calls child modules:

HCL
module "orders_service" {
  source  = "app.terraform.io/acme/ecs-service/aws"   # private registry; or git::https://…?ref=v3.2.0
  version = "~> 3.2"

  name            = "orders"
  image_digest    = var.orders_digest
  cpu             = 512
  memory          = 1024
  desired_count   = 3
  vpc_id          = data.aws_vpc.shop.id
  private_subnets = data.aws_subnets.private.ids
  alb_listener    = data.aws_lb_listener.https.arn
  path_patterns   = ["/orders/*"]
}

output "orders_url" { value = module.orders_service.url }

Module design guidance:

  • Encapsulate an opinionated unit ("an ECS service with our logging, alarms and IAM conventions"), not a thin wrapper around one resource.
  • Small, explicit interface: typed variables with validation and descriptions; outputs for everything consumers need.
  • Version modules (Git tags or a registry) and pin versions in callers; publish changelogs.
  • Avoid deep nesting (modules calling modules calling modules), which makes changes hard to trace.
  • Community modules (e.g. terraform-aws-modules/vpc/aws) save time; review them like any dependency.

Import, refactoring and migration

Bringing existing infrastructure under management, and reorganising code without destroying things:

HCL
# Adopt an existing bucket created by hand (Terraform 1.5+): plan shows "import", then apply records it in state
import {
  to = aws_s3_bucket.legacy_reports
  id = "acme-reports-2019"
}
# terraform plan -generate-config-out=generated.tf   → writes a starting resource block for you

# Rename or move into a module without destroy/recreate
moved {
  from = aws_s3_bucket.artifacts
  to   = module.storage.aws_s3_bucket.artifacts
}

# Stop managing a resource without destroying it
removed {
  from = aws_s3_bucket.old_logs
  lifecycle { destroy = false }
}

Tools for bulk adoption: terraform query with list resources (Terraform 1.14) and for_each import blocks (OpenTofu) for discovering and importing many resources; Terraformer and cloud-specific exporters (Azure aztfexport, GCP bulk export) generate code from existing estates. Migrating from Terraform to OpenTofu is mostly swapping the binary and provider registry; read the compatibility notes for your versions.

Workspaces and environment layouts

Ways to manage dev/staging/prod:

Approach How Trade-off
CLI workspaces terraform workspace new staging: same code, separate state per workspace; terraform.workspace in expressions Simple, but environments must be nearly identical, and it's easy to apply to the wrong workspace
Directory per environment envs/dev, envs/prod each a root module calling shared modules with different inputs Explicit, visible differences, separate backends/credentials; some duplication (reduced with tooling)
Terragrunt Wrapper that generates backends and DRYs up per-environment configuration and dependencies between stacks Popular for large estates; another tool to learn
HCP Terraform workspaces / Stacks, Spacelift stacks, env0, Atlantis Remote runs per workspace with variables, VCS triggers, policy checks Collaboration features; Atlantis is open source and runs plans in PR comments

Most teams favour separate root modules per environment and component, each with its own state, credentials (prod applied only by the pipeline's prod role) and approval gates.

Testing and quality

  • Static: fmt, validate, TFLint (provider-aware linting), security and misconfiguration scanners (Trivy config, Checkov, KICS).
  • Native tests: terraform test / tofu test run *.tftest.hcl files with run blocks that plan or apply and assert on results, with mocked providers for fast unit-style tests.
  • Integration tests: Terratest (Go) applies real infrastructure in a sandbox account, checks it, and destroys it.
  • Cost estimation: Infracost comments the monthly cost delta on pull requests.
HCL
# tests/bucket.tftest.hcl
run "versioning_enabled" {
  command = plan
  variables { environment = "dev" }
  assert {
    condition     = aws_s3_bucket_versioning.artifacts.versioning_configuration[0].status == "Enabled"
    error_message = "Artifact bucket must have versioning enabled."
  }
}

Policy as code

Policy as code evaluates plans (or configurations) against rules before apply:

  • OPA (Open Policy Agent) with Rego, via Conftest or tools that feed it terraform show -json output; used by Spacelift, env0, Scalr and HCP Terraform.
  • Sentinel (HashiCorp's policy language in HCP Terraform/Enterprise), with advisory, soft-mandatory and hard-mandatory levels.
  • Checkov/Trivy custom policies, cloud-native guardrails (SCPs, Azure Policy, organisation policies) as the last line of defence at the API.
Rego
# policy/s3.rego (Conftest): deny S3 buckets without versioning in the plan
package main

deny contains msg if {
  some r in input.resource_changes
  r.type == "aws_s3_bucket_versioning"
  r.change.after.versioning_configuration[_].status != "Enabled"
  msg := sprintf("%s must enable versioning", [r.address])
}

Drift

Drift happens when someone changes infrastructure outside IaC (console hotfix, a script, another tool), or when the cloud changes defaults. Handle it by:

  • Detecting regularly: scheduled terraform plan -detailed-exitcode (exit code 2 = changes) or -refresh-only in CI, HCP Terraform drift detection, AWS Config / Azure Policy / Cloud Asset Inventory.
  • Deciding: either update code to match reality (the change was right) or re-apply to restore the declared state.
  • Preventing: read-only console access in production, break-glass procedures that are followed by codifying the change, and a single pipeline path to apply.

Beyond Terraform

Ansible: configuration management

Ansible (Red Hat) configures servers (packages, files, services, users) and orchestrates multi-step operations, agentless over SSH (or WinRM), with YAML playbooks:

  • Inventory: hosts and groups (static files or dynamic inventory plugins from AWS, Azure, GCP, VMware).
  • Tasks use modules (apt, dnf, copy, template (Jinja2), systemd_service, user, cloud modules) that are idempotent: they check state and change only what's needed, reporting changed or ok.
  • Roles package tasks, templates, handlers and defaults for reuse (Ansible Galaxy, collections); handlers run once when notified (restart a service after its config changed).
  • --check --diff for dry runs; Ansible Vault encrypts secrets in files; Molecule tests roles.
YAML
# playbook.yml: configure a fleet of VMs running a Go service
- hosts: orders_vms
  become: true
  vars:
    orders_version: "1.4.2"
  tasks:
    - name: Install runtime packages
      ansible.builtin.apt:
        name: [ca-certificates, chrony]
        state: present
        update_cache: true
    - name: Install the binary
      ansible.builtin.get_url:
        url: "https://artifacts.acme.dev/orders/{{ orders_version }}/orders-linux-arm64"
        dest: /opt/orders/bin/orders
        mode: "0755"
        checksum: "sha256:{{ orders_sha256 }}"
      notify: Restart orders
    - name: Render the systemd unit
      ansible.builtin.template:
        src: orders.service.j2
        dest: /etc/systemd/system/orders.service
      notify: Restart orders
  handlers:
    - name: Restart orders
      ansible.builtin.systemd_service:
        name: orders
        state: restarted
        daemon_reload: true

Terraform provisions infrastructure; Ansible configures what runs on it. In container- and image-based architectures, much of Ansible's former role moves into image builds (Packer, Dockerfiles), and Ansible is used for VMs, network devices, on-premises estates and operational runbooks. Alternatives: Chef, Puppet, Salt (agent-based, older), and cloud-init for first-boot configuration.

Packer: machine images

Packer (HashiCorp) builds machine images (AMIs, Azure images, GCE images, VMware templates, Docker images) from a template: start a temporary VM from a base image, run provisioners (shell, Ansible), and snapshot the result. It's the standard way to create golden images for immutable infrastructure (Vol. 7 ch. 86).

HCL
# orders.pkr.hcl
packer {
  required_plugins {
    amazon  = { source = "github.com/hashicorp/amazon",  version = "~> 1.3" }
    ansible = { source = "github.com/hashicorp/ansible", version = "~> 1.1" }
  }
}

source "amazon-ebs" "al2023_arm" {
  region        = "ap-south-1"
  instance_type = "t4g.small"
  ssh_username  = "ec2-user"
  ami_name      = "orders-{{timestamp}}"
  source_ami_filter {
    filters     = { name = "al2023-ami-*-arm64", virtualization-type = "hvm" }
    owners      = ["amazon"]
    most_recent = true
  }
  metadata_options { http_tokens = "required" }      # IMDSv2 on the image
}

build {
  sources = ["source.amazon-ebs.al2023_arm"]
  provisioner "ansible" { playbook_file = "playbook.yml" }
}

Pair image builds with vulnerability scanning and a scheduled rebuild, so patched images flow through the pipeline regularly.

Pulumi: IaC in general-purpose languages

Pulumi lets you write infrastructure in TypeScript, Python, Go, C#/.NET, Java or YAML, while keeping a declarative engine with state, previews (pulumi preview) and updates (pulumi up). Benefits: real programming constructs (loops, functions, classes, packages, unit tests in your usual framework), IDE support, sharing abstractions as libraries (component resources). Risks: too much cleverness makes infrastructure code hard to review; keep it declarative in spirit. Pulumi can use Terraform providers (via bridges) and manages state in Pulumi Cloud or self-managed backends (S3, Azure Blob, GCS).

Go
// Go (Pulumi, pulumi-aws v7 resource names): versioned bucket with an export
func main() {
    pulumi.Run(func(ctx *pulumi.Context) error {
        bucket, err := s3.NewBucket(ctx, "artifacts", nil)
        if err != nil { return err }
        _, err = s3.NewBucketVersioning(ctx, "artifacts", &s3.BucketVersioningArgs{
            Bucket: bucket.ID(),
            VersioningConfiguration: &s3.BucketVersioningVersioningConfigurationArgs{Status: pulumi.String("Enabled")},
        })
        if err != nil { return err }
        ctx.Export("bucket", bucket.Bucket)
        return nil
    })
}

CDK for Terraform (CDKTF) offered similar ideas on Terraform; HashiCorp deprecated it in 2025, so prefer HCL, Pulumi or AWS CDK for new work.

CloudFormation, CDK and Bicep

Cloud-native IaC tools manage only their own cloud, but integrate deeply and need no separate state (the service keeps it):

  • AWS CloudFormation: JSON/YAML templates deployed as stacks; change sets preview changes; drift detection; StackSets for many accounts/regions; automatic rollback on failure. AWS CDK (TypeScript, Python, Java, C#, Go) synthesises CloudFormation from code, with high-level constructs (Vol. 7 ch. 90 example).
  • Azure Bicep: a concise language compiling to ARM templates, deployed to a scope (resource group, subscription, management group); what-if previews; deployment stacks manage lifecycle and deny-assignments; Azure Verified Modules provide vetted building blocks.
  • Google Cloud Infrastructure Manager runs Terraform as a managed service; Config Connector manages GCP resources as Kubernetes objects.
  • Crossplane (CNCF) manages cloud resources through Kubernetes CRDs with composition, applying GitOps (chapter 95) to infrastructure.

Choosing

Situation Good fit
Multi-cloud or many SaaS providers, large community Terraform or OpenTofu
Open-source licence and community governance matter, or state encryption OpenTofu
Developers want real languages and testing Pulumi, AWS CDK
AWS-only, deep integration, no state management CloudFormation / CDK
Azure-only Bicep (with deployment stacks)
Kubernetes-centric platform team Crossplane, or Terraform with GitOps controllers
OS configuration of VMs, network devices, operational runbooks Ansible
Golden images Packer (or EC2 Image Builder, Azure Image Builder)

Whatever you choose: everything in Git, plans reviewed in pull requests, applies only through pipelines with environment-scoped credentials, state protected, drift detected, and policies checked before changes reach the cloud.

Lab: drift, state, keys and refactoring

OpenTofu 1.13 with the AWS provider 6.20 and the random provider 3.7, against the moto emulator (reset before the lab); boto3 plays "someone using the console".

Experiment 1: drift

A database security group allows PostgreSQL only from inside the VPC. Someone opens it to the internet by hand ("temporary debug"):

Text
someone opened the database port to 0.0.0.0/0 in the console ('temporary debug')
$ tofu plan -refresh-only
Note: Objects have changed outside of OpenTofu
                  + "0.0.0.0/0",
$ tofu plan
  # aws_security_group.db will be updated in-place
                  - "0.0.0.0/0",
Plan: 0 to add, 1 to change, 0 to destroy.
$ tofu apply
Apply complete! Resources: 0 added, 1 changed, 0 destroyed.

The plan refreshed real state, noticed the manual change and proposed reverting it to the code. That's the value of IaC beyond the first deploy: the code is the definition, and drift (manual changes, other tools, emergency fixes) becomes visible. Run plans on a schedule to detect drift, and lock down console write access in production so the pipeline is the only path for changes.

Experiment 2: secrets in state, and state encryption

A random_password for a database, alongside the network:

Text
terraform.tfstate: 6914 bytes, 4 resources
the database password in plain text in the state: 1 occurrence(s) ("8f3o…")
after enabling OpenTofu state encryption: password occurrences in the state file: 0; first bytes: {"serial":4,"lineage":"927af33d-…"

The password sat in the state in plain text, as does anything a provider returns (database passwords, private keys, connection strings), even when outputs are marked sensitive (that only hides them from the console). OpenTofu's state encryption (terraform { encryption { … } }, here AES-GCM with a PBKDF2 passphrase; KMS-based key providers are available) encrypted the payload, leaving only metadata readable, and the configured fallback migrated the existing plain state on the next apply. With Terraform, rely on the backend: encrypted S3 buckets with tight IAM, or a managed service. Better still, keep secrets out of state: let the database generate and manage its own password (AWS RDS manage_master_user_password) or read secrets at run time from a secret store.

Experiment 3: count versus for_each

Three subnets, one per zone; then the middle zone is removed from the list:

Text
count, removing the middle zone:
     # aws_subnet.s[1] must be replaced
     # aws_subnet.s[2] will be destroyed
     # (because index [2] is out of range for count)
   Plan: 1 to add, 0 to change, 2 to destroy.
for_each, removing the middle zone:
     # aws_subnet.s["b"] will be destroyed
     # (because key ["b"] is not in for_each map)
   Plan: 0 to add, 0 to change, 1 to destroy.

With count, resources are identified by position: removing item 1 shifted zone c from index 2 to index 1, so OpenTofu replaced subnet 1 (with zone c's settings) and destroyed subnet 2, destroying a subnet that should have been untouched and everything in it. With for_each, resources are identified by key, so only "b" went. Use for_each with stable keys for collections; keep count for "zero or one" toggles.

Experiment 4: import and moved blocks

A bucket created by hand is adopted; then a resource is renamed in code:

Text
import block for a bucket created by hand:
     # aws_s3_bucket.uploads will be imported
     # (imported from "legacy-uploads")
   Plan: 1 to import, 0 to add, 0 to change, 0 to destroy.
renaming aws_s3_bucket.b to .state_demo without a moved block:
     # aws_s3_bucket.b will be destroyed
     # aws_s3_bucket.state_demo will be created
   Plan: 1 to add, 0 to change, 1 to destroy.
with a moved block:
     # aws_s3_bucket.b has moved to aws_s3_bucket.state_demo
   Plan: 0 to add, 0 to change, 0 to destroy.

import blocks bring existing resources under management through a reviewable plan (no more one-off terraform import commands). And because state maps addresses to objects, renaming a resource in code looks like deleting one resource and creating another: for a bucket full of data, that's a disaster. A moved block tells the tool it's the same object, so refactoring (renames, moving into modules, count to for_each) changes nothing real.

Try it yourself

  1. Put the state in an S3 backend on moto with a lockfile (use_lockfile = true) and run two applies at once.
  2. Add a prevent_destroy lifecycle rule to the database security group and try experiment 3's mistake against it.
  3. Turn the VPC into a module with inputs and outputs, and use moved blocks to refactor without changes.
  4. Write a policy with OPA/conftest that fails a plan (as JSON) if any security group allows 0.0.0.0/0 on a port other than 443.

Revision sheet: infrastructure as code

Key ideas

  • Why IaC: reviewable, versioned, reproducible infrastructure; drift detection; environments from the same code.
  • Terraform/OpenTofu: providers, resources, data sources, variables, locals, outputs, modules, expressions and functions, for_each/count, depends_on, lifecycle (prevent_destroy, create_before_destroy, ignore_changes), workspaces.
  • Workflow: init, plan (refresh, diff), apply, destroy; plan files; plans in pull requests; automation with locks.
  • State: mapping code to real objects; remote backends with locking; sensitivity and encryption; state mv/rm, import and moved blocks; splitting state by blast radius.
  • Beyond Terraform: CDK/CDKTF, Pulumi, CloudFormation, Bicep, Crossplane, Ansible for configuration; policy-as-code (OPA/conftest, Sentinel, Checkov).
  • Practices: small state files per component and environment, pinned provider versions with lock files, modules with clear interfaces, scheduled drift detection, no console changes in production.

Numbers to remember

  • Lab: a console change was detected and reverted by the next plan; a password appeared in plain-text state until encryption; count destroyed 2 and created 1 where for_each destroyed 1; a rename without moved planned destroy+create, with moved 0 changes.

Pitfalls

  • Committing state files or .tfvars with secrets.
  • One giant state for everything.
  • count over lists that change order.
  • Renames without moved blocks.
  • Unpinned providers; skipping plan review.
  • Manual console fixes in production.

Glossary

  • Provider: plugin translating resources into API calls.
  • Plan: computed set of actions to reach the desired state.
  • State: record mapping code addresses to real resources.
  • Drift: differences between real infrastructure and code.
  • Module: reusable group of resources with inputs and outputs.
  • Backend: where state is stored and locked.