Shell Provisioner

Next we need to do things on the server (otherwise, what's the point?). To do so, we'll configure Provisioners.

The easiest it to run shell/bash scripts. Here's what that looks like using a Shell provisioner.

1{
2 "min_packer_version":"1.0.0",
3 "variables":{ Click to show }
4 "infra_name": "cloudcasts",
5 "infra_env": "",
6 "aws_region": "us-east-2",
7 "aws_instance": "t3.small"
8 },
9 "builders":[
10 { Click to show }
11 "type":"amazon-ebs",
12 "ami_name":"{{user `infra_name`}}-{{user `infra_env`}}-{{timestamp}}-app",
13 "instance_type":"{{user `aws_instance`}}",
14 "region":"{{user `aws_region`}}",
15 "profile": "cloudcasts",
16 
17 "source_ami_filter": {
18 "filters": {
19 "architecture": "x86_64",
20 "name": "ubuntu/images/hvm-ssd/ubuntu-focal-20.04-amd64-server-*",
21 "root-device-type": "ebs",
22 "virtualization-type": "hvm"
23 },
24 "most_recent": true,
25 "owners": [
26 "099720109477"
27 ]
28 },
29 "ssh_username":"ubuntu",
30 "launch_block_device_mappings":[
31 {
32 "device_name":"/dev/sda1",
33 "volume_size":8,
34 "delete_on_termination":true,
35 "encrypted":false,
36 "volume_type":"gp3",
37 "throughput": 125,
38 "iops": 3000
39 }
40 ],
41 "tags":{
42 "Name":"{{user `infra_name`}}-{{user `infra_env`}}-{{timestamp}}-app",
43 "Project":"{{user `infra_name`}}",
44 "Environment":"{{user `infra_env`}}",
45 "Role":"baked-ami",
46 "Unique":"baked-ami-{{timestamp}}",
47 "ManagedBy":"packer",
48 "Component":"app"
49 }
50 }
51 ],
52 "provisioners":[
53 {
54 "script": "{{template_dir}}/scripts/base.sh",
55 "type": "shell"
56 }
57 ]
58}

Here's the contents of scripts/base.sh:

1#! /usr/bin/env bash
2 
3set -e
4 
5# Helps clear issues of not finding Ansible package,
6# perhaps due to updates running when server is first spun up
7sleep 10
8 
9export DEBIAN_FRONTEND="noninteractive"
10 
11# Install Ansible
12echo ">>>>>>>>>>> INSTALLING ANSIBLE"
13sudo apt-get update
14sudo apt-get install -y ansible

As you can see, it installs Ansible, which we'll use next.

Don't miss out

Sign up to learn when new content is released! Courses are in production now.