Whats a bulletproof way to determine if I am running inside a vagrant machine?
Guest OS is Debian Linux, though if there are indicators per-os that would be great to have documented as well.
Whats a bulletproof way to determine if I am running inside a vagrant machine?
Guest OS is Debian Linux, though if there are indicators per-os that would be great to have documented as well.
AFAIK, there isn't a way outside of your own customizations. One idea that comes to mind is to touch a file that you then reference from your apps. Add something like config.vm.provision "shell", inline: "touch /etc/is_vagrant_vm"
to the bottom of your Vagrantfile and base your conditionals around the existence of that file.
Provisioning a file that you can check the existence of seems like the most reliable way to handle this.
Another option if you don't want to write files to the box would be to check for the existence of the vagrant
user itself:
grep -q '^vagrant:' /etc/passwd && echo 'Vagrant environment: true'
This is not foolproof as others have indicated, and it is possible (although uncommon) to have a vagrant box that uses a different user to connect as.
Checking the user's existence also would not work reliably if you have machines in your environment with a user account called vagrant that are not actually vagrant boxes, but that would also be fairly uncommon.
I don't know if there is any bulletproof way for this, but one thing I often do is to config my vagrant environment's shell UI to be different from the shell UI of my host machine. This way I can tell the difference at first glance. It also helps if you want to distinguish among multiple vagrant environments.
To customize the shell UI, oh-my-zsh will come in handy.
Assuming you don't run a vagrant instance in your vagrant instance:
if which vagrant > /dev/null 2>&1; then
echo "This is most likely the host"
fi
You can use facter
facter | grep vagrant
This is how I was able to answer the question with a very small chunk of bash. The -e
flag checks if the file exists. Change provision
to a file path that makes sense for your build.
#!/usr/bin/env bash
user=$USER
provision=/vagrant/Vagrantfile
if [ -e $provision ]
then
echo "Vagrantfile found..."
echo "Setting $user to vagrant..."
user=vagrant
fi
# Example usage
cd /home/$user
Tested on "centos/7"
In vagrant your are in control of which IP you are running against, so you could change it to for example 192.168.0.10
Then:
curl localhost:8080/health => in local e.g spring-boot
curl 192.168.0.10:8080/health => in vagrant
NOTE: /health assumes spring-boot but you could also use your own implementation of a /health endpoint as well