These are the notes for Cybersecurity Fundamentals (defensive), episode 66. In episode 65 we set IAM policies, roles, networks and keys one setting at a time. At the scale of many environments, accounts and resources that breaks down. This episode turns the cloud into code you can review and scan, catches changes made behind the code's back, and introduces the platforms that watch a whole cloud. Every term is defined the first time it appears; the Glossary collects them.
Scope. Defensive and educational only. Every program is a toy simulation; no real cloud account is touched, and the password in Demo 2 is fake. Samples were run on 13 Nov 2026 in the SyntaxPilot compiler (Python 3.13).
Step 1: infrastructure as code
- Console: the cloud provider's website where you click to create resources.
- ClickOps: the joking name for building infrastructure by clicking in the console. Nobody reviews the clicks, and environments drift apart.
- Environment: a full copy of a system for one purpose: dev, test, prod.
Demo 1: clicking vs one template
# Three environments set up BY HAND ("ClickOps") vs from ONE definition (IaC).
by_hand = {
"dev": {"bucket_public": False, "db_encrypted": True, "ssh_open": False},
"test": {"bucket_public": False, "db_encrypted": True, "ssh_open": True}, # forgot
"prod": {"bucket_public": True, "db_encrypted": False, "ssh_open": False}, # 2 a.m. fix
}
template = {"bucket_public": False, "db_encrypted": True, "ssh_open": False}
as_code = {env: dict(template) for env in ("dev", "test", "prod")}
def differences(envs):
keys = template.keys()
return [f"{k}: " + ", ".join(f"{e}={envs[e][k]}" for e in envs)
for k in keys if len({envs[e][k] for e in envs}) > 1]
print("by hand:", *differences(by_hand) or ["identical"], sep="\n ")
print("as code:", *differences(as_code) or ["identical"], sep="\n ")
Real output:
by hand:
bucket_public: dev=False, test=False, prod=True
db_encrypted: dev=True, test=True, prod=False
ssh_open: dev=False, test=True, prod=False
as code:
identical
- Infrastructure as code (IaC): describing servers, networks, storage and permissions in text files and letting a tool create them. The files live in Git (version control), so every change is reviewed (pull request, episode 63), versioned and repeatable.
Terraform and CloudFormation
Real-life example: an architect's drawing (every wall written down before a brick is laid), the contractor's estimate ("I will build 2 walls and remove 1"), and the site register of what was really built.
- Terraform: an IaC tool that works across many clouds. Microsoft Learn: "Terraform is a CLI tool" (a command-line program), free to use under the BSL (Business Source License). You write configuration in HCL, the HashiCorp Configuration Language.
- plan: "Generates a plan to bring actual state into line with desired state, by querying your deployed resources and comparing to the configuration." Review it like code: an unexpected destroy is a red flag.
- apply: "Implement the plan and bring the target environment in line via API calls."
- State file: Terraform's record mapping each resource in the code to the real resource. Microsoft Learn: "State files can contain sensitive data and must be stored securely." Google Cloud's Terraform guide: "There are many resources and data providers in Terraform that store secret values in plaintext in the state file"; use a remote state backend with locking, restrict access to the build system and admins, and encrypt state as an extra layer. Never commit state to Git.
- AWS CloudFormation: AWS's own IaC service. "You create a template that describes all the AWS resources that you want", and CloudFormation provisions them. Creating the template makes a stack: the collection of resources managed "as a single unit". Templates are text files tracked like source code (commonly JSON or YAML).
A small Terraform example (HCL):
resource "aws_s3_bucket" "invoices" {
bucket = "shop-invoices"
}
resource "aws_s3_bucket_public_access_block" "invoices" {
bucket = aws_s3_bucket.invoices.id
block_public_acls = true
block_public_policy = true
ignore_public_acls = true
restrict_public_buckets = true
}
Step 2: IaC scanning
The dark side of IaC: it copies a mistake perfectly. A public bucket in a shared module (a reusable piece of IaC) becomes fifty public buckets.
- Static analysis: checking code without running it.
- IaC scanning: static analysis of infrastructure code for risky settings, run in the CI pipeline (episode 60) before anything is deployed.
- Exit code: the number a program returns when it finishes;
0means success, anything else means failure, which makes a pipeline step fail.
Demo 2: a toy IaC scanner
# A toy IaC scanner: read Terraform-style code and flag risky settings BEFORE deploy.
import re, sys
CODE = '''resource "aws_s3_bucket_public_access_block" "invoices" {
block_public_acls = false
block_public_policy = false
}
resource "aws_security_group_rule" "ssh" {
from_port = 22
cidr_blocks = ["0.0.0.0/0"]
}
resource "aws_db_instance" "orders" {
storage_encrypted = false
password = "Sup3rSecret!"
}'''
CHECKS = [
(r"block_public_\w+\s*=\s*false", "HIGH public access block turned off"),
(r'cidr_blocks\s*=\s*\["0\.0\.0\.0/0"\]', "HIGH open to the whole internet"),
(r"storage_encrypted\s*=\s*false", "MED database not encrypted at rest"),
(r'password\s*=\s*"', "HIGH hard-coded secret in code"),
]
fails = 0
for n, line in enumerate(CODE.splitlines(), 1):
for pattern, msg in CHECKS:
if re.search(pattern, line):
print(f"line {n:2}: {msg}"); fails += 1
print(f"{fails} findings -> pipeline", "FAILED" if fails else "passed")
sys.exit(1 if fails else 0)
Real output (and the process exits with code 1):
line 2: HIGH public access block turned off
line 3: HIGH public access block turned off
line 7: HIGH open to the whole internet
line 10: MED database not encrypted at rest
line 11: HIGH hard-coded secret in code
5 findings -> pipeline FAILED
- 0.0.0.0/0: CIDR notation (episode 18) for "every IPv4 address", i.e. the whole internet.
- Hard-coded secret: a password or key written directly in code.
- Checkov: "a static code analysis tool for infrastructure-as-code"; scans Terraform (including plan files), CloudFormation, Kubernetes, Helm, Kustomize, Dockerfiles, Serverless, Bicep and ARM templates.
- tfsec: a Terraform scanner from Aqua Security. Its README: "Going forward we want to encourage the tfsec community to transition over to Trivy", Aqua's newer scanner, where engineering attention now goes.
- Real scanners parse the code properly instead of using regular expressions, and ship hundreds of checks; the idea is the same.
Step 3: policy as code and guardrails
Scanners know general best practice; your company also has its own rules ("data stays in Mumbai", "every resource has an owner tag").
Demo 3: policy as code
# Policy as code: company rules written as small, tested functions.
PLAN = [ # what the change WILL create (like a Terraform plan)
{"type": "bucket", "name": "reports", "region": "ap-south-1", "tags": {"owner": "asha"}},
{"type": "vm", "name": "gpu-box", "region": "us-east-1", "tags": {}, "size": "x16"},
]
def rule_region(r): return r["region"] == "ap-south-1" or "data must stay in ap-south-1"
def rule_owner(r): return "owner" in r["tags"] or "every resource needs an owner tag"
def rule_size(r): return r.get("size") != "x16" or "x16 servers need approval"
POLICIES = [rule_region, rule_owner, rule_size]
# the policies are code, so they get tests too
assert rule_owner({"tags": {"owner": "neha"}}) is True
assert rule_owner({"tags": {}}) != True
denies = [f"DENY {r['name']}: {msg}" for r in PLAN for p in POLICIES
if (msg := p(r)) is not True]
print(*denies, sep="\n")
print("decision:", "BLOCK the deploy" if denies else "allow")
Real output:
DENY gpu-box: data must stay in ap-south-1
DENY gpu-box: every resource needs an owner tag
DENY gpu-box: x16 servers need approval
decision: BLOCK the deploy
- Tag: a key-value label on a cloud resource (
owner=asha), used for ownership, cost and policy. - Policy as code: rules written as code, versioned, reviewed and tested like any program, and checked automatically (here, against the plan).
- Open Policy Agent (OPA): an open-source "policy management and enforcement engine"; it graduated from the CNCF (Cloud Native Computing Foundation) in February 2021. Its policies are written in Rego, a declarative policy language.
- Guardrail: a rule set centrally that keeps every team inside safe limits.
- Preventive guardrail: blocks the bad action (an SCP, a policy check that fails the pipeline).
- Detective guardrail: spots it afterwards (a CSPM finding, a drift alert).
- Corrective guardrail: fixes it automatically (e.g. re-enables Block Public Access).
- "Guardrails, not gates": teams move fast inside the rails without asking permission for every change.
Step 4: drift detection
The problem: during a 2 a.m. outage someone makes the invoices bucket public in the console. The code still says private, so every scan passes.
- Drift: the real infrastructure no longer matches its code.
- Unmanaged resource: something that exists in the cloud but not in any code.
Demo 4: a toy drift detector
# Drift detection: compare what the code says with what really exists.
desired = {"bucket/invoices": {"public": False, "versioning": True},
"sg/web": {"ports": [443]},
"db/orders": {"encrypted": True}}
actual = {"bucket/invoices": {"public": True, "versioning": True}, # changed by hand
"sg/web": {"ports": [443, 22]}, # "just for a minute"
"db/orders": {"encrypted": True},
"vm/test-temp": {"size": "x16"}} # never in code
for rid in sorted(desired.keys() | actual.keys()):
if rid not in actual:
print(f"{rid:16} DELETED outside the code")
elif rid not in desired:
print(f"{rid:16} UNMANAGED: exists but not in code")
else:
for k, want in desired[rid].items():
if actual[rid].get(k) != want:
print(f"{rid:16} DRIFTED {k}: code={want} actual={actual[rid].get(k)}")
Real output:
bucket/invoices DRIFTED public: code=False actual=True
sg/web DRIFTED ports: code=[443] actual=[443, 22]
vm/test-temp UNMANAGED: exists but not in code
- Drift detection: comparing real resources with the code. AWS CloudFormation's version "enables you to detect whether a stack's actual configuration differs, or has drifted, from its expected configuration"; a resource has drifted "if any of its actual property values differ from the expected property values", including if it was deleted. Terraform's plan shows the same gap.
- Then either put the change into code (if it was right) or re-apply the code (if it wasn't), and find out why someone changed production by hand.
Step 5: immutable infrastructure and golden images
Demo 5: snowflakes vs one image
# Mutable servers patched by hand drift apart; immutable ones are rebuilt from one image.
import random
random.seed(7)
GOLDEN = {"os": "patched-2026-11", "ssh_password_login": False, "agent": "edr-5.2"}
def hand_patch(server): # a tired admin, one server at a time
if random.random() < 0.5: server["os"] = "patched-2026-11"
if random.random() < 0.3: server["ssh_password_login"] = True # "temporary"
return server
mutable = [hand_patch({"os": "patched-2026-08", "ssh_password_login": False,
"agent": "edr-5.2"}) for _ in range(4)]
immutable = [dict(GOLDEN) for _ in range(4)] # replace, never patch in place
for name, fleet in (("mutable ", mutable), ("immutable", immutable)):
kinds = {tuple(sorted(s.items())) for s in fleet}
print(f"{name}: {len(kinds)} different server configs out of {len(fleet)}")
print("server 2:", mutable[1]["os"], "| password login:", mutable[1]["ssh_password_login"])
Real output (random.seed(7) makes it repeatable):
mutable : 4 different server configs out of 4
immutable: 1 different server configs out of 4
server 2: patched-2026-08 | password login: True
- Mutable infrastructure: servers changed in place (log in, patch, tweak).
- Snowflake server: a hand-crafted, one-of-a-kind server nobody can rebuild exactly.
- Immutable infrastructure: never change a running server; to patch or change, build a new one and replace the old.
- Golden image: a pre-built, hardened (episode 9), scanned and approved machine image that every new server starts from. Rebuild it on a schedule with the latest patches.
- EDR agent: endpoint detection and response software (episode 69 goes deeper), here just a setting that should be identical everywhere.
- Bonus: if nobody needs to log in, remote login (SSH) can be switched off entirely.
Step 6: cloud-native security platforms
Real-life example: a hospital needs building inspection, monitors on every patient, a list of who holds which keycard, and a locked medical-records room.
- Workload: anything that runs code: virtual machines, containers, serverless functions.
- Entitlement: a permission an identity has.
- CSPM (episode 64): cloud security posture management — settings and misconfigurations.
- CWPP (cloud workload protection platform): discovers workloads across clouds and scans them for security problems; may add runtime protection and segmentation.
- CIEM (cloud infrastructure entitlement management): identifies which human and machine identities can access which parts of the cloud, and enforces least privilege.
- DSPM (data security posture management): "a holistic view of a company's sensitive data": where it is, who can access it, how it has been used, and its security posture; includes discovering and classifying data.
- CNAPP (cloud-native application protection platform): a product that bundles multiple cloud security tools (CSPM, CWPP, CIEM, often IaC scanning and more) into one platform.
- Attack path: a chain of weaknesses an attacker could link (public VM → critical vulnerability → role that can read the customer database). Combining the views lets you fix the most dangerous chains first.
Demo 6: a toy CIEM
# A toy CIEM: compare what each identity CAN do with what it actually DID (90 days of logs).
granted = {"role/web-app": {"s3:GetObject", "s3:PutObject", "s3:DeleteBucket", "iam:*"},
"user/old-intern": {"ec2:*", "s3:*"},
"role/backup": {"s3:GetObject", "s3:PutObject"}}
used = {"role/web-app": {"s3:GetObject", "s3:PutObject"},
"role/backup": {"s3:GetObject", "s3:PutObject"}}
for ident, perms in granted.items():
unused = perms - used.get(ident, set())
if not used.get(ident):
print(f"{ident:16} INACTIVE 90 days -> remove the identity")
elif unused:
print(f"{ident:16} remove unused: {sorted(unused)}")
else:
print(f"{ident:16} right-sized")
Real output:
role/web-app remove unused: ['iam:*', 's3:DeleteBucket']
user/old-intern INACTIVE 90 days -> remove the identity
role/backup right-sized
Unused permissions do nothing for you and everything for an attacker who steals that identity. The "used" data comes from the audit logs of episode 64.
The whole chain
- Clicked setups drift apart → infrastructure as code (Terraform, CloudFormation).
- Code copies mistakes → IaC scanning in the pipeline (Checkov, tfsec/Trivy).
- Rules nobody reads → policy as code (OPA/Rego), guardrails.
- Hand changes behind the code → drift detection.
- Snowflake servers → immutable infrastructure, golden images.
- Too many views → CSPM, CWPP, CIEM, DSPM in one CNAPP.
Common mistakes (and the fix)
| Mistake | What you see | Why | Fix |
|---|---|---|---|
terraform.tfstate committed to Git |
secrets from the state are public | state can hold plain-text secrets | encrypted, locked remote state; .gitignore it |
password = "Sup3rSecret!" in a .tf file |
line 11: HIGH hard-coded secret in code |
code is shared and copied | a secrets manager, short-lived credentials |
| applying without reading the plan | a database is destroyed and recreated | unreviewed change | review every plan; protect critical resources |
| a "quick fix" in the console | DRIFTED public: code=False actual=True |
change outside the code | change the code, re-apply; alert on drift |
| SSH in and patch each server | 4 different server configs out of 4 |
snowflake servers | new golden image, replace servers |
| scanner findings ignored ("just warnings") | the pipeline passes with HIGH findings | no failing exit code | fail the build on HIGH; track exceptions with an expiry |
| roles never cleaned up | remove unused: ['iam:*', 's3:DeleteBucket'] |
permissions accumulate | CIEM reviews; remove unused permissions and identities |
Mini project: a mini IaC pipeline
Build a small "pipeline" script that runs four stages on a toy plan: (1) the IaC scanner of Demo 2, (2) the policy checks of Demo 3, (3) a fake apply that copies the desired state into an actual dictionary, (4) the drift detector of Demo 4 (which should now report nothing). Then change one setting by hand in actual and show the drift detector catching it. Exit with code 1 if any stage fails.
Practice
1. Add a check to the toy scanner for S3 versioning switched off (status = "Suspended").
Solution
CHECKS.append((r'status\s*=\s*"Suspended"', "LOW bucket versioning suspended"))
Add a line status = "Suspended" to CODE and the scanner flags it.
2. Write a policy: every resource must have a cost-centre tag.
Solution
def rule_cost(r): return "cost-centre" in r["tags"] or "every resource needs a cost-centre tag"
POLICIES.append(rule_cost)
assert rule_cost({"tags": {"cost-centre": "shop"}}) is True
Both resources in the sample plan now fail it.
3. Make the drift detector report a deleted resource.
Solution
Delete "db/orders" from actual. The existing branch prints db/orders DELETED outside the code.
4. Why does an IaC scan pass while production has a public bucket?
Solution
The scan reads the code, which says private. The bucket was changed outside the code (drift). Only drift detection (or CSPM) looks at the real resource.
5. Preventive, detective or corrective? (a) An SCP denying s3:PutBucketPolicy outside the platform team. (b) A CSPM alert on a public bucket. (c) A function that re-enables Block Public Access within a minute.
Solution
(a) preventive, (b) detective, (c) corrective.
6. Add a "last used" date to the toy CIEM and flag permissions unused for more than 90 days.
Solution
last_used = {("role/web-app", "s3:GetObject"): 2, ("role/web-app", "s3:PutObject"): 120}
for (ident, perm), days in last_used.items():
if days > 90:
print(f"{ident}: {perm} unused for {days} days -> remove")
Quick quiz
A: the scanner is broken
B: someone changed it by hand: drift
C: the cloud provider made it public
D: Terraform plans are random
IaC scans pass, but production has a public bucket. What most likely happened?
Answer
B. Scans read the code, and the code says private. A change made outside the code is drift; drift detection compares the real resources with the code to catch it.
Interview questions
- What are the security benefits of IaC? Every change is reviewed, versioned and repeatable; environments match; mistakes can be scanned before deploy and rolled back.
- What is the risk with Terraform state? It can contain secrets in plain text; keep it in an encrypted, access-controlled, locked remote backend, never in Git.
- What does an IaC scanner do? Static analysis of infrastructure code for misconfigurations (public storage, open ports, no encryption, hard-coded secrets) before deployment.
- What is policy as code? Organisation rules written as code, versioned and tested, evaluated automatically (e.g. OPA policies in Rego against a Terraform plan).
- Preventive vs detective guardrails? Preventive blocks an action (SCP, failing policy check); detective finds it afterwards (CSPM, drift alert).
- What is drift and how do you catch it? Real infrastructure differing from its code; compare continuously (CloudFormation drift detection, Terraform plan, CSPM) and alert.
- What is immutable infrastructure? Servers are never modified in place; changes ship as new images that replace old servers.
- What is a golden image? A hardened, scanned, approved base image every server starts from, rebuilt regularly.
- CSPM vs CWPP vs CIEM vs DSPM? Settings; workloads; identities and entitlements; sensitive data.
- What is a CNAPP? A platform bundling those capabilities so attack paths across settings, workloads, identities and data can be seen and prioritised together.
Glossary
| Term | Meaning |
|---|---|
| console | the provider's web interface for clicking to create resources |
| ClickOps | building infrastructure by clicking, unreviewed |
| environment | a full copy of a system: dev, test, prod |
| infrastructure as code (IaC) | infrastructure described in text files and created by a tool |
| Git | version control that records every change |
| Terraform | a multi-cloud IaC command-line tool |
| HCL | HashiCorp Configuration Language, Terraform's language |
| BSL | Business Source License, Terraform's licence |
| plan | Terraform's preview of what it will create, change or destroy |
| apply | Terraform carrying out the plan through API calls |
| state file | Terraform's map from code to real resources; may hold secrets |
| remote state backend | shared, locked, protected storage for state |
| CloudFormation | AWS's IaC service using templates |
| template | a CloudFormation file describing resources |
| stack | the resources created from a template, managed as one unit |
| module | a reusable piece of IaC |
| static analysis | checking code without running it |
| IaC scanning | static analysis of infrastructure code for risky settings |
| exit code | a program's result number; non-zero fails a pipeline step |
| 0.0.0.0/0 | every IPv4 address: the whole internet |
| hard-coded secret | a password or key written in code |
| Checkov | an open-source static analysis tool for IaC |
| tfsec | a Terraform scanner; users are pointed to Trivy |
| Trivy | Aqua Security's scanner that succeeds tfsec |
| tag | a key-value label on a resource |
| policy as code | rules as versioned, tested code checked automatically |
| Open Policy Agent (OPA) | an open-source policy engine, CNCF graduated |
| Rego | OPA's policy language |
| CNCF | Cloud Native Computing Foundation |
| guardrail | a central rule keeping teams within safe limits |
| preventive / detective / corrective | blocks / spots / fixes automatically |
| drift | real infrastructure no longer matching its code |
| drift detection | comparing real resources with the code |
| unmanaged resource | exists in the cloud but not in code |
| mutable infrastructure | servers changed in place |
| snowflake server | a hand-crafted, unrepeatable server |
| immutable infrastructure | replace servers instead of changing them |
| golden image | a hardened, approved base machine image |
| workload | anything that runs code: VMs, containers, functions |
| entitlement | a permission an identity has |
| CSPM | cloud security posture management: settings |
| CWPP | cloud workload protection platform: workloads |
| CIEM | cloud infrastructure entitlement management: identities and permissions |
| DSPM | data security posture management: sensitive data |
| CNAPP | cloud-native application protection platform: these combined |
| attack path | a chain of weaknesses an attacker could link |
Summary
- IaC turns clicks into reviewed, versioned, repeatable code; review plans and protect Terraform state.
- Scan IaC in the pipeline before deploy (Checkov, tfsec → Trivy); fail the build on serious findings.
- Write company rules as tested policy as code (OPA/Rego) and enforce them with guardrails.
- Detect drift between code and reality, and fix the process that caused it.
- Replace servers from golden images instead of patching in place.
- CSPM, CWPP, CIEM and DSPM watch settings, workloads, identities and data; a CNAPP joins them.
- Next episode: container security.
Sources (fetched 13 Nov 2026)
- Microsoft Learn, How Terraform works: https://learn.microsoft.com/en-us/training/modules/terraform-introduction-to-infrastructure-as-code/5-how-terraform-works
- Google Cloud, Terraform best practices for security: https://docs.cloud.google.com/docs/terraform/best-practices/security
- AWS CloudFormation, What is CloudFormation?: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/Welcome.html
- AWS CloudFormation, drift detection: https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-stack-drift.html
- Checkov on PyPI: https://pypi.org/project/checkov/
- aquasecurity/tfsec README: https://github.com/aquasecurity/tfsec
- InfoQ, CNCF graduates Open Policy Agent (Feb 2021): https://www.infoq.com/news/2021/02/opa-cncf-graduation/
- TechTarget, CNAPP (with CSPM, CWPP, CIEM): https://www.techtarget.com/cybersecurity/definition/cloud-native-application-protection-platform-CNAPP
- TechTarget, DSPM: https://www.techtarget.com/searchsecurity/definition/data-security-posture-management-DSPM