Packer Sample Script
Sample script to create an image with Packer
Website Visitors:In this tutorial, we will explain about a sample script to create an instance, deploy software and create an image from it. Before you run the script, make sure to install aws cli and add your AWS access key and secret key in ~/.aws/credentials file or checkout the Packer Variables tutorial to know different ways to use your AWS credentials with Packer.
Simple Packer script to create an instance
|
|
For the above script, you should search for the latest source ami and update the value every time. With Packer you can automate this step as well. You don’t have to search for the latest image every time. Instead Packer will search for the latest AMI and use it to deploy an image.
Install nginx with Packer
Below script creates instance from AWS, installs nginx, creates an image from it, saves it to your AWS account and terminates that instance immediately. Here websitefiles folder is the source folder containing all your html files. They are uploaded to the Downloads folder on the instance, and then copied to /var/www/html folder.
|
|
You can now deploy an instance using the new AMI that you’ve just created.
aws ec2 run-instances --instance-type t2.micro --count 1 --key-name KeyPairPem --image-id IMAGEID
Ansible with Packer
You can also add ansible and other configuration management tools for installing softwares in the place of shell given above. To use ansible in your Packer configuration, add provisioner section as shown below:
|
|
Create a file called ansible.yml and add below code to it. In the same folder create a folder called websiteFiles and add all your website files into that folder. Below script will install nginx and copy all the files from websiteFiles folder in your machine to the newly deployed instance.
|
|
In order to use the role nginxinc.nginx, we have to download the same from ansible galaxy. Create file called nginx.yml and add the code, - src: nginxinc.nginx
to it. Next in your terminal navigate to the folder where you have nginx.yml file and run, ansible-galaxy install -r nginx.yml
command. Now run your packer build command: packer build template.json
. This will start packer script, and it will call ansible playbook and run the nginx install.
Suggested Article
If you’d like to go through Packer definitions, check it out here or browse other articles on Packer here
Conclusion
In this article, we’ve provided you with a sample Packer script and its basic usage. We hope you have learned something new in this article. All other DevOps categories are listed here: DevOps Tools. Have a look at the posts as per your topic of interest.
Please feel free to share your thoughts about this article in the comments section below.
Your inbox needs more DevOps articles.
Subscribe to get our latest content by email.