Search code examples
vagrantenvironment-variablesvagrantfilevagrant-provision

How can I make environment variables available during Vagrant provisioning?


I would like to make environment variables available to Vagrant during provisioning so that I can run some commands that rely on them for credentials. Specifically aws cli and pg_restore.

For example, pg_restore needs access to the $PGPASS variable which I'm setting in my .bash_profile. I've tried running source /home/vagrant/.bash_profile which exports the required AWS environment variables, but later in my provisioning block the aws command fails because the environment variables are not set.

.bash_profile

export AWS_ACCESS_KEY_ID='keyid'
export AWS_SECRET_ACCESS_KEY='secret'

Vagrantfile provisioning block

config.vm.provision :shell, run: "always", inline: <<-SH.gsub(/^\s*/,"")
  source /home/vagrant/.bash_profile
  aws s3 cp s3://bucket/sql/file /tmp/file # fail, missing credentials
  echo $(printenv | grep AWS_) # outputs blank line
SH

Solution

  • You run the provisioning as root user which your bash is for vagrant user so make sure to run the provisioning as vagrant by adding privileged: false

    config.vm.provision :shell, privileged: false, run: "always", inline: <<-SH.gsub(/^\s*/,"")
      source /home/vagrant/.bash_profile
      aws s3 cp s3://bucket/sql/file /tmp/file # fail, missing credentials
      echo $(printenv | grep AWS_) # outputs blank line
    SH