Wasasando

Shell provisioning inside a loop produces unexpected results

I want to create three VMs using single Vagrantfile. I also want to create a user and give that user sudo rights. The Vagrantfile below works, but the shell provisioning script appears to be run three times on each VM. Resulting in three lines added to `/etc/sudoers` rather than the one I was expecting. Is it not possible to use shell provisioning inside a loop like I've done?

The Vagrantfile:

# -*- mode: ruby -*-
# vi: set ft=ruby :

# Vagranyfile API/syntax version
VAGRANTFILE_API_VERSION = "2"

Vagrant.require_version ">= 2.2.0"

# createVM function
# Function is required as Vagrant treats stuff inside the .confihure
# as a closure, and looping there causes weirdness.
def createVM(config, i)
config.vm.define "server#{i}" do |server|
server.vm.hostname = "server#{i}"
server.vm.box = "generic/ubuntu1804"
server.vm.box_url = "generic/ubuntu1804"
server.vm.network :private_network, ip: "10.1.1.1#{i}"

server.vm.provider :libvirt do |libvirt|
libvirt.memory = 1024
libvirt.cpus = 2
end
end

config.vm.provision :shell do |shell|
shell.path = 'vagrant/provision.sh'
end
end

Vagrant.configure(VAGRANTFILE_API_VERSION) do |config|
for i in 1..3 do
createVM(config, i)
end
end

And the provisioning.sh script:

#!/bin/bash

# apt-get update
# apt-get -y install git vim

if $(cat /etc/passwd | grep mark &> /dev/null) ; then
echo "User already exists"
else
useradd mark -s /bin/bash -m -G adm
fi

chpasswd << 'END' mark:vagrant END # Add user mark to sudoers file echo 'mark ALL=(ALL:ALL) ALL' >> /etc/sudoers

Exit mobile version