Create Ubuntu 20.04 AMI hardened according to CIS benchmarks using Terraform and Ansible


  1. All actions are performed using GitHub actions workflows.
  2. Terraform is used to create a temporary VPC, IAM Role, and EC2 instance.
  3. After the infrastructure has been deployed, an Ansible playbook is executed on the remote EC2 instance using the AWS Systems Manager Run command and the AWS-ApplyAnsiblePlaybooks document. The instance is in a private subnet and does not require any open inbound ports.
  4. AMI creation is triggered for the instance after playbook execution is completed.
  5. Terraform destroys the temporary infrastructure created after the AMI is created.
  6. Static resources like the Terraform State, the Ansible playbook zip, and the output of the Systems Manager Run command are stored in Amazon S3.

Design decisions and challenges

EC2 instance and private subnet connectivity

GitHub Actions workflow design

  • The first part of the workflow creates the infrastructure and starts Ansible playbook execution.
  • The second part of the workflow creates the AMI and deletes the infrastructure.
  • Allows manual changes to the instance before the AMI is created.
  • Reduces GitHub actions execution time since the second part doesn’t have to wait for the Ansible playbook execution to complete.



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Kaustubh Khavnekar

Kaustubh Khavnekar

Senior Platform Engineer at Quantiphi