โšก
Zero to Platform Architect2026
Phase 3 & 3B: DevSecOps & Fleet Patching

Lesson 1: Immutable Golden AMIs, CIS Benchmark Hardening with Packer & Exception Handling

๐Ÿง  The Concept (Explain Like Iโ€™m 5)

Imagine buying a standard factory car straight off the dealership lot (a raw Ubuntu or Amazon Linux AMI):

  • The Dangerous Mutable Way (Modifying the Car on the Highway): You drive the car onto a 100 mph highway (Production). While driving at full speed, mechanics lean out of the windows with wrenches trying to bolt on roll cages, swap the engine oil, and install bulletproof glass. If a mechanic drops a wrench, the car crashes instantly. (This is SSHing into live production servers to run apt-get upgrade or configuration scripts).
  • The Immutable Golden AMI Standard (The Formula 1 Assembly Facility):
    1. You bring the car into a sterile, climate-controlled assembly workshop (Packer Build Sandbox).
    2. Master mechanics install the roll cages, fire extinguishers, and GPS trackers (Ansible Hardening & CIS Benchmarks).
    3. Safety inspectors run 200 forensic compliance diagnostic checks (InSpec / OpenSCAP).
    4. Once it passes 100% of safety tests, you freeze the design and stamp out 500 identical carbon-copy clones (The Golden AMI).
    5. If an engine part ever wears out, you never fix the carโ€”you simply deliver a brand-new identical clone and crush the old one.

๐Ÿข The Enterprise Context (Why Platform Architects Care)

  1. The Death of Configuration Drift & Snowflake Servers: In mutable environments, servers drift over time. Small manual hotfixes make each machine unique. When a server inevitably crashes, no one can recreate it from scratch. Immutable Golden AMIs guarantee that server #1 and server #500 are byte-for-byte identical.
  2. CIS (Center for Internet Security) Benchmarks: Regulatory standards (PCI-DSS 4.0, HIPAA, SOC 2, ISO 27001) mandate operating system hardening. The CIS Benchmark specifies ~200 concrete controls: disabling obsolete filesystems (cramfs, hfs), disabling legacy SSH ciphers, enforcing password hashing algorithms (SHA-512), and locking down kernel parameters via sysctl.
  3. Multi-Account Factory Distribution: In an enterprise with 50 AWS accounts, you build the Golden AMI once in a centralized Shared Services / Security Account, encrypt it with AWS KMS, and distribute it to all member accounts via AWS Resource Access Manager (RAM).

๐Ÿ—บ๏ธ Visual Architecture: Centralized Golden AMI Pipeline

flowchart TD
    Trigger["โฑ๏ธ Scheduled Trigger (Every 30 Days or Zero-Day CVE)"] --> Central["<b>Central Security Account (111111111111)</b>"]
    
    subgraph BuildSandbox ["Packer Build Sandbox (Isolated Private VPC)"]
        Raw["Base Canonical Ubuntu AMI"] --> EphemeralEC2["Boots Ephemeral EC2 Instance<br/>(No Public IP / SSM Communicator)"]
        EphemeralEC2 --> Ansible["Ansible Hardening Playbook<br/>โ€ข Apply CIS Level-1 Rules<br/>โ€ข Install Datadog & CrowdStrike<br/>โ€ข Harden sysctl kernel parameters"]
        Ansible --> OpenSCAP{"OpenSCAP / InSpec<br/>Compliance Audit"}
        
        OpenSCAP -->|"Fail Compliance (< 100%)"| Abort["โŒ Abort Build & Terminate VM"]
        OpenSCAP -->|"Pass 100% Compliant"| EncryptSnap["Take Encrypted EBS Snapshot<br/>(Customer-Managed KMS Key)"]
    end

    Central --> BuildSandbox
    EncryptSnap --> GoldenAMI[("๐Ÿ”’ Registered Golden AMI<br/>corp-ubuntu-22.04-cis-v2.4")]

    subgraph CrossAccountDistribution ["Cross-Account Fleet Distribution"]
        KMSGrant["KMS Key Policy: Grant kms:Decrypt & CreateGrant"]
        RAM["Share AMI to AWS Organization via AWS RAM"]
    end

    GoldenAMI --> KMSGrant
    GoldenAMI --> RAM

    RAM --> DevAcc["Member Account: Dev (222222222222)"]
    RAM --> StagingAcc["Member Account: Staging (333333333333)"]
    RAM --> ProdAcc["Member Account: Prod (999999999999)"]

    ProdAcc --> ASG["Trigger Auto Scaling Group Instance Refresh โœ…"]

๐Ÿ”ฌ Under the Hood: CIS Level 1 vs. Level 2 Hardening

The Center for Internet Security divides hardening rules into two levels:

Level Intended Environment Typical Hardening Actions Platform Architectural Impact
CIS Level 1 Standard Enterprise Workloads โ€ข Disable unused legacy filesystems (cramfs, freevxfs, jffs2)
โ€ข Restrict sysctl network stack (rp_filter = 1, tcp_syncookies = 1)
โ€ข Restrict SSH (PermitRootLogin no, MaxAuthTries 4)
High security with zero disruption to standard container runtimes and microservices.
CIS Level 2 High-Security / Defense Workloads โ€ข Restrict core dumps (fs.suid_dumpable = 0)
โ€ข Enforce Mandatory Access Control (SELinux / AppArmor enforcing)
โ€ข Disable USB storage drivers in kernel
Defense-in-depth; requires careful testing because strict AppArmor or disabled kernel modules can break Docker/Kubernetes networking.

๐Ÿ’ป Production Manifest: Packer Template with SSM Communicator

Building AMIs inside private subnets without public IPs requires using the AWS Systems Manager (SSM) Communicator, eliminating open inbound SSH ports:

packer {
  required_plugins {
    amazon = {
      version = ">= 1.3.0"
      source  = "github.com/hashicorp/amazon"
    }
    ansible = {
      version = ">= 1.1.0"
      source  = "github.com/hashicorp/ansible"
    }
  }
}

source "amazon-ebs" "ubuntu_hardened" {
  ami_name      = "corp-golden-ubuntu-22.04-cis-${formatdate("YYYY-MM-DD-hhmm", timestamp())}"
  instance_type = "c6i.large"
  region        = "us-east-1"

  # Find official Canonical base image
  source_ami_filter {
    filters = {
      name                = "ubuntu/images/hvm-ssd/ubuntu-jammy-22.04-amd64-server-*"
      root-device-type    = "ebs"
      virtualization-type = "hvm"
    }
    most_recent = true
    owners      = ["099720109477"] # Canonical Official Account
  }

  # Security: Build in private subnet using AWS SSM (Zero inbound SSH ports open!)
  subnet_id                   = "subnet-0a8b9c1d2e3f4a5b6"
  associate_public_ip_address = false
  ssh_interface               = "session_manager"
  communicator                = "ssh"
  ssh_username                = "ubuntu"
  iam_instance_profile        = "PackerSSMBuildInstanceProfile"

  # Encryption: Customer-Managed KMS Key
  encrypt_boot = true
  kms_key_id   = "arn:aws:kms:us-east-1:111111111111:key/golden-ami-master-key"

  tags = {
    OS          = "Ubuntu"
    Version     = "22.04"
    Hardened    = "CIS-Level-1"
    Environment = "SharedServices"
    Compliance  = "SOC2-PCI"
  }
}

build {
  sources = ["source.amazon-ebs.ubuntu_hardened"]

  # Run Ansible CIS Benchmark hardening playbook
  provisioner "ansible" {
    playbook_file = "./playbooks/cis-benchmark-hardening.yml"
    extra_arguments = [
      "--extra-vars", "ansible_python_interpreter=/usr/bin/python3"
    ]
  }

  # Execute automated OpenSCAP compliance audit
  provisioner "shell" {
    inline = [
      "sudo apt-get update && sudo apt-get install -y libopenscap8",
      "oscap xccdf eval --profile xccdf_org.ssgproject.content_profile_cis_level1_server --report /tmp/compliance-report.html /usr/share/xml/scap/ssg/content/ssg-ubuntu2204-ds.xml || true"
    ]
  }
}

โš ๏ธ Real-World Failure Modes, Exceptions & Break-Glass Playbooks

Exception 1: Cross-Account KMS Key Permission Access Denied on AMI Launch

  • The Outage: A Golden AMI is successfully built in Central Account 111111111111 and shared with Production Account 999999999999. In Production, the Auto Scaling Group launches a new instance from the AMI.
  • The Failure: The instance terminates immediately with:
    Client.InternalError: Client.InternalError: Client error on launch
    Or the launch template displays an opaque authorization error: Encoded authorization failure message.
  • The Root Cause: The Golden AMIโ€™s root EBS snapshot is encrypted with the Central Accountโ€™s KMS key. Although the AMI itself was shared via RAM, the Production Accountโ€™s Auto Scaling service role has no permissions to decrypt the KMS key or create cryptographic grants!
  • The Architectural Resolution: Update the KMS Key Policy in the Central Account to explicitly grant cross-account usage to the entire AWS Organization:
    {
      "Sid": "AllowCrossAccountMemberAccountDecryption",
      "Effect": "Allow",
      "Principal": { "AWS": "*" },
      "Action": [
        "kms:DescribeKey",
        "kms:Decrypt",
        "kms:ReEncrypt*",
        "kms:GenerateDataKey*",
        "kms:CreateGrant"
      ],
      "Resource": "*",
      "Condition": {
        "StringEquals": {
          "aws:PrincipalOrgID": "o-abcdef1234"
        }
      }
    }

Exception 2: Over-Hardening Kernel Parameters Breaking Container Networking

  • The Disaster: A platform engineer applies a strict CIS Level 2 hardening script to the Golden AMI. When Kubernetes worker nodes boot from the new AMI, Cilium / AWS VPC CNI crashes completely! Pods cannot obtain IP addresses, and DNS fails across the node.
  • The Root Cause: The CIS hardening script included:
    net.ipv4.ip_forward = 0
    net.ipv6.conf.all.disable_ipv6 = 1
    Container engines and CNI plugins strictly require net.ipv4.ip_forward = 1 to route packets between the host virtual ethernet interfaces (veth) and the physical network! Disabling IP forwarding prevents the Linux kernel from routing container traffic.
  • The Architectural Safeguard: Always maintain an Audited Hardening Exception List documented in version control:
    # /etc/sysctl.d/99-kubernetes-exceptions.conf
    # EXCEPTION: Required by AWS VPC CNI for container packet routing.
    net.ipv4.ip_forward = 1
    # EXCEPTION: Required for node-local loopback communications.
    net.ipv6.conf.lo.disable_ipv6 = 0

Exception 3: Packer Temporary Build VM SSH Timeout in Isolated Subnets

  • The Failure: When running Packer in enterprise VPCs, the build stalls for 10 minutes and aborts with: Timeout waiting for SSH.
  • The Root Cause: In enterprise environments, subnets have zero direct internet access, and security policies strictly forbid opening inbound port 22. Standard Packer attempts to open an SSH socket over public or private IP directly.
  • The Solution: Use the AWS Systems Manager Session Manager Communicator (ssh_interface = "session_manager"). Packer establishes an outbound TLS tunnel over the AWS SSM VPC Endpoint, requiring zero public IPs and zero inbound firewall openings!

๐Ÿ“ Staff Architect & SRE Interview Scenarios

โ“ ๐ŸŸข Low Difficulty: Why Must Boot Volumes Be Encrypted with Customer-Managed KMS Keys?

Question: Why do enterprise compliance policies prohibit using the default AWS managed key (aws/ebs) for Golden AMI encryption, requiring a Customer-Managed Key (CMK) instead?

Answer: The default AWS-managed KMS key (alias/aws/ebs) is owned by AWS and cannot be shared across different AWS accounts. If you build an AMI encrypted with aws/ebs in your Tooling Account, member accounts (Dev, Staging, Prod) are cryptographically blocked from ever launching instances from it! A Customer-Managed Key (CMK) allows platform architects to configure custom key policies, share access across AWS Organization member accounts, and enforce automated annual cryptographic rotation.

โ“ ๐ŸŸก Medium Difficulty: InSpec vs OpenSCAP for Automated Auditing

Question: How does automated compliance testing differ from standard unit testing in an image pipeline?

Answer: Standard unit tests verify application code functionality. Compliance tools (such as Chef InSpec or OpenSCAP) verify operating system state against regulatory rules:

  • They audit file ownership and permissions (verifying /etc/shadow is owned by root:root with permissions 0000).
  • They inspect kernel configurations (verifying sysctl net.ipv4.conf.all.accept_redirects == 0).
  • They scan installed software packages for forbidden utilities (verifying telnet, rsh, and ftp are uninstalled).
  • If a single rule fails, Packer halts and prevents the flawed image from ever registering as a production Golden AMI.
โ“ ๐Ÿ”ด Hard Difficulty: How Do You Patch an In-Use Golden AMI with a Critical Zero-Day?

Question: When a critical Linux kernel zero-day (such as Dirty Pipe or PwnKit) is published, what is the end-to-end automation sequence that patches thousands of running production instances?

Answer:

  1. Automated Trigger: Security advisory triggers the CI/CD pipeline via webhook or scheduled EventBridge rule.
  2. Bake & Audit: Packer boots a fresh VM, pulls the latest patched kernel package, executes CIS hardening, passes OpenSCAP audit, and registers Golden AMI v2.5.
  3. Launch Template Versioning: The pipeline updates the AWS Launch Template default version ($Latest) across all member accounts to point to the new Golden AMI ID.
  4. Autonomous Instance Refresh: The pipeline invokes StartInstanceRefresh on the Auto Scaling Groups with min_healthy_percentage = 100 and checkpoint_percentages = [10, 100].
  5. Zero-Downtime Rollout: Old instances drain active connections and terminate cleanly, replaced by freshly patched instances across the entire global fleet in under 4 hours with zero manual SSH access.
โ“ ๐ŸŸฃ Complex Difficulty: AMI Copying vs Direct Cross-Account Launching

Question: When sharing a Golden AMI across 50 member accounts, is it better to have member accounts launch directly from the shared AMI, or should member accounts copy the AMI into their local accounts first? What are the architectural trade-offs?

Answer:

  • Direct Cross-Account Launch (Recommended for standard fleets): Member accounts launch instances directly from the centralized AMI. Pros: Zero AMI storage duplication costs; updates are instantaneous. Cons: Requires cross-account KMS permissions on the central key.
  • AMI Copying (Mandatory for High-Security / Multi-Region DR): Each member account copies the AMI into its own local account and re-encrypts the snapshot using its own account-local KMS key. Pros: Complete isolation; if the central account or central KMS key is accidentally deleted, member accounts continue functioning independently; required for cross-region replication. Cons: High storage overhead and extra pipeline latency copying hundreds of gigabytes across accounts.