Build Image from Ansible code and persist them on local or in AWS ECR
In a previous article, we have seen how to create a testable Ansible role with Molecule and Docker. This role installs and configures WordPress in a Docker image. This part was only covered tests using Molecule. Here we are going to go further to reuse this work to build the Docker image with Packer.
We will see how to configure Packer through manifests. There will be two manifests, one to build the image locally and the other remotely. We will persist the remote image in AWS Elastic Registry (ECR). For both manifests, we will use the Ansible provisioner and Docker post-processors. The provisioner will reuse the WordPress role. The post-processors will build persist the image in the Docker registry.
We will use Terraform to deploy and configure AWS ECR. Then we will create a Packer manifest to build the image on local. Β A docker-compose file will run the image to ensure all is working well. Finally, we will create the second Packer manifest to tag and push the image to AWS ECR.
Install The Prerequisites
The prerequisites presented here are for MacOSX. Adapt versions to your platform architecture.
At the project root, create the terraform structure and the aws-ecr module:
The module state is stored in AWS S3. You have to create your own S3 bucket and replace the value in terraform/environments/dev/aws-ecr/main.tf:
Just below, you have the content of the module aws-ecr files:
Initialize and apply the layer:
Connect to AWS web console and ensure the registry is ready:
Create The Ansible File Hierarchy
At the root of the project, create the ansible directory:
Create the WordPress playbook in ansible/playbooks/wordpress.yml:
The WordPress ansible of the previous article needs to be put into ansible/roles .
Persist The Docker Image Locally
Create the packer directory:
We create a script to install ansible in the container before running the Ansible provisioned:
Here the scripts/install-ansible.sh :
There is also another script scripts/cleanup.sh to clean up the container after Ansible has finished :
Here is the Packer manifest to build the image:
Build the image on local docker. The image version is passed as a variable :
You can check the image is present:
Test Local Image With Docker-Compose
Once WordPress is ready, you can access it on localhost:
Persist The Image In AWS ECR
Comparing to the previous manifest, the one for AWS ECR adds docker-push post-processor :
Build the image. The docker repository URL is taken from the outputs of the aws-ecr module and passed as a variable :
Conclusion
We have seen how to reuse an existing Ansible role to create Docker images with Packer. Here we have worked with a local Docker registry and a remote one in AWS ECR deployed with Terraform. The two methods have their own Packer manifest. We have checked the generated image was working with docker-compose.