DEV Community

Heathesh Bhandari
Heathesh Bhandari

Posted on

Running shell commands as sudo using packer

Problem Statement:

How do I run shell commands as sudo when creating an AMI using packer.

Solution:

Create a separate file with your shell script in it, and run that script as sudo.

Example:

  • Create a file you wish to run, for example, if I'm using an operating system that uses yum and I want to update my operating system on launch and then create a folder for my application called my-app and assign relevant permissions, I would create a startup.sh like so, and save it in the folder where I run packer from:

startup.sh

sudo yum update -y
sudo mkdir -p /my-app
sudo chmod 755 -R /my-app
Enter fullscreen mode Exit fullscreen mode
  • Then I create my packer.io config file like so (I'm using AWS for this example, so I've pre-setup a VPC, subnet and IAM role to run this):

builder.json

{
    "variables": {
        "base_ami": "ami-xxxxxxxxxxx"
    },
    "builders": [
        {
            "type": "amazon-ebs",
            "region": "eu-west-1",
            "source_ami": "{{user `base_ami`}}",
            "instance_type": "t2.micro",
            "ssh_username": "ec2-user",
            "ami_name": "my-ami {{timestamp}}",
            "vpc_id": "vpc-xxxxxxxx",
            "subnet_id": "subnet-xxxxxxx",
            "iam_instance_profile": "MyAwsServerRole"
        }
    ],
    "provisioners": [
        {
            "type": "file",
            "source": "startup.sh",
            "destination": "~/startup.sh"
        },
        {
            "type": "shell",
            "remote_folder": "~",
            "inline": [
                "sudo bash ~/startup.sh",
                "rm ~/startup.sh"
            ]
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode
  • Once I've setup my startup.sh script and my builder.json configuration, I validate them and then run the script.
packer validate builder.json
packer build builder.json
Enter fullscreen mode Exit fullscreen mode
  • This packer config file creates an instance, copies the startup.sh file over to the home folder of the user on the instance, runs the script as sudo and then deletes the startup.sh file (to clean up).

Discussion (0)