Skip to content
Tutorials Center
My learning

Topics

Lesson 12 of 36 ยท Provisioning

The Shell Provisioner

Use the Vagrant shell provisioner: inline scripts, script files, arguments, environment variables, privileged mode, heredocs, error handling and examples.

The shell provisioner is the simplest and the most used. It copies a script into the guest and runs it. Because almost every Linux task can be expressed as shell commands, it takes you a long way, from installing packages to creating databases. Its weakness is that you carry the whole burden of idempotence and error handling yourself. This lesson shows every option and the habits that keep shell provisioning reliable.

Inline scripts

For a few commands, write them directly in the Vagrantfile with inline::

Ruby
Vagrant.configure("2") do |config|
  config.vm.box = "bento/ubuntu-24.04"
  config.vm.provision "shell", inline: "apt-get update && apt-get install -y nginx"
end

For several lines use a Ruby heredoc. <<~SHELL removes the common indentation, and the closing word must sit alone on its line:

Ruby
config.vm.provision "shell", inline: <<~SHELL
  set -euxo pipefail
  export DEBIAN_FRONTEND=noninteractive
  apt-get update
  apt-get install -y nginx git
  systemctl enable --now nginx
SHELL

set -euxo pipefail is a good first line: -e stops at the first failing command, -u fails on unset variables, -x prints each command (which makes the Vagrant output readable), and pipefail makes a failing command inside a pipe count as a failure.

Script files

Longer scripts belong in their own files, where editors highlight them and tools like ShellCheck can lint them:

Ruby
config.vm.provision "shell", path: "scripts/bootstrap.sh"

The path is relative to the Vagrantfile (a URL also works). Vagrant uploads the file to a temporary location in the guest and runs it. Because the project folder is already shared as /vagrant, you could also run inline: "/vagrant/scripts/bootstrap.sh", but path: works even when the synced folder is disabled, so it is preferred.

A typical script:

Terminal
#!/usr/bin/env bash
set -euo pipefail

echo "Installing database and tools"
export DEBIAN_FRONTEND=noninteractive
apt-get update -y
apt-get install -y postgresql git curl

# idempotent: create the role only if it does not exist
sudo -u postgres psql -tc "SELECT 1 FROM pg_roles WHERE rolname='shop'" | grep -q 1 \
  || sudo -u postgres psql -c "CREATE ROLE shop LOGIN PASSWORD 'devpassword'"

Arguments and environment variables

Pass values to a script with args: (like command-line arguments) or env: (environment variables):

Ruby
config.vm.provision "shell",
  path: "scripts/install-app.sh",
  args: ["--version", "3.2.1", "--env", "development"],
  env:  { "APP_USER" => "deploy", "DB_NAME" => "shop_dev" }

Inside the script, $1, $2, ... hold the arguments and $APP_USER the variable. This keeps scripts generic and lets the Vagrantfile decide the specifics. Never put real secrets in the Vagrantfile; it is usually committed. For development passwords that is acceptable, for anything else read them from your host environment (ENV["API_KEY"]) and pass them through env:.

Privileged, binary and other options

Option Default Meaning
privileged true Run through sudo as root. Set false to run as the vagrant user.
run "once" "always" or "never", see Provisioning overview
upload_path /tmp/vagrant-shell Where the script is uploaded in the guest
reset false Reboot connection after the script (reconnect SSH, useful after changing groups)
reboot false Reboot the guest after the script finishes
binary false Keep Windows line endings (CRLF) unchanged
keep_color false Keep colors in the output
name A label used in the output and for --provision-with

The privileged: false option is important for user-level installs:

Ruby
config.vm.provision "shell", privileged: false, inline: <<~SHELL
  git clone https://github.com/example/dotfiles.git ~/dotfiles
  echo 'alias ll="ls -la"' >> ~/.bashrc
SHELL

With privileged: true that clone would end up in /root, not in /home/vagrant. Use reset: true when you add the user to a group (for example usermod -aG docker vagrant) and a later step needs the new group: the SSH session is restarted and picks up the membership.

Scripts written on Windows may have CRLF line endings. A script with \r at the end of each line fails with errors like bash: /tmp/vagrant-shell: /bin/bash^M: bad interpreter. Vagrant normally converts them, but if you hit it, configure Git with core.autocrlf or an .gitattributes entry such as *.sh text eol=lf.

Several provisioners and shared logic

You can declare any number of shell provisioners. Name them so the output is clear and you can re-run one:

Ruby
Vagrant.configure("2") do |config|
  config.vm.provision "system", type: "shell", path: "scripts/system.sh"
  config.vm.provision "database", type: "shell", path: "scripts/database.sh"
  config.vm.provision "app", type: "shell", path: "scripts/app.sh", privileged: false
end
CONSOLE
$ vagrant provision --provision-with database
==> default: Running provisioner: database (shell)...

Ruby also lets you generate provisioners in a loop, for example one per package group, or read a list of packages from a file:

Ruby
packages = %w[git curl vim htop]
config.vm.provision "shell", inline: "apt-get install -y #{packages.join(' ')}"

Building a safe script: a stand-in

A very common error is a script that works the first time and breaks the second. The stand-in below is Ruby that simulates a guest with a tiny "state" (a set of installed packages and a config file), and runs an unsafe and a safe provisioning step twice, so you can see how idempotence works. It is a model, not shell.

Ruby Idempotent versus non-idempotent steps (stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

After three runs the unsafe version has three copies of the same line in the profile, while the safe version has one. Real scripts need exactly this care, with grep -q, [ -f file ] guards, mkdir -p, ln -sf, id user || useradd user and command -v tool || install_tool.

Tips

  • Always start scripts with set -euo pipefail and set DEBIAN_FRONTEND=noninteractive for apt.
  • Echo a clear message at each step; Vagrant output is your build log.
  • Prefer many small named provisioners over one huge script, so you can re-run a part.
  • Keep shell scripts portable between box families only if you must; otherwise target your one distribution.
  • If provisioning gets complicated (templates, services, users, many hosts), consider a configuration management tool, see Config management provisioners.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which option runs a script file located next to the Vagrantfile?

    The path: option uploads and runs a script file; inline: is for commands written in the Vagrantfile.
  2. 2. A script clones dotfiles into ~ but they appear in /root. What is the most likely fix?

    Shell provisioners run as root by default; privileged: false runs as the vagrant user.
  3. 3. What does set -e do in a provisioning script?

    With -e, the first failing command terminates the script, so Vagrant reports the failure instead of continuing with a half-configured machine.
  4. 4. How do you pass an environment variable to a shell provisioner?

    The env: option takes a hash of names and values that the script sees as environment variables.

Summary

  • inline: is for short commands, path: for script files; use heredocs for multi-line inline scripts.
  • args: and env: pass parameters; privileged: false runs as the vagrant user; reset: and reboot: restart sessions.
  • Start scripts with set -euo pipefail and make every step idempotent.
  • Name provisioners and split scripts so you can re-run a single part.
  • Beware of CRLF line endings when scripts are edited on Windows.

Next: File Provisioner and Triggers