Automation with Hashicorp Packer #7: Script Provisioner
Table of Contents
Introduction
This tutorial provides a detailed guide on using the Script Provisioner in Hashicorp Packer. Packer is a powerful tool for creating custom machine images across various platforms such as AWS, Azure, GCP, and more. The Script Provisioner allows you to execute scripts during the image creation process, making it easier to automate software installation and configuration.
Step 1: Set Up Your Packer Template
- Create a new directory for your Packer project.
- Inside the directory, create a JSON file for your Packer template. Name it
template.json
. - Add the basic structure to the JSON file:
{ "builders": [ { "type": "amazon-ebs", "access_key": "YOUR_AWS_ACCESS_KEY", "secret_key": "YOUR_AWS_SECRET_KEY", "region": "us-east-1", "source_ami": "ami-12345678", "instance_type": "t2.micro", "ssh_username": "ec2-user", "ami_name": "my-custom-ami" } ], "provisioners": [] }
- Replace placeholder values with your actual AWS credentials and desired configurations.
Step 2: Add the Script Provisioner
- In the "provisioners" section of your JSON file, add the Script Provisioner configuration:
{ "type": "script", "scripts": [ "install-software.sh" ] }
- Save your changes to the
template.json
file.
Step 3: Create Your Installation Script
- In the same directory, create a shell script named
install-software.sh
. - Add commands to install the necessary software. For example:
#!/bin/bash sudo yum update -y sudo yum install -y httpd sudo systemctl start httpd sudo systemctl enable httpd
- Make sure to give execution permissions to the script:
chmod +x install-software.sh
Step 4: Build the Packer Image
- Open your terminal and navigate to your project directory.
- Run the Packer build command:
packer build template.json
- Monitor the output to ensure that the image is being created successfully and that the script runs without errors.
Step 5: Verify the Created Image
- Once the build is complete, log in to your AWS Management Console.
- Navigate to the EC2 dashboard and check the AMIs section to ensure your custom image appears.
- Launch an instance using your new AMI to verify that the software was installed correctly.
Conclusion
In this tutorial, you learned how to utilize the Script Provisioner in Hashicorp Packer to automate the installation of software in your custom machine images. By following these steps, you can streamline the process of creating images tailored to your needs. Next, consider exploring more advanced features of Packer, such as using other provisioners or building images for different platforms.