As a DevOps engineer you always encounter the scenario that you need to bake the image with which to spin up the new servers on the Public Clouds like AWS/Azure/GCP. This article introduce how to bake the image using HashiCorp Packer and use it via IaC tools like Terraform on the Public Cloud (take AWS as an example) in a continuous manner.
- Follow the tutorial on HashiCorp official website to install Packer on your developer machine. https://developer.hashicorp.com/packer/tutorials/docker-get-started/get-started-install-cli.
- Go to your AWS Management Console and generate an Access key under the IAM user with the necessary permission to build an AMI image. Export the credentials on your developer machine like the below. export AWS_ACCESS_KEY_ID= export AWS_SECRET_ACCESS_KEY=
- Prepare your script for building the AMI with Packer in JSON format.
- Use the command below to upgrade your script in JSON into HCL format. packer hcl2_upgrade .json
- Go to your HashiCorp Cloud Platform website and generate the tokens required to push the built AMI onto Packer repo. Export the tokens into your env vars on your developer machine. export HCP_CLIENT_ID= export HCP_CLIENT_SECRET=
- Build your AMI with the command below. packer build .hcl And Packer will upload the newly built AMI onto Packer repo on HCP website.
- Add the required snippet into your Terraform code. Note: the value for bucket_name and region can be set according to your actual situation.
- Refer to the ID of built AMI with the below statement in your Terraform code. image_id = data.hcp_packer_image.sample.cloud_image_id
- So Terraform will always get the AMI ID of the newly built AMI as the referral to spin up the new EC2 instance.
Therefore you can build your AMI and use the ID of the output in your Terraform code in a continuous manner. And most importantly it's totally FREE. Hope it can help with your daily work.
Top comments (0)