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.


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


  • 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 like so, and save it in the folder where I run packer from:

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 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):


    "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": "",
            "destination": "~/"
            "type": "shell",
            "remote_folder": "~",
            "inline": [
                "sudo bash ~/",
                "rm ~/"
Enter fullscreen mode Exit fullscreen mode
  • Once I've setup my 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 file over to the home folder of the user on the instance, runs the script as sudo and then deletes the file (to clean up).

Top comments (0)