Cloud and DevOps have transformed infrastructure into cattle, not pets. Hardening must be embedded into the code that provisions servers—Terraform, CloudFormation, Packer—so every instance is born hardened and compliance is continuously enforced. This lesson connects the dots between OS hardening scripts, configuration management, and immutable infrastructure, turning your security baselines into automated guardrails.
Packer automates the creation of machine images (AMI, VHD, etc.) from a base ISO. You can inject provisioning scripts (Ansible, Bash) during the build to apply hardening settings, remove unnecessary packages, and run compliance scans. The resulting image is a known-good, hardened baseline. No more manually hardening after deployment. Any new instance from that image inherits security.
// Packer template snippet: provision with Ansible
{
"builders": [{
"type": "amazon-ebs",
"source_ami": "ami-0c55b159cbfafe1f0",
"instance_type": "t2.micro",
"ssh_username": "ubuntu"
}],
"provisioners": [{
"type": "ansible",
"playbook_file": "hardening.yml"
}]
}This Packer template launches a base AMI, runs the Ansible hardening playbook, and then creates a new AMI. All subsequent instances are hardened from first boot.
Terraform can enforce security groups, IAM roles, and launch configurations that ensure instances boot with the right settings. Use userdata scripts to register with a configuration management server, or apply a final hardening run via a pipeline. Terraform policy as code (Sentinel, OPA) can prevent provisioning of non-compliant resources (e.g., EC2 without encryption). The infrastructure definition itself becomes the enforcement point.
💡 Use 'terraform plan' to preview changes and ensure security groups aren't inadvertently opened. Integrate Terraform into CI/CD with branch protection.
| IaC Stage | Tool | Hardening Activity |
|---|---|---|
| Image creation | Packer + Ansible | OS hardening, package removal, baseline scan |
| Infrastructure provisioning | Terraform/CloudFormation | Security groups, IAM roles, encryption, logging |
| Configuration management | Ansible/DSC | Post-boot drift correction, continuous compliance |
| Policy enforcement | OPA/Sentinel | Prevent deployment if security policies violated |
The pinnacle of continuous hardening is immutable infrastructure: when a server drifts or needs a patch, you don't log in and fix it; you build a new golden image and replace the server. This eliminates configuration drift and makes rollbacks trivial. Combined with blue/green deployments, it reduces the attack window dramatically. The OS becomes a disposable asset, not a legacy system.
⚠️ Immutable infrastructure works best for stateless, cloud-native applications. Stateful databases and legacy apps may require a hybrid approach with in-place hardening.
Verify exercises to earn ★ 180 XP and unlock next lab level.