I want my local development environment to have an environment variable set so that my PHP app can read it.
In my Vagrantfile I have:
config.vm.provision "shell", inline: <<-SHELL
## Set environment variables...
echo "export APP_ENV=development" > /home/vagrant/.profile
echo "export APP_ENV=development" > /home/vagrant/.bashrc
...
In my PHP code I added:
var_dump(shell_exec( 'whoami' ));
var_dump(shell_exec( 'echo $APP_ENV' ));
The output is:
string(8) "vagrant "
string(1) " "
I remembered to re-provision my box (many times). I'm mostly confused why the second var_dump
isn't returning "development" but I'm especially confused why it would return a single space rather than an empty string or NULL if it's not set at all. What am I missing?
Vagrant 1.8.5
Virtualbox 5.1.30r118389
UPDATE:
When I SSH into the box as vagrant user, and run $ echo $APP_ENV
, it returns "development".
I added source /home/vagrant/.profile
to the provisioning script and PHP still can't see the var I'm setting.
UPDATE2:
I think Apache might be running as www-data
. Here's some screenshots from my phpinfo()
.
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
so the files will be owned by vagrant
and they will be run
config.vm.provision "shell", privileged: false, inline: <<-SHELL
## Set environment variables...
echo "export APP_ENV=development" >> /home/vagrant/.profile
echo "export APP_ENV=development" >> /home/vagrant/.bashrc
...
Got it! I was modifying /home/vagrant/.profile but Apache is running as www-data
so here's what works:
config.vm.provision "shell", inline: <<-SHELL
## Set environment variables...
echo "export APP_ENV=development" >> /etc/apache2/envvars
sudo service apache2 restart
...
I have to restart apache for the changes to take effect. If you restart apache elsewhere in your script you should be able to skip the second line.
If this helped you, upvote Frédéric Henri's answer which pointed me in the right direction to figure this out.
NOTE One problem with the current solution is that it will add a new line to /etc/apache2/envvars every time you provision. So after a few iterations, I see
export APP_ENV=development
export APP_ENV=development
export APP_ENV=development
This is not ideal :-/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.