A sample hashicorp packer project to provision a new AWS AMI with node, pm2 and mongodb

Packer is an amazing tool to provision multi cloud virtual machine images with code. Making it easier to audit/maintain images and check provisioning code it into source control. Packer has three main building blocks:

  1. builders
  2. provisioners
  3. post processors

Our sample project to deploy node, pm2 and mongodb on an ubuntu 20 x86_64 server has three main files:

  1. app-server.json [ this will contain the packer config json ]
    "builders": [
            "type": "amazon-ebs",
            "profile": "my-local-aws-credentials-profile",
            "region": "ap-southeast-2",
            "ami_name": "ubuntu-node-mongo-packer-v1",
            "source_ami": "ami-0a43280cfb87ffdba",
            "instance_type": "t3.medium",
            "ssh_username": "ubuntu"
    "provisioners": [
            "type": "file",
            "source": "hellonode.js",
            "destination": "/tmp/hellonode.js"
            "type": "shell",
            "script": "app-server.sh"
    "post-processors": [
            "type": "manifest",
            "output": "output.json"

  1. app-server.sh [ this will contain the shell commands to provision the server ]
sleep 30

# Install node js
curl -fsSL https://deb.nodesource.com/setup_15.x | sudo -E bash -
sudo apt-get install -y nodejs

# Install pm2
sudo npm install -g pm2

# Install Mongo
sudo rm /etc/apt/sources.list.d/mongodb*.list
sudo apt update
sudo apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 656408E390CFB1F5
echo "deb [arch=amd64] http://repo.mongodb.org/apt/ubuntu $(lsb_release -sc)/mongodb-org/4.4 multiverse" | sudo tee /etc/apt/sources.list.d/mongodb-org.list
sudo apt update
sudo apt install -y mongodb-org
sudo systemctl enable mongod.service
sudo systemctl start mongod.service
sudo systemctl status mongod.service

# Configure pm2 to run hellonode on startup
mkdir -p ~/code/app-dist
mv /tmp/hellonode.js ~/code/app-dist/hellonode.js
cd  ~/code/app-dist/
sudo pm2 start hellonode.js
sudo pm2 startup systemd
sudo pm2 save
sudo pm2 list

  1. hellonode.js [ A sample nodejs http server for testing ]
var http = require("http");
var port = 8080;
var now = new Date();
  .createServer(function (req, res) {
    res.writeHead(200, { "Content-Type": "text/plain" });
    res.write("Hello World - this is node.js\n");
    res.write("Date on server: " + now.toGMTString());
  .listen(port, "");
console.log("Server running at port: " + port);

And finally to create the AMI just run the command below and a new AMI will appear in the console that can be used to launch new instances.

packer build app-server.json
October 21, 2020 · IaC · Hashicorp-Packer · AMI · AWS

Previous:Some notes on Zeebe (A scalable process orchestrator)
Next:How to samples with AWS CDK