Infrastructure as Code
Define infrastructure in versioned, reviewed code: declarative definitions, modules, state, plan-and-apply workflows, drift detection, testing, and safe use of AI for infrastructure changes.
Introduction
Someone creates a database through a cloud console, tweaks a firewall rule “just for now,” and resizes a server during an incident. Months later nobody knows what exists, why, or how to recreate it. The staging environment differs from production in twenty undocumented ways.
Infrastructure as code (IaC) replaces memory and clicking with definitions in version control. Environments become reproducible, changes become reviewable, and disasters become recoverable. The same power makes mistakes expensive: one wrong line can delete a database. This lesson covers both sides.
Learning Objectives
- Explain declarative infrastructure, desired state, and drift.
- Structure infrastructure code with modules and environment separation.
- Manage state safely.
- Use a plan, review, apply workflow in the pipeline.
- Detect drift and prevent manual changes.
- Test and validate infrastructure code, including policy checks.
- Use AI to draft and review infrastructure changes without applying unreviewed output.
1. Declarative Definitions and Desired State
A declarative definition states the end result (“a database of this size, in this network, with backups every day”). A tool compares it with reality and works out the changes. An imperative script states the steps (“run this, then that”) and is harder to rerun safely.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Illustrative notation, in the style of common IaC tools
resource "database" "main" {
name = "signaldesk-${var.environment}"
engine = "postgres"
engine_version = "16"
instance_class = var.db_instance_class
storage_gb = var.db_storage_gb
multi_az = var.environment == "production"
backup_days = var.environment == "production" ? 14 : 3
publicly_accessible = false
deletion_protection = var.environment == "production"
subnet = network.private_data.id
tags = local.common_tags
}
The key properties are:
- Idempotent: applying the same definition twice changes nothing the second time.
- Reviewable: a pull request shows exactly what will change.
- Reproducible: the same code creates a new environment on demand.
- Documented: the code is the accurate description of what exists, complementing the architecture documentation’s deployment view.
2. What to Define in Code
For SignalDesk’s containers, the infrastructure includes:
| Area | Examples |
|---|---|
| Network | Private and public networks, routing, firewall rules |
| Compute | Container service or cluster, service definitions, scaling rules |
| Data | Managed database, backups, queue, object storage |
| Identity and access | Service accounts, roles, least-privilege policies |
| Secrets plumbing | Secrets manager entries (not values), access grants |
| Observability | Log destinations, dashboards, alerts (expanded in the operations course) |
| DNS and certificates | Domain records, TLS certificates |
| Registry | Image registry, retention rules |
Define everything that would have to be recreated after a disaster. Anything created by hand is a liability.
3. Structure: Modules and Environments
Avoid copy-pasting the production definition into staging. Write reusable modules and instantiate them per environment with different inputs.
1
2
3
4
5
6
7
8
9
10
11
12
infra/
modules/
network/
database/
service/ Container service with scaling and health checks
observability/
environments/
dev/ main.tf variables: small sizes, shared resources
staging/ main.tf production-like, smaller scale
production/ main.tf full size, multi-zone, deletion protection
policies/ Policy-as-code rules (section 6)
README.md How to plan and apply; who may do what
Principles:
- Environments differ by inputs, not by structure. If staging uses different modules than production, it does not test production.
- Separate state per environment, so that an error in development cannot touch production.
- Keep modules small and focused, with documented inputs and outputs, and version them.
- Pin provider and module versions.
- Use descriptive names and tags (owner, environment, cost center) for cost tracking and cleanup (lesson 10).
4. State
Most IaC tools keep state: a record of what they created, used to compute the next change. State is critical and sensitive.
- Store state remotely, in a shared backend with locking, so that two people cannot apply at once.
- Protect it: access control and encryption, since state can contain secrets.
- Back it up and version it.
- Never edit by hand, except through the tool’s supported commands in a controlled repair.
- Keep it small and split by boundary (network, data, application) so that a plan is fast and an error has limited reach.
5. The Change Workflow: Plan, Review, Apply
1
2
3
4
5
6
7
8
9
1. Change the code on a branch.
2. Pipeline runs: format, validate, lint, policy checks.
3. Pipeline runs "plan" against the target environment and posts
the plan (what will be created, changed, destroyed) to the pull request.
4. A reviewer reads the plan, not only the code.
5. Merge. For non-production, apply automatically; for production,
apply after approval.
6. Pipeline applies the exact plan that was reviewed.
7. Post-apply checks confirm the result (smoke tests, drift check).
The reviewer’s job is to read the plan. Pay special attention to:
- Destroy or replace actions on stateful resources (databases, volumes, queues).
- Changes to network rules or identity policies that widen access.
- Changes in many resources from a small code change, which suggests a surprise.
- Unexpected differences between what the author intended and what the plan shows.
Protect critical resources with deletion protection and lifecycle rules that prevent accidental replacement. Apply with credentials that are scoped to the environment, and require approval for production.
6. Policy, Validation, and Testing
Infrastructure code can be checked before it touches anything.
| Check | Catches |
|---|---|
| Format and validate | Syntax errors, undefined variables |
| Static analysis | Insecure patterns: public databases, open ports, unencrypted storage |
| Policy as code | Organization rules: required tags, approved regions, no wildcard permissions, deletion protection on production data |
| Plan inspection | Dangerous actions in the proposed change |
| Cost estimate | Surprises in monthly cost, from the plan |
| Ephemeral environment test | Whether a module creates a working environment end to end |
| Post-deploy verification | Health checks, connectivity, expected outputs |
Apply the testing mindset from the quality course: define what could go wrong (a public database, a missing backup, a deleted volume) and write a check for each. A policy that fails when a database is made public is a test.
7. Drift
Drift is the difference between what the code says and what exists, caused by manual changes, emergency fixes, or other tools.
- Detect it: run a scheduled plan against each environment and alert on a non-empty result.
- Prevent it: restrict console write access, require changes through the pipeline, and give people read-only access by default, with a documented emergency procedure (“break glass”) that is logged and followed by a code change.
- Resolve it: either bring the code in line with a legitimate change, or reapply the code to undo an illegitimate one. Never leave it unresolved.
An emergency manual fix is acceptable; leaving it undocumented and un-coded is not.
8. Secrets and Sensitive Values
- Do not put secret values in code or state where avoidable. Define the secret container in code and set values through a secure process.
- Reference secrets from a secrets manager at runtime (lesson 5).
- Treat state files and plan output as sensitive, since they can reveal values.
- Rotate credentials, and keep the rotation procedure documented.
9. Using AI for Infrastructure Code
Infrastructure code is where AI’s plausibility is most dangerous. A model may produce a working definition that is wide open to the internet, omits backups, or uses resource arguments that do not exist in your provider version.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Act as a cloud infrastructure engineer drafting infrastructure code.
Inputs:
- Architecture deployment view and container list: [paste]
- Requirements: availability, data protection, scale (illustrative
figures): [paste]
- Tooling and provider versions: [paste]
- Naming, tagging, and security rules: [paste]
Tasks:
1. Draft modules for network, database, queue, and container service,
with variables for environment differences.
2. Make every resource private by default; list every place where you
expose something and why.
3. List the permissions each identity receives and justify each.
4. List the resources that hold state and the protection you applied
(backups, deletion protection).
5. List assumptions, and arguments you could not verify against the
specified provider version.
Do not include secret values. Do not use wildcard permissions.
Review a plan.
1
2
3
4
5
6
7
8
9
10
11
12
Act as a cautious infrastructure reviewer.
Inputs: the code diff [paste] and the plan output [paste].
Tasks:
1. Summarize what will be created, changed, and destroyed.
2. List any destructive action on stateful resources.
3. List any change that widens network or identity access.
4. List differences between the intent of the code diff and the plan.
5. List anything that should be checked before applying.
Do not approve. Flag uncertainty.
Always: run the model’s code through validation and policy checks, read the plan yourself, apply to a disposable environment first, and never let a model-driven process apply changes to production without a human approving the plan.
10. Practical Exercise
For SignalDesk (or your project):
- Define the network, database, queue, container service, identity, and registry in code, in modules with per-environment inputs.
- Configure remote, locked, access-controlled state, separate per environment.
- Add pipeline stages: format, validate, static analysis, policy checks, and plan posted to the pull request.
- Write at least five policy rules (for example: no public database, tags required, deletion protection in production, no wildcard permissions, encryption enabled).
- Create the development or staging environment from scratch using only the code, and record how long it takes.
- Make a manual console change and confirm that the scheduled drift check detects it.
- Run the AI drafting and plan-review prompts, check each claim against the provider documentation and the actual plan, and fix what is wrong.
- Document the workflow, who may apply to which environment, and the emergency procedure in the developer guide.
Verification
You are ready to continue when:
- A new environment can be created from code alone, repeatably.
- State is remote, locked, access-controlled, and separate for each environment.
- Every change passes validation and policy checks, and production applies require a reviewed plan and approval.
- Stateful resources have backups and protection against accidental deletion.
- Drift is detected automatically, and an emergency procedure exists.
- No secret values appear in code, plans, or logs.
Key Takeaways
- Infrastructure as code makes environments reproducible, reviewable, and recoverable.
- Use modules with per-environment inputs; keep separate state with locking and protection.
- Review the plan, not only the code, and guard destructive and access-widening actions.
- Detect and resolve drift; restrict manual changes with a logged emergency path.
- AI drafts infrastructure quickly, but unreviewed output can expose or destroy; people approve the plan.
What’s Next?
Infrastructure and images are only part of what differs between development and production. Next, we handle the rest: environments, configuration, and secrets, and how to keep them consistent without leaking anything.