Lesson 8: Infrastructure as Code and Environment Automation
Lesson opener
In one line: Infrastructure as Code replaces manual cloud console clicks with version-controlled, peer-reviewed configuration files that make environments reproducible, auditable, and safe to change.
Why it matters: At Northline, a staging environment drifted from production for four months because an engineer added a firewall rule manually during an incident and never documented it. The next time a production incident required exactly that rule, it was missing. IaC makes "it is configured the same way everywhere" a provable fact, not an assumption.
Before this lesson: You should understand cloud environments and resource types (#cloud1, #cloud8), secrets management (#cyber5, #cloud11), Kubernetes infrastructure concepts (#devops7), and CI/CD pipelines (#devops1–4). The Terraform concepts in this lesson use real workflow patterns; you do not need a cloud account to follow the exercises.
Learning objectives
By the end of this lesson you will be able to:
- Explain the difference between declarative and imperative infrastructure management and why declarative is preferred for production.
- Describe the core Terraform concepts: providers, resources, variables, outputs, modules, state, and remote backends.
- Explain state locking, drift detection, and the consequences of bypassing them.
- Separate environments using workspaces or directory-per-environment patterns.
- Integrate
planandapplyinto a CI/CD review workflow with human approval. - Handle secrets correctly in an IaC codebase — what never to commit and how to inject values.
- Describe policy-as-code awareness (what it is and why it matters).
- Validate infrastructure changes before and after applying them.
Lesson deliverable: An annotated Terraform module skeleton for a Northline staging environment (VPC, compute instance group, and secrets reference), with a written explanation of the state management strategy, environment separation approach, and secret handling.
Prerequisites
| Concept | Where covered |
|---|---|
| Cloud resource types and regions | #cloud1, #cloud8 |
| Secrets management | #cyber5, #cloud11 |
| CI/CD pipeline gates and approvals | #devops1–4, #devops5 |
| Kubernetes cluster concepts | #devops7 |
| Architecture review and change risk | #sad5, #sad9 |
Plain English: what is Infrastructure as Code?
The two models
Imperative: You tell the system how to reach the desired state step by step. "Create a VM. Now attach a disk. Now open port 443. Now add this firewall rule." If step 3 fails halfway through, the system may be in an unknown intermediate state.
Declarative: You describe what the desired state is and let the tool figure out how to get there. "I want a VM with a disk, port 443 open, and this firewall rule." The tool compares what exists today against what you declared and calculates the smallest set of changes needed.
Terraform is declarative. The configuration file is the authoritative description of what should exist. Terraform's job is to make reality match that description.
The analogy
Think of a declarative IaC file as a floor plan for a building. The floor plan says "there should be three rooms with these dimensions." The construction crew (Terraform) figures out whether to knock down walls, build new ones, or leave others unchanged. If you want a new room, you update the floor plan and re-run the crew — you do not call individual workers and micromanage each nail.
The floor plan (your IaC code) lives in version control. Every change is a pull request, reviewed by peers, and merged before the crew touches anything.
Terraform core concepts
Providers
A provider is a plugin that translates Terraform's resource definitions into API calls for a specific platform.
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0" # Pin versions; unpinned providers introduce breaking changes
}
}
}
provider "aws" {
region = var.aws_region
# Credentials come from the environment (IAM role, environment variables)
# NEVER hardcode credentials here
}⚠️ Always pin provider versions. An unpinned provider can silently upgrade and change behaviour in your CI pipeline on a day you did not plan for it.
Resources
A resource is a single infrastructure object managed by Terraform.
resource "aws_security_group" "billing_api" {
name = "billing-api-${var.environment}"
description = "Allow HTTPS inbound for billing-api"
vpc_id = aws_vpc.northline.id
ingress {
from_port = 443
to_port = 443
protocol = "tcp"
cidr_blocks = ["10.0.0.0/8"] # Internal only; never 0.0.0.0/0 without review
}
egress {
from_port = 0
to_port = 0
protocol = "-1"
cidr_blocks = ["0.0.0.0/0"]
}
tags = {
Environment = var.environment
Owner = "platform-team"
ManagedBy = "terraform"
}
}Variables and outputs
Variables parameterise a configuration so the same code runs in multiple environments with different values.
variable "environment" {
description = "Deployment environment: dev, staging, or production"
type = string
validation {
condition = contains(["dev", "staging", "production"], var.environment)
error_message = "environment must be dev, staging, or production."
}
}
variable "instance_count" {
description = "Number of API instances to run"
type = number
default = 2
}Outputs expose values from a module or root configuration for use by other modules or for display after apply.
output "billing_api_security_group_id" {
description = "Security group ID for billing-api; used by RDS module"
value = aws_security_group.billing_api.id
}Modules
A module is a reusable group of resources. Northline's platform team maintains a northline-vpc module that every team uses — it encodes company-standard CIDR ranges, flow log configuration, and tagging conventions.
module "northline_vpc" {
source = "git::https://github.com/northline-internal/terraform-modules//vpc?ref=v2.1.0"
environment = var.environment
cidr_block = var.vpc_cidr
}Pinning module versions with a ref tag is as important as pinning provider versions. An unpinned ?ref=main means your infrastructure can change when someone merges an unrelated update to the module repo.
State
Terraform maintains a state file (terraform.tfstate) that records the mapping between your configuration and the real cloud resources. This is how Terraform knows what already exists and what needs to change.
State is sensitive. It contains resource IDs, ARNs, and sometimes output values that include sensitive data. Never commit the state file to version control. Store it in a remote backend with encryption.
terraform {
backend "s3" {
bucket = "northline-terraform-state"
key = "billing-api/production/terraform.tfstate"
region = "eu-west-1"
encrypt = true
dynamodb_table = "northline-terraform-locks" # State locking
}
}State locking
When Terraform runs plan or apply, it acquires a lock on the state file. This prevents two simultaneous applies from corrupting the state. At Northline, the DynamoDB table stores the lock.
Never force-unlock state without understanding why it is locked. A stale lock (from a crashed apply) can be safely unlocked, but unlocking during an active apply causes corruption. Always investigate before using
terraform force-unlock.
Drift
Drift occurs when someone makes a manual change to a cloud resource outside of Terraform (e.g., modifying a firewall rule in the AWS console). The next terraform plan detects the difference between the state file and reality and proposes to revert the manual change.
Detecting drift is a feature, not a bug. Northline runs terraform plan in CI every night to detect drift and alert the platform team. Drift is never silently accepted — it is either incorporated into the IaC (the manual change was intentional and should become code) or reverted (it was accidental).
Terraform limitations: Terraform manages what it knows about. Resources created outside Terraform (by other tools or by the cloud provider automatically) are invisible to it unless explicitly imported. State can become inconsistent after provider upgrades or resource replacements. Always review the plan output carefully before applying.
Plan and apply
terraform plan is a dry run. It shows exactly what Terraform will create, change, or destroy before touching anything. Always review the plan before apply. A plan that shows an unexpected destroy action should stop the workflow until the cause is understood.
terraform apply executes the plan. In Northline's CI pipeline, apply is a separate step that requires human approval (see #devops5 gate patterns) — the plan runs automatically, but apply requires a named sign-off.
# Generate and save a plan file
terraform plan -out=tfplan
# Human reviews the plan output
# After approval, apply exactly the saved plan (no surprises)
terraform apply tfplanApplying from a saved plan file ensures that what the reviewer approved is exactly what runs. Applying without a saved plan allows changes to drift between review and execution.
Walkthrough: Northline's IaC workflow
Business objective
Provision a staging environment for the billing-api service: a VPC, a security group, an EC2 auto-scaling group (or equivalent), and a reference to the database credentials stored in the secrets manager.
Owners
| Role | Responsibility |
|---|---|
| Platform engineer | Writes and maintains IaC modules; reviews all apply requests |
| Backend engineer | Consumes modules; writes service-specific resources |
| Security engineer | Reviews security group rules, IAM policies, secret access (#cyber9) |
| Cost owner | Reviews resource types and sizes; tags for cost allocation (#cloud8) |
Environment separation
Northline uses a directory-per-environment pattern rather than workspaces, because it makes it impossible to accidentally apply production changes when targeting staging:
infrastructure/
├── modules/
│ ├── northline-vpc/
│ └── northline-asg/
└── environments/
├── dev/
│ ├── main.tf
│ ├── variables.tf
│ └── terraform.tfvars ← non-sensitive values only
├── staging/
│ ├── main.tf
│ ├── variables.tf
│ └── terraform.tfvars
└── production/
├── main.tf
├── variables.tf
└── terraform.tfvarsEach environment has its own backend configuration pointing to a separate state file. CI/CD pipeline jobs are scoped to one environment directory; a staging pipeline cannot accidentally apply to production.
⚠️ Terraform workspaces are an alternative approach. They share the same code but use separate state files per workspace. Northline prefers directory-per-environment for stronger isolation, but workspaces are common in smaller teams. Evaluate the trade-off for your context.
Secrets in IaC: what never to commit
| Forbidden | Why | Alternative |
|---|---|---|
Cloud credentials in .tf files | Committed to version control; exposed in CI logs | Use IAM roles, OIDC federation, or environment variables injected by CI |
Database passwords in terraform.tfvars | .tfvars files are often committed | Reference a secrets manager secret by ARN; never store the value |
API tokens as resource default values | terraform.tfstate stores applied values | Same: reference, never store |
Sensitive outputs without sensitive = true | Printed in CI logs | Mark with sensitive = true; suppress from plan output |
# Reference the secret by ARN — never store the value in IaC
data "aws_secretsmanager_secret_version" "db_password" {
secret_id = "billing/production/db-password"
}
# Pass the ARN reference to the resource; the value is resolved at runtime
resource "aws_db_instance" "billing" {
# ...
password = data.aws_secretsmanager_secret_version.db_password.secret_string
# Note: this value appears in the state file (encrypted at rest)
# Mark the output as sensitive to suppress log printing
}
output "db_endpoint" {
value = aws_db_instance.billing.endpoint
sensitive = false # Not sensitive; safe to display
}Policy as code (awareness level)
Policy as code tools (Sentinel, Open Policy Agent, Checkov) evaluate Terraform plans against organisational rules before apply. Examples of Northline policies:
- No security group with
0.0.0.0/0ingress on port 22 or 3389. - All resources must have
EnvironmentandOwnertags. - S3 buckets must have encryption enabled.
- No public EC2 instances without a documented exception.
⚠️ Policy-as-code tooling is environment-dependent — confirm which tool (if any) your pipeline uses. The concept is the same: the policy runs after plan and before human approval, blocking non-compliant changes automatically.
CI/CD review workflow
Engineer creates PR with IaC changes
→ CI: terraform fmt -check (style)
→ CI: terraform validate (syntax)
→ CI: terraform plan -out=tfplan (dry run; output posted to PR as comment)
→ CI: policy-as-code scan (Checkov or equivalent)
→ Human: peer review of plan output + code
→ Human: platform engineer approves
→ CI: terraform apply tfplan (apply the exact saved plan)
→ CI: validation tests run (see below)
→ PR merged; plan and apply logs stored as artifactsThis workflow mirrors the deployment strategy gate pattern from #devops5: automated checks, then a named human approval, then execution.
Validation before and after changes
Before (in the plan review):
- Does the plan show any unexpected destroys?
- Are resource types and sizes appropriate for the environment?
- Are security group rules correctly scoped?
- Does the plan output contain any sensitive values in plaintext?
After (post-apply):
terraform planagain immediately after apply: should show "No changes." If it shows changes, something went wrong.- Smoke tests against the provisioned resources (can the API reach its database? Is the load balancer responding?).
- Drift check: run plan 24 hours later and confirm no drift was introduced.
Rollback limitations
Terraform does not have a built-in "rollback" command. Rollback means reverting your IaC code to a previous version and running
applyagain. This works for most changes but has important limitations:- Destroyed resources (databases, S3 buckets with objects) cannot be recreated identically from IaC alone. Data is gone.
- Provider-managed changes (e.g., auto-minor-version upgrades on a managed database) are invisible to Terraform.
- State file corruption from a failed apply requires careful manual remediation (see
terraform statesubcommands).Always run
terraform planbefore reverting and review what "rollback" will actually do. For databases and stateful resources, the rollback plan involves backups and restoration procedures, not just re-running Terraform.
Worked examples
Example A: Adding a new environment variable to all environments
An engineer needs to add a MAX_CONNECTIONS variable to all three environments. They:
- Add it as a variable in the shared module with a sensible default.
- Override the value in
production/terraform.tfvars(higher limit) andstaging/terraform.tfvars(lower limit). - Open a PR; CI runs plan for each environment; the plans show only the addition.
- Platform engineer reviews, approves. CI applies, starting with dev, then staging, then production (separate pipeline jobs with separate approvals).
No manual console changes. No drift. Every environment's configuration is visible in the PR diff.
Example B: Importing an unmanaged resource
The networking team discovered an S3 bucket created manually six months ago that stores billing reports. It is not in Terraform.
# Import the existing resource into Terraform state
terraform import aws_s3_bucket.billing_reports northline-billing-reports-prod
# Now add the resource definition to main.tf
# Run terraform plan — should show "No changes" if the config matches realityAfter import, the resource is managed by Terraform. Future changes go through the IaC workflow. The import is documented in the commit message with the reason ("Adopted pre-existing resource; created by X on date Y during incident Z").
Failure chain: the midnight state corruption
Two engineers simultaneously run terraform apply on production
→ No state locking configured (DynamoDB table missing)
→ Both applies read the same state file
→ Both calculate the same "create load balancer" action
→ Two load balancers created; only one expected
→ Second apply writes state file: records one load balancer
→ First load balancer exists in cloud but not in state: orphaned resource
→ Resources cost money and expose an attack surface but are unmanaged
→ Post-incident: DynamoDB locking enabled; CI serialises apply jobsState locking is not a nice-to-have. It is a correctness requirement for any team with more than one person.
Guided exercise
Scenario: A Northline team inherits an AWS environment with three resources created manually: a VPC (vpc-0abc1234), a subnet (subnet-0def5678), and a security group (sg-0ghi9012). They want to bring all three under Terraform management.
Step 1: Write the terraform import commands for all three resources (use placeholder resource names like aws_vpc.main, aws_subnet.primary, aws_security_group.api).
Step 2: After import, terraform plan shows that the security group has an ingress rule allowing 0.0.0.0/0 on port 22. What do you do?
Step 3: Write the backend configuration for a remote S3 backend with locking, using the bucket northline-terraform-state and key billing/staging/terraform.tfstate.
Step 4: The team wants to use the same module for dev, staging, and production. Should they use Terraform workspaces or directory-per-environment? Justify your choice.
Solution
Step 1:
terraform import aws_vpc.main vpc-0abc1234
terraform import aws_subnet.primary subnet-0def5678
terraform import aws_security_group.api sg-0ghi9012Step 2: Do not accept the drift by writing 0.0.0.0/0 into the IaC config. Investigate: was the SSH rule intentional? If not, remove it from the IaC config, submit a PR, get security review, and after approval, terraform apply will remove the offending rule. If it was intentional (e.g., bastion host with further access control), document the justification in the config and get explicit security sign-off before encoding it.
Step 3:
terraform {
backend "s3" {
bucket = "northline-terraform-state"
key = "billing/staging/terraform.tfstate"
region = "eu-west-1"
encrypt = true
dynamodb_table = "northline-terraform-locks"
}
}Step 4: Directory-per-environment is recommended for Northline's context. Reasons: (a) Workspaces share the same code, so a mistake in a variable value or a destructive refactor can affect all environments unless carefully scoped. (b) Directory-per-environment makes a CI job that targets environments/staging/ structurally incapable of applying to environments/production/. (c) Different environments sometimes diverge in meaningful ways (different provider versions, different module versions during a migration) — directories accommodate this cleanly. Workspaces are acceptable for simpler use cases where all environments are truly identical in structure.
Independent exercise
Task: Write a Terraform module skeleton for a Northline notification-service staging environment that includes:
- A VPC with two subnets (CIDR values as variables).
- A security group allowing HTTPS inbound from
10.0.0.0/8only. - A reference to a secrets manager secret (by name, not value) for an SMTP password.
- An output exposing the security group ID.
- A remote S3 backend configuration.
Acceptance criteria:
- [ ] Provider version is pinned with
~>constraint. - [ ] No credentials, passwords, or tokens appear as literal values in any
.tffile. - [ ] All resources have
EnvironmentandOwnertags via variables. - [ ] Security group does not allow
0.0.0.0/0on any port. - [ ] Sensitive outputs are marked
sensitive = true. - [ ] A
variables.tffile defines and validates all input variables. - [ ] Backend configuration includes encryption and DynamoDB locking.
- [ ] A short written explanation describes how this module would be adapted for production (e.g., larger subnets, stricter IAM).
Common mistakes
| Mistake | Consequence | Prevention |
|---|---|---|
| No state locking | State corruption from concurrent applies | Always configure a locking backend before first apply |
Committing .tfvars with secrets | Credentials exposed in version control history | Use terraform.tfvars in .gitignore; inject sensitive values from CI secrets |
Pinning to latest or no version | Infrastructure changes on a day you did not plan | Pin providers with ~> and modules with a ref tag |
terraform apply without reviewing the plan | Unexpected destroys of production databases | Always use plan -out=tfplan + apply tfplan; require human approval |
| Accepting drift without investigation | Silent security regression (e.g., open firewall rule stays open) | Run nightly drift detection; investigate every difference |
terraform force-unlock during an active apply | State corruption | Only force-unlock a stale lock (verify no apply is running first) |
Sensitive outputs not marked sensitive = true | Values printed in CI logs | Mark all outputs containing IDs, ARNs, or any dynamic values that may be sensitive |
Quick checks
Q1: What is the difference between declarative and imperative infrastructure management?
A: Declarative describes the desired end state; the tool calculates how to reach it. Imperative specifies each step to reach the state. Declarative is safer for production because partial failures leave the system closer to a known state, and idempotent re-runs converge correctly.
Q2: What is Terraform state, and why must it never be committed to version control?
A: State is the mapping between Terraform's resource definitions and real cloud resources. It may contain sensitive values (endpoint URLs, resource IDs, sometimes secret outputs). It also changes on every apply — committing it causes constant merge conflicts. Store in an encrypted remote backend.
Q3: What is drift, and what should you do when terraform plan detects it?
A: Drift is a difference between the state file and the real cloud resources, caused by manual changes outside Terraform. When detected, investigate: if the change was intentional, encode it in IaC and get it reviewed; if accidental, revert it via a normal apply. Never silently accept drift.
Q4: Why should terraform apply always be done from a saved plan file (-out=tfplan)?
A: It guarantees that exactly what the reviewer approved is what executes. Without a saved plan, the plan can change between review and apply (e.g., another engineer makes a change, or a provider returns different data), and the reviewer has approved something that no longer matches what runs.
Q5: Name two limitations of Terraform rollback.
A: Any two from: (a) destroyed resources (databases, S3 objects) cannot be recreated — data is lost; (b) there is no built-in rollback command, only revert-and-apply; (c) state corruption from a failed apply requires manual remediation; (d) provider-managed auto-changes are invisible to Terraform.
Quiz alignment
| Quiz question | Lesson section |
|---|---|
| Declarative vs imperative | Plain English |
| State and remote backends | Core concepts → State |
| State locking purpose | Core concepts → State locking |
| Drift detection and response | Core concepts → Drift |
| Secrets in IaC | Walkthrough → Secrets table |
| Rollback limitations | Walkthrough → Rollback limitations |
Takeaways
- Declarative IaC makes environments reproducible and auditable. Manual cloud console changes create invisible risk.
- State is the source of truth between Terraform and reality. Protect it: remote backend, encryption, locking, never in version control.
- Always plan before apply. Always review the plan. Always apply from a saved plan file. Gate apply with a human approval for production.
- Drift is a signal, not an annoyance. Every drift detected is a potential security regression or compliance gap.
- Secrets never appear as literal values in IaC files. Reference secrets manager ARNs; let the runtime resolve the value.
- Terraform has real limitations: no native rollback, stateful resources are not safely reversible, and state can be corrupted. Design workflows and backup strategies accordingly.
- Policy as code extends IaC governance: automated rules enforce security baselines before a human ever sees the plan.
Bridge to next lesson
With IaC, you can provision and change infrastructure reliably. The next logical question is: how do you operate that infrastructure once it is running — observing it, responding to it, and improving it continuously? This connects to the observability patterns in #sad5 and #sad7, the MLOps deployment lifecycle in #mlops\*, and the cloud cost and governance practices in #cloud8 and #cloud11. The full DevOps picture is: ship code safely (#devops5), package it securely (#devops6), run it reliably (#devops7), and provision its environment reproducibly — this lesson.