Reputation:
With Vagrant, is it possible to pass args from say vagrant up {args}
into the provisioned file?
I want people to be able to pass in their github account name so that I can pass it to the provisioned file - something like:
vagrant up iwayneo
and iwayneo
is then passed to the provisioned file - is this possible?
If I do the following in an sh script that is ran before vagrant up
:
echo "Please enter the local username - for vagrant boxes enter vagrant:"
read uname
export LOCALUSER=$uname
echo " " >> ~/.bashrc
echo "LOCALUSER=$uname" >> ~/.bashrc
echo "Please enter the bitbucket username:"
read bbuname
export BITBUCKETUSER=$bbuname
echo " " >> ~/.bashrc
echo "BITBUCKETUSER=$bbuname" >> ~/.bashrc
echo "Please enter bitbucket password:"
read bbpass
export BITBUCKETPASS=$bbpass
echo " " >> ~/.bashrc
echo "BITBUCKETPASS=$bbpass" >> ~/.bashrc
echo "configured for local username $uname, bitbucket username $bbuname and bitbucket pass $bbpass"
source ~/.bashrc
And then the following in my vagrant file:
puts "Current user is #{ENV['LOCALUSER']}"
if !ENV.has_key?("LOCALUSER")
raise "Please specify the `LOCALUSER` environment variable - you can do this by running config.sh"
end
if !ENV.has_key?("BITBUCKETUSER")
raise "Please specify the `BITBUCKETUSER` environment variable - you can do this by running config.sh"
end
if !ENV.has_key?("BITBUCKETPASS")
raise "Please specify the `BITBUCKETPASS` environment variable - you can do this by running config.sh"
end
The LOCALUSER raise is called and the puts "Current user is #{ENV['LOCALUSER']}"
yields Current user is
so it is definitely not taking.
AHAAAA - I have to do it using the one liner format? Is there a way to do this not using that format?
Remarked the answer as correct but any help here would be really appreciated
Upvotes: 1
Views: 2132
Reputation: 4176
The most common way to do this kind of thing is to use environment variables. For example:
ACCOUNT=iwayneo vagrant provision
Then you can use it in Vagrantfile using the ENV class. Assuming you want to pass it as an argument to a shell provisioner script, you can use something like this:
if !ENV.has_key?("ACCOUNT")
raise "Please specify the `ACCOUNT` environment variable"
end
Vagrant.configure("2") do |config|
config.vm.provision "shell", path: "script.sh", args: ENV["ACCOUNT"]
end
EDIT: Addition for the sh script setup:
You have to source
your sh script for the variables to take effect in the shell session. Otherwise they are only available during the script run for that subshell. Similarly, you also need to export
the variables in .bashrc for them to be available in the Vagrant process.
All this is related to how shells and child processes work with environment variables. Nothing special with Vagrant.
Upvotes: 2