Bookstore Platform — EKS Deploy Tree¶
This directory provisions the AWS infrastructure the Bookstore Platform v2 runs on. Terraform builds the substrate (VPC, EKS control plane, system node group, Karpenter, LB controller, EBS-CSI, metrics-server); Argo CD takes it from there for application workloads.
You opt in to costs. The user — not this Makefile — runs make up. Read all eleven sections before you do.
1. What this deploys¶
A single-region EKS cluster, ready for a multi-tenant platform:
- VPC —
10.0.0.0/16across three Availability Zones, with public (/20), private (/20), and intra (/22) subnets per AZ. The intra subnets host EKS control-plane ENIs; they have no NAT egress. - EKS cluster — Kubernetes
1.37, the control plane logs to CloudWatch, secrets are envelope-encrypted with a customer-managed KMS key. The principal that runsterraform applyis granted cluster-admin via an EKS access entry — noaws-authConfigMap. - One small managed node group ("system") — 2 ×
t3.mediumOn-Demand, taintedCriticalAddonsOnly=true:NoSchedule. Hosts Karpenter, the AWS Load Balancer Controller, CoreDNS, the EBS-CSI controller, metrics-server. Nothing else. - Karpenter
1.15.1— running inkube-system, with its CRDs in a separatekarpenter-crdrelease (§7). TwoNodePoolresources:general(On-Demand,c/m/rfamilies, generation > 4) andspot(prefers Spot, falls back to On-Demand, higherweightso Karpenter reaches for it first). Consolidation isWhenEmptyOrUnderutilizedwith a 30-second timer. OneEC2NodeClass(default) using the EKS-optimizedal2023@latestAMI alias. - AWS Load Balancer Controller
1.13.0— the bridge fromService type=LoadBalancerandIngressto ALBs / NLBs. IRSA-scoped to the upstreamv2.13.0IAM policy, vendored and reviewed inpolicies/(it used to be fetched over HTTP at plan time). - EBS-CSI driver, vpc-cni, kube-proxy, CoreDNS — installed as EKS-managed addons. Each
addon_versionis EKS's default build for the cluster's Kubernetes version:addons.tflooks it up with anaws_eks_addon_versiondata source (most_recent = false) keyed onmodule.eks.cluster_version, and the EKS module runs the same lookup for vpc-cni, so a version bump moves every add-on whose default build changed (kube-proxy always) in the same plan. Beyond the version, we setconfiguration_valuesfor CoreDNS and EBS-CSI (system-pool placement, replica count). - metrics-server
3.13.0— forkubectl topand HPA. Karpenter does not require it.
The Bookstore Platform application workloads (auth, payments, search, ML, observability, …) are not installed here. Argo CD bootstraps those after the cluster is up — see ../argocd/.
2. Cost estimate¶
The numbers below are list-price us-east-1 as of 2026-05; cross-check your region.
| Component | Hourly | Monthly (730 h) |
|---|---|---|
| EKS control plane (standard support) | $0.10/hr | ~$73 |
2 × t3.medium On-Demand |
2 × $0.0416 | ~$61 |
| NAT Gateway (single, dev) | $0.045/hr | ~$33 |
| NAT data processing | $0.045/GB | varies |
| EBS gp3 (3 × 30 GB system roots) | $0.08/GB-mo | ~$7 |
| CloudWatch logs (5 control-plane log types) | varies | $5-15 |
| Subtotal (idle) | ~$180/month, ~$5-8/day | |
| Karpenter workers (on-demand) | scales with pods | extra |
| Karpenter workers (spot) | typically 60-80% cheaper than on-demand | extra |
| ALB/NLB per Service | $0.0225/hr + LCU charges | $16+ each |
The Spot NodePool is the headline saving. Steady-state, the platform's stateless tiers (gateway, search, ML inference replicas) all tolerate Spot interruption — Karpenter will pack them onto Spot capacity by default because the Spot NodePool has higher weight than general.
Scaling to zero. Karpenter consolidates nodes that go idle within 30 seconds; if you stop submitting pods, your worker bill drops to zero quickly. The control plane and system node group keep running until make down.
3. Version policy¶
Kubernetes 1.37 is the pinned target. EKS released it on 2026-10-01; standard support ends 2027-12-01. Past that date the cluster shifts to extended support (until 2028-12-01), which carries an additional $0.50/hr surcharge per cluster. Don't get caught.
Check current support windows:
aws eks describe-cluster-versions \
--query "clusterVersions[].{version:clusterVersion,status:status,endOfStandardSupport:endOfStandardSupportDate}" \
--output table
Bump procedure (when 1.38 hits standard support):
- Read the upstream Kubernetes 1.38 changelog and the EKS release notes for any deprecations that affect the cluster's add-ons or your workloads. Check Karpenter's compatibility matrix too: if the pinned
karpenter_chart_versiondoes not support the new minor, bump Karpenter in its own apply first (§7 "Upgrading Karpenter"). - Set
kubernetes_version = "1.38"invariables.tf(or via-var). terraform plan— you should see in-place changes onmodule.eks.aws_eks_cluster.this(the version), thesystemnode group (its version) and the add-ons:aws_eks_addon.kube_proxyalways,aws_eks_addon.corednsandaws_eks_addon.aws_ebs_csi_driveronly if EKS's default build for 1.38 differs, andmodule.eks.aws_eks_addon.before_compute["vpc-cni"]withaddon_version(known after apply). The one replacement ismodule.eks.time_sleep.this[0], the module's 30-second wait before the node groups, whosetriggersinclude the cluster version; it is a harmless timer that touches no AWS resource. If anything else is destroyed, stop and investigate. No node-group destroy/create.terraform apply. EKS performs a rolling control-plane upgrade in place (≈20 minutes).- For the managed
systemnode group,terraform applytriggers a rolling AMI bump — the module replaces nodes one at a time, respecting PDBs. Karpenter-provisioned nodes will be replaced naturally asexpireAfter: 720hfires (or you cankubectl delete nodes -l karpenter.sh/nodepoolto force it). - Re-run
make planto confirm zero diff; commit.
Do not skip versions. EKS only supports N → N+1 upgrades.
Existing clusters on 1.35. A cluster applied before the 1.37 bump runs Kubernetes 1.35 and Karpenter 1.6.0, and needs three applies, in this order (with a tfvars file, put -var after -var-file; the last value wins):
terraform apply -var kubernetes_version=1.35: Karpenter 1.15.1, its CRDs and its IAM changes, with the control plane still on 1.35. Karpenter 1.6.0 supports neither 1.36 nor 1.37 (compatibility matrix), and in one combined apply the control plane would upgrade before the Helm release does, because the release depends onmodule.eks. Adopt the CRDs first (§7 "Upgrading Karpenter").terraform apply -var kubernetes_version=1.36.terraform apply(the1.37default).
Read the EKS notes for both 1.36 and 1.37 before you start.
Provider versions and the lock file¶
versions.tf uses range constraints (~> 5.95, and >= 1.19.0, < 2.0.0 for the third-party gavinbunney/kubectl provider). A range says what is allowed; .terraform.lock.hcl records what was chosen, together with the registry's hashes for every platform. That file is committed in all four Terraform roots (this tree, multi-region/, ../terraform-account-baseline/ and ../../gke/terraform/).
Why it matters: without the lock file, every terraform init resolves the newest version inside the range. Two CI runs a month apart can install different provider builds, and nothing checks the download against a hash anyone reviewed. That matters most for a third-party provider like gavinbunney/kubectl, which runs with your AWS credentials and cluster-admin token.
How to bump a provider deliberately:
terraform init -upgrade # resolve new versions inside the ranges
terraform providers lock \
-platform=linux_amd64 -platform=darwin_arm64 # record hashes for CI and Apple-silicon laptops
git diff .terraform.lock.hcl # review exactly what moved
CI runs terraform init -lockfile=readonly, so a constraint change that is not matched by a regenerated lock file fails the build instead of resolving silently. On another platform (Intel Mac, Windows, arm64 Linux), init checks the registry's zh: hashes in the lock file and may add an h1: line for your platform; commit it.
4. Prerequisites¶
- An AWS account with permission to create VPCs, EKS clusters, IAM roles, KMS keys, SQS queues, and EC2 instances. Run from a laptop, the principal you run Terraform as becomes the cluster admin, so make it your real working identity, not a throwaway service role. (CI uses an explicit apply role instead; see "GitHub Actions workflow" in §11.)
- AWS CLI v2 configured:
aws sts get-caller-identitymust return the expected account. - Terraform
>= 1.11.0, < 2.0.0(1.11 is where the S3 backend'suse_lockfileis GA)..terraform-versionpins1.14.8fortfenv/asdfusers: the version CI and the devcontainer run, and the one the lock file was generated with. kubectl(any version within ±1 minor of1.37).helm3.22.x(or4.3.x): the releases whose version-skew range covers Kubernetes 1.37.jq— the cleanup scripts use it heavily.- Outbound network egress for
terraform init(HashiCorp registry + GitHub Releases for module sources).
5. Quick start¶
# 1) Copy and edit the variables file (region, cluster name, tags).
cp example.tfvars my.tfvars
$EDITOR my.tfvars
# 2) Initialize providers + modules (~1 min).
make init
# 3) See the plan.
terraform plan -var-file=my.tfvars -out=tfplan
# 4) Apply. The Makefile target prompts y/N and warns about cost.
make up
# …or, if you used a tfvars file:
# terraform apply -var-file=my.tfvars
# 5) Verify.
terraform output kubeconfig_command
First apply takes 18 to 22 minutes: VPC ≈ 3 min, EKS control plane ≈ 10 min, system node group + addons ≈ 5 min, Karpenter + LB controller ≈ 2 min.
If terraform apply fails mid-way and you want to retry: it's safe to re-run. The module set is idempotent on partial state.
6. Connecting kubectl¶
Two options, pick one:
Option A — merge into your local kubeconfig (recommended for human use):
$(terraform output -raw kubeconfig_command)
# This prints: aws eks update-kubeconfig --region <REGION> --name bookstore-platform
kubectl config use-context arn:aws:eks:<REGION>:<ACCOUNT>:cluster/bookstore-platform
kubectl get nodes
Option B — use the standalone kubeconfig.yaml Terraform wrote:
export KUBECONFIG=./kubeconfig.yaml
kubectl get nodes
The cleanup scripts auto-detect ./kubeconfig.yaml. They prefer it over ~/.kube/config so they always target the right cluster.
7. Karpenter autoscaling¶
How it works. When the kube-scheduler can't fit a pod on existing nodes, the pod stays Pending. Karpenter watches Pending pods, picks a minimum-cost instance type that satisfies all requirements (architecture, OS, capacity-type, taints, resource requests), launches that EC2 instance directly via the EC2 API (no Auto Scaling Group), waits for it to join the cluster, and schedules the pod onto it. No middle-tier. No 10-minute ASG cooldown.
When pods drain off a node, Karpenter's consolidation reaper (running every 30 seconds, per the NodePool config) checks whether the cluster's workloads would still fit if the node went away. If they would, the node gets cordoned and deleted.
Test it:
# Submit 50 replicas of a CPU-hungry pod. Karpenter will provision new nodes.
kubectl create deployment karpenter-demo \
--image=public.ecr.aws/eks-distro/kubernetes/pause:3.10 \
--replicas=50
kubectl set resources deployment/karpenter-demo --requests=cpu=500m
# Watch nodes appear (typically ~60 seconds from pod submission).
watch kubectl get nodes -l karpenter.sh/nodepool
# Tear down — consolidation removes the nodes within ~30 seconds of the
# last pod evicting.
kubectl delete deployment karpenter-demo
watch kubectl get nodes -l karpenter.sh/nodepool
Inspecting decisions. kubectl logs -n kube-system -l app.kubernetes.io/name=karpenter is your friend. Karpenter's structured logs name every node it provisions, why, and what cost band it picked.
Upgrading Karpenter. Read Karpenter's upgrade guide for every minor between the old and the new version, then bump karpenter_chart_version. Three things in this tree move with it:
- CRDs. They come from the
karpenter-crdchart (helm_release.karpenter_crd), because Helm never upgrades the CRDs it installed from the controller chart'scrds/directory. A cluster first applied with Karpenter 1.6.0 has three CRDs without Helm ownership metadata, so the first apply after the bump fails withinvalid ownership metadata. Label and annotate them first, as Karpenter's troubleshooting guide describes:
kubectl label crd ec2nodeclasses.karpenter.k8s.aws nodepools.karpenter.sh nodeclaims.karpenter.sh \
app.kubernetes.io/managed-by=Helm --overwrite
kubectl annotate crd ec2nodeclasses.karpenter.k8s.aws nodepools.karpenter.sh nodeclaims.karpenter.sh \
meta.helm.sh/release-name=karpenter-crd meta.helm.sh/release-namespace=kube-system --overwrite
- Controller IAM.
karpenter.tfturns on the sub-module's v1 policy (enable_v1_permissions) and addsiam:ListInstanceProfiles(required since 1.7.0) andec2:DescribeInstanceStatus(required since 1.12.0), which the v20 sub-module does not grant. Check the upgrade guide's IAM notes against that list on every bump. - Drift. Since 1.12.0 Karpenter includes the CA bundle in its drift hash, and the upgrade guide warns that this marks existing nodes as drifted. Expect Karpenter to replace its nodes after the 1.6.0 to 1.15.1 upgrade.
The other notes from 1.7 to 1.15 need no change here: the chart values this tree sets are unchanged (the webhook block it used to set had been ignored since 1.1.0), the default EC2NodeClass sets no spec.kubelet (whose validation 1.15.0 tightened), and nothing in the repo queries the metrics those releases renamed or relabelled.
8. Teardown¶
Always teardown via make full-cleanup. It runs:
cleanup-pre-destroy.sh— drainsService type=LoadBalancer(so the LB controller removes its ALBs/NLBs), drainsPersistentVolumeClaim(so EBS-CSI deletes the EBS volumes), scales the Karpenter controller to zero, cordons and deletes Karpenter-managed nodes, deletes theNodePoolandEC2NodeClass.terraform destroy— tears down everything in Terraform state.cleanup-verify.sh— runs through 11 AWS-CLI checks. Exits 0 only when all are clean.
make full-cleanup
Why this order matters: terraform destroy knows about VPCs and node groups but not about the EC2 instances Karpenter created, the EBS volumes the CSI driver created, or the ALBs the LB controller created. Without the pre-destroy drain, the VPC delete will hang on dependent ENIs, you'll get half-destroyed state, and you'll be left chasing orphans manually.
If you really do want to skip the drain (because the cluster is already partially gone, say), make down works on its own — cleanup-pre-destroy.sh exits 0 gracefully if it can't reach the API server.
9. What happens if cleanup fails¶
Common failure modes and the manual escape hatch for each:
terraform destroyhangs on the VPC. Almost always an LB controller ENI you didn't drain. Runcleanup-pre-destroy.shagain, then retry destroy. If the controller is already deleted, find the orphan ENI:aws ec2 describe-network-interfaces --filters "Name=description,Values='ELB *'" --query 'NetworkInterfaces[].NetworkInterfaceId'andaws ec2 delete-network-interface --network-interface-id eni-xxx.- Orphan NLB / ALB.
make verify-cleanupwill name them. Delete withaws elbv2 delete-load-balancer --load-balancer-arn <ARN>(oraws elb delete-load-balancer --load-balancer-name <NAME>for classic). - Orphan EBS volume in
availablestate.aws ec2 delete-volume --volume-id vol-xxx. If it'sin-use, find the instance:aws ec2 describe-volumes --volume-ids vol-xxx --query 'Volumes[].Attachments'and terminate that instance first. - Orphan EC2 instance tagged with the cluster. Karpenter usually catches these via the interruption-queue, but if its controller was already gone:
aws ec2 terminate-instances --instance-ids i-xxx. - Stuck NAT gateway in
deletingstate. Normal — takes 1-5 minutes. Re-runmake verify-cleanupuntil it clears. - IAM role with the cluster prefix.
aws iam list-attached-role-policies --role-name <NAME>, detach each,aws iam delete-role --role-name <NAME>. - KMS alias still present. Expected. The encryption key is in a 7-30 day pending-delete window; the alias detaches but lingers. Safe to ignore, or
aws kms delete-alias --alias-name alias/eks/<CLUSTER>-.... - Log group still present. Terraform doesn't delete
/aws/eks/<CLUSTER>/*log groups by default. Delete withaws logs delete-log-group --log-group-name /aws/eks/<CLUSTER>/cluster.
When in doubt, re-run make verify-cleanup. It enumerates every check.
10. Production hardening checklist¶
This deploy is dev-grade. To move it to production, walk this list:
- NAT gateway —
single_nat_gateway = false. Multi-AZ NAT removes a single-zone failure mode (and costs ~$66/month extra). - API endpoint —
cluster_endpoint_public_access = false, or lockcluster_endpoint_public_access_cidrsto your office/VPN egress range. Public +0.0.0.0/0is a footgun; if your IAM ever leaks, the attacker can directly hit the API server. Tag the stackEnvironment = "prod"and the plan refuses the open default. - System node group sizing —
t3.mediumis enough for the controllers we host. If you add more cluster-critical workloads (Prometheus, Fluent Bit, OPA Gatekeeper, …), bump tom6i.largeor larger. - EKS audit logs — already on. Set a CloudWatch retention policy:
aws logs put-retention-policy --log-group-name /aws/eks/<CLUSTER>/cluster --retention-in-days 90. - KMS key rotation — the EKS module enables automatic rotation on the cluster encryption key by default. Confirm with
aws kms describe-key --key-id <KEY> --query 'KeyMetadata.KeyRotationStatus'. - Budget alarms — apply
../terraform-account-baseline/(its account-wide budget is on by default), and optionallyenable_budget_alarm = truehere for a cluster-scoped one. - Karpenter sanity bounds —
karpenter_general_cpu_limit/karpenter_general_memory_limitin variables.tf. Don't trust your HPAs not to runaway. - Container image scanning — turn on ECR image scanning on push (
aws ecr put-image-scanning-configuration --repository-name <REPO> --image-scanning-configuration scanOnPush=true). - Pod Security — apply the
restrictedPod Security Standard at the namespace level for everything exceptkube-system. - Backup / DR — Velero or AWS Backup for EBS-backed PVCs; etcd snapshots come "free" with EKS (managed automatically).
- State — move to the S3 backend (
backend-s3.tf.example), and pass a customer-managed KMS key tobootstrap-state.shso that reading state needskms:Decryptas well ass3:GetObject. See below for why.
What is in state, and who can read it¶
Terraform state holds every attribute of every resource and data source in this tree, in cleartext. sensitive = true changes none of that; it only hides a value from CLI and plan output. Inventory for this tree (checked 2026-10-24):
| In state | Why it matters |
|---|---|
| Helm release values (Karpenter, LB controller, Vault, ESO, Argo CD, Velero, Falco, Kyverno) | Configuration only: no passwords or tokens are passed through values/set in this tree. Keep it that way. Anything passed to helm_release lands in state. |
| IAM role and policy documents; the ARNs of KMS keys; VPC, subnet and security-group IDs; endpoints; the OIDC provider | Not credentials, but a complete map of the account for anyone planning an attack. |
local_file.kubeconfig (only when write_kubeconfig = true, the laptop default) |
The CA and endpoint only. It authenticates with the aws eks get-token exec plugin, so no token is written to disk or state. |
Not in state: a cluster bearer token. The kubernetes, helm and kubectl providers authenticate with the aws eks get-token exec plugin (versions.tf), which mints a token when each provider connects, under that run's own identity, and stores it nowhere. (This tree used to read one through data.aws_eks_cluster_auth, which put a cleartext cluster-admin token in state and in every saved plan.) Also not in state: the Argo CD initial admin password (generated in-cluster and read by hand; see argocd-bootstrap.tf) and any Vault root token (initialised out-of-band; see vault.tf).
What protects it: the state bucket from bootstrap-state.sh has versioning, a public-access-block on all four settings, and a bucket policy that denies non-TLS requests. Encryption is SSE-S3, or SSE-KMS if you pass a key ARN. With SSE-S3, anyone with s3:GetObject on the bucket can read state. With SSE-KMS, they also need kms:Decrypt under your key policy, and KMS calls show up in CloudTrail. A Bucket Key groups them: one per requester per key period, not one per read. Earlier versions of this tree marked the cluster CA and a KMS key ARN as sensitive. Both are non-secrets, so the flag was removed, with a comment in outputs.tf explaining why.
11. Optional / opt-in features (Phase 14 additions)¶
Every feature below is var-gated and OFF by default. The base deploy doesn't include any of them; flip the flag to opt in.
Encryption philosophy (KMS choice across this tree)¶
The tree uses two different KMS strategies depending on the artifact's blast radius and lifetime:
- AWS-managed keys (
alias/aws/sns,alias/aws/s3) for short-lived signal queues whose publisher is an IAM principal in this account, e.g. the Falco alert SNS topic (published by Falco's IRSA role). The data is ephemeral (alert payload, immediately consumed), the blast radius if the key were compromised is low. AWS-managed keys are free, get automatic rotation, and require zero key-policy maintenance from you. Exception: a topic that an AWS service publishes to (AWS Budgets, CloudWatch alarms) needs a customer-managed key, because the service principal must be allowed in the key policy and an AWS-managed key's policy cannot be edited. The budget topic usedalias/aws/snsuntil 2026-10-24 and silently delivered nothing; it now has its own CMK (cost-budgets.tf). - Customer-managed CMKs for long-lived data buckets — CloudTrail logs, AWS Config history, Velero backups, EKS Secrets envelope encryption. The data is forensically valuable years after creation; the key policy is the chokepoint that controls who can read it. A CMK gives you an explicit allow-list of principals, custom rotation schedules, and the ability to deny decrypt by removing yourself from the key policy in an incident.
Tier 1+ feature additions that create new resources should follow this rule: if it's a signal/notification path, AWS-managed key is fine; if it's audit/backup/secrets, create a CMK + alias.
CloudWatch log retention¶
cloudwatch_log_group_retention_in_days (default 30). The EKS module creates /aws/eks/<cluster>/cluster; this attribute caps how long the audit/api/scheduler logs live. Cost ~$0.03/GB-month — small enough you'll never notice on a sane retention, large enough to ruin your day at infinite retention. Bump to 90 for ops debugging or 365/3653 for compliance.
Cost-budget alarm¶
enable_budget_alarm = true
monthly_budget_usd = 100
budget_alarm_email = "platform-team@example.com"
Creates an aws_budgets_budget + an SNS topic encrypted with its own CMK (~$1/month; Budgets cannot publish to an alias/aws/sns topic) + email subscription. Fires at 80% forecast and 100% actual. AWS Budgets is free for the first 2 budgets per account. Caveat: AWS sends a confirmation link to the email; nothing flows until the subscriber clicks it. This is the cluster's budget and is destroyed with the cluster. The account-wide alarm, which is on by default and survives teardown, is ../terraform-account-baseline/budget.tf. Apply that first.
VPC endpoints¶
enable_vpc_endpoints = true
Adds an S3 gateway endpoint (free) + interface endpoints for ecr.api, ecr.dkr, sts, ec2, logs, kms (~$0.01/hr per AZ each, plus $0.01/GB data). Break-even vs NAT: around 50 GB/month of pulled images + AWS API traffic. Long-lived clusters almost always pay off.
Graviton (arm64) NodePool¶
enable_graviton_pool = true
Adds a Karpenter NodePool that requires arm64 and picks from c7g/m7g/r7g families. 20-40% cheaper than equivalent x86 with no perf penalty for most stateless workloads. Container images must be multi-arch or arm64-only — verify with docker manifest inspect <image> before enabling.
Argo CD bootstrap¶
enable_argocd_bootstrap = true
argocd_repo_url = "https://github.com/your-org/platform-gitops"
argocd_root_app_path = "argocd/apps"
Installs Argo CD 7.7.x + creates a root Application (App-of-Apps pattern) that points at the given repo+path. After apply: port-forward argo-cd-server, log in as admin with the password from kubectl -n argocd get secret argocd-initial-admin-secret. The chicken-and-egg is solved here: Terraform brings up the controller; Argo CD takes it from there.
Velero backups¶
enable_velero = true
velero_backup_bucket = "" # auto-named when empty
Creates a versioned + KMS-encrypted S3 bucket, an IRSA role for Velero with S3 + EBS snapshot perms, the Velero 7.2.x Helm release in its own velero namespace, and a daily Schedule with 30-day retention. Drill: velero backup create test --include-namespaces test-ns && velero restore create --from-backup test. Document the runbook with your team before relying on it.
Falco runtime detection¶
enable_falco = true
falco_alert_email = "security@example.com" # optional
Installs Falco 4.13.x with the modern eBPF driver (the 05.08 lab installed and ran chart 9.2.2 on kind, and this tree has not been re-rendered against it). PSA exception: the least-privileged driver adds CAP_BPF, CAP_PERFMON, CAP_SYS_RESOURCE and CAP_SYS_PTRACE to attach kernel eBPF programs, and the daemonset mounts host paths, so its namespace (falco) runs pod-security.kubernetes.io/enforce: privileged. It is the only namespace this tree labels privileged; kube-system, which holds Cilium, carries no label. Documented in falco.tf. Alerts go to stdout only: there is no Falcosidekick, and the warning priority floor keeps NOTICE rules such as Terminal shell in container off. Output is JSON on stdout (picked up by your log shipper). The optional SNS topic, IRSA role and email subscription are created, but nothing publishes to the topic until an http_output is configured; this tree does not ship one.
Kyverno image-signing policy¶
enable_image_signing = true
image_signing_keyless_issuer = "https://token.actions.githubusercontent.com"
image_signing_keyless_subject = "https://github.com/<ORG>/<REPO>/.github/workflows/<WORKFLOW>.yml@refs/heads/main"
image_signing_image_references = ["ghcr.io/<ORG>/*"]
Installs Kyverno 3.3.x + a ClusterPolicy named require-signed-images that uses cosign keyless verification. The subject is required (a variable validation fails without it). With only the issuer, any GitHub Actions workflow in any repository, an attacker's included, produces a passing signature. It is matched literally with */? wildcards, not as a regex: an earlier example here, https://github.com/your-org/.+, could never match. Default failureAction: Audit (image_signing_validation_failure_action): warns in PolicyReports but does NOT block Pod creation, so until you switch it this policy gates nothing. Run for 2-4 weeks, fix every flagged image, narrow image_signing_image_references to your own registry, THEN set it to Enforce. Excluded namespaces: kube-system, kube-public, kube-node-lease, kyverno, falco, velero, argocd, bookstore-platform-system.
Vault + ESO for production secrets¶
enable_vault = true
enable_external_secrets = true
vault_replicas = 3 # 1 for dev, 3 for production, 5 for very-large
vault_storage_size = "10Gi" # per-replica Raft PVC
Installs HashiCorp Vault 0.30.x (app version 1.18.x) as a 3-replica Raft cluster + External Secrets Operator 0.10.x as the bridge from Vault values into K8s Secrets. Vault auto-unseals via an AWS KMS CMK (no manual Shamir-key drama on pod restart). Forward-ref: Part 15 ch.15.05 walks the end-to-end wiring — ClusterSecretStore CR pointing at Vault, ExternalSecret CRs in app namespaces, rotation semantics, and the Vault-policy-per-K8s-role pattern.
When to enable:
- You have static credentials (DB passwords, API keys, signing keys) living in kubectl create secret-managed Secret objects today and want them rotated automatically.
- You want a single audit trail for who-read-what-secret-when (Vault's audit log).
- You need dynamic secrets (per-lease database credentials, short-lived AWS STS sessions via Vault's AWS engine) — a K8s Secret can't do this.
HA vs non-HA tradeoff:
- vault_replicas = 3 (default): production. Raft quorum = 2 — survives one pod loss without losing service. 3x EBS volumes, 3x pod resources.
- vault_replicas = 1: dev/smoke-test. No quorum, no Raft consensus, restarts cause a brief window of "sealed, waiting on KMS unseal". Cheaper, simpler, do not use for anything you'd cry over losing.
Cost (HA mode, ap-south-1):
- 3x Vault pods on existing Karpenter/system nodes (no extra EC2 bill).
- 3x EBS gp3 volumes at vault_storage_size (~$0.80/month for 10Gi each).
- 1x KMS CMK for unseal (~$1/month + a few cents in API calls).
- ESO controller pods (~free; runs as 2 small replicas).
- Total: ~$4-5/month additive over the base cluster.
KMS key safety: the unseal CMK has prevent_destroy = true in vault.tf. Losing the key = losing your sealed data. Document the key ARN (terraform output vault_kms_key_arn) in your DR runbook before a real workload depends on Vault.
TLS posture (intra-cluster plaintext by default): the Vault Helm release ships with global.tlsDisable = true and the Raft listener with tls_disable = 1. Vault traffic is plaintext on the wire; the encryption boundary is the cluster mesh (Istio / Cilium WireGuard) plus the ClusterIP-only Service that keeps the API off public networks. To expose Vault via Ingress or an NLB, you must flip both knobs in lockstep — provision a server cert via cert-manager, mount it through server.extraVolumes, set global.tlsDisable = false, and add tls_cert_file / tls_key_file to the listener block. The TLS POSTURE banner at the top of vault.tf walks the exact change set. Until that's wired, leave the defaults alone — they're internally consistent, and mismatching them puts the pod into a CrashLoop.
disable_mlock = true: disable_mlock = true is set in the Vault HCL config because Kubernetes' kubelet doesn't swap pod memory anyway, and enabling mlock would require CAP_IPC_LOCK (incompatible with PSA restricted, which drops all capabilities). This is HashiCorp's documented K8s-hardening guidance — there's nothing for mlock to lock against in a non-swap pod environment.
enable_vault vs enable_external_secrets (independent flags): these two booleans control separate add-ons; the typical combinations are: (a) both true — Vault as ESO's backend store (the most powerful setup, dynamic secrets + rotation + audit, the default for the Bookstore Platform); (b) Vault true, ESO false — Vault accessed directly via SDK/CLI from pods (rare in K8s, usually only for vault CLI bootstrap workflows); (c) Vault false, ESO true — ESO connects to AWS Secrets Manager / SSM Parameter Store / GCP Secret Manager / Azure Key Vault etc. (simpler, no self-hosted secret store to operate). The vault.tf and external-secrets.tf files are decoupled — flipping one flag doesn't move the other.
Fully destroying Vault (KMS lifecycle dance): terraform destroy will FAIL on the unseal CMK because of lifecycle { prevent_destroy = true } in vault.tf. This is intentional — losing the unseal CMK loses Vault's sealed data forever. To do a full destroy: (1) edit vault.tf to comment out the lifecycle { prevent_destroy = true } block on aws_kms_key.vault_unseal; (2) terraform apply to remove the lifecycle protection (no other change); (3) terraform destroy proceeds normally; (4) note the CMK still enters a 30-day deletion window in AWS — cancel via aws kms cancel-key-deletion if you change your mind within the window.
What this Terraform does NOT install (intentionally):
- ClusterSecretStore CRs — these are user-namespace concerns + Argo CD's job. Part 15 ch.15.05 has the manifests.
- Vault policies, K8s auth method config, role bindings — bootstrapped by an out-of-band vault CLI run after first apply (also covered in ch.15.05).
- Vault file audit device — the audit PVC is mounted but vault audit enable file path=/vault/audit/audit.log must be run after init+unseal (one of the first ops bootstrap commands, documented in ch.15.05 and as an inline auditStorage comment in vault.tf).
- The Vault CSI provider — we use ESO instead (one controller per cluster, no per-pod webhook overhead).
Cilium CNI (replaces VPC-CNI) — .tf.example only¶
cilium-installation.tf.example is shipped as .tf.example because switching CNIs is a major operational change. Rename to .tf ONLY after reading the file's top-of-file warning, draining nodes, and testing in staging. PSA exception again (Cilium needs NET_ADMIN + BPF + SYS_ADMIN).
GitHub Actions workflow¶
.github/workflows/terraform.yml is a template: copy it to your real repo, commit a remote backend first (the workflow refuses to run against local state), create two GitHub environments, terraform-plan and production, and set two repository variables, TF_PLAN_ROLE_ARN and TF_APPLY_ROLE_ARN. Uses OIDC (no long-lived access keys) with two roles: a read-only plan role for PRs, and an apply role trusted only from production. PRs get a speculative plan. On push to main it plans again, waits for a production reviewer, then applies that saved plan with no re-plan and no -auto-approve. Read the header before using it.
Laptop mode vs CI mode (eks.tf). By default (enable_cluster_creator_admin_permissions = true) the EKS module makes whoever runs Terraform a cluster-admin and the administrator of the cluster's secrets-encryption KMS key. It re-reads that identity on every plan, which is fine when one person plans and applies. Under the workflow, plans run as the read-only plan role, so the workflow sets CI mode for every job: enable_cluster_creator_admin_permissions = false, terraform_apply_role_arn (an explicit cluster-admin access entry for the apply role, which is also the KMS key administrator) and terraform_plan_role_arn (a view-only entry). Add a break-glass role with kms_key_administrators if you want one named in the key policy. variables.tf refuses the combinations that would hand the plan role cluster-admin.
Switching an existing cluster to CI mode: if it was created in laptop mode by the same apply role, rename the creator's access entry in state first, so the plan sees an unchanged entry instead of deleting and re-creating one for the same principal (EKS allows one entry per principal, and the create can run before the delete):
terraform state mv 'module.eks.aws_eks_access_entry.this["cluster_creator"]' \
'module.eks.aws_eks_access_entry.this["terraform-apply"]'
terraform state mv 'module.eks.aws_eks_access_policy_association.this["cluster_creator_admin"]' \
'module.eks.aws_eks_access_policy_association.this["terraform-apply_admin"]'
If a person created the cluster from a laptop, the first CI apply removes that person's admin entry and KMS administration. Name them in kms_key_administrators, and give them an access entry, before switching if they need to keep either.
Nightly drift detection¶
drift-check/nightly-drift.yml runs terraform plan -refresh-only -detailed-exitcode at 03:00 UTC with the read-only plan role. Exit code 2 means refresh found resources that no longer match state: drift, never merged-but-unapplied code, though not always a person (AWS-side updates count; see DRIFT.md Step 1). CI sets write_kubeconfig = false, because a runner-local kubeconfig.yaml would look deleted on every run. It opens an issue that lists the drifted resource addresses and never posts plan output. Atlantis users: drift-check/atlantis.yaml.example (repo side, projects only) and drift-check/atlantis-repos.yaml.example (server side, where the apply gate must live, because Atlantis reads the repo file from the PR's own branch). drift-check/DRIFT.md is the runbook for "I got a drift alert, what do I do?".
Multi-region scaffolding¶
multi-region/ is a separate sub-directory that wraps the cluster-substrate into a module and instantiates it once per region in var.regions. Route 53 LBR, CNPG cross-region replication, and ApplicationSet generators are intentionally LEFT AS TODO comments in multi-region/main.tf — see multi-region/README.md for the wiring story.
Account-baseline (separate tree)¶
../terraform-account-baseline/ is a sibling tree (separate state!) for per-account services: GuardDuty, Security Hub, Config, CloudTrail, IAM Access Analyzer. Each is gated by its own variable; all default OFF. ~$30-100/month with everything on (Config is the bulk).
infracost integration¶
make plan-cost produces a terraform plan + an infracost breakdown. Falls back to a plain plan if infracost isn't installed (brew install infracost).
12. Cross-references¶
- Part 10 ch.01 — EKS architecture deep dive. Reads the same control-plane / node-group story this README skims.
- Part 10 ch.06 — Karpenter chapter. NodePool/EC2NodeClass semantics, consolidation policies, disruption budgets — everything
karpenter-pools.tfactually configures. - Part 13 ch.03 — Multi-region. This deploy is single-region; the multi-region chapter walks the topology delta (Route53 latency routing, replicated state, cross-region failover drills).
- Part 13 ch.13.10 — Cost. The OpenCost / CloudCost story this deploy can feed. Karpenter's tagging is set up to attribute spend by
NodePooland pool label (bookstore-platform.example.com/pool). ../argocd/— Argo CD bootstrap; the application workloads that run on top of this cluster.../platform-base/— namespace + RBAC + PSA + NetworkPolicy baselines applied by Argo CD before any tenant workload lands.