Get IP address from VM
On this page I gathered approaches to get virtual machine ip address from host shell when VM already initialized and started.
Example 1. Simple command
Simple example, only with shell commands:
$ vagrant ssh -c "ip address show eth0 | grep 'inet ' | sed -e 's/^.*inet //' -e 's/\/.*$//'" vm-instance-name
Example 2. Command with python
Another example with python. More handy for complex logic and quick changes in code:
$ vagrant ssh -c "hostname -I | python3 -c 'import fileinput; ip=list(fileinput.input())[0].split(\" \")[0].strip(); print(ip)'" vm-instance-name
Example 2. Build inventory
A bit more complex example to build list of hosts from running Vagrant environment
build-vagrant-inventory.sh
#!/bin/bash
function getIp {
ip=$(vagrant ssh -c "hostname -I | python3 -c 'import fileinput; ip=list(fileinput.input())[0].split(\" \")[0].strip(); print(ip)'" $1)
echo $ip
}
function getAllRunningVMList {
for vm in $(vagrant status | grep running | awk '{print $1}')
do
echo $vm
done
}
list=$(getAllRunningVMList)
rm -f inventory.list
for entry in $list
do
ip=$(getIp $entry)
echo "$entry:$ip" >> inventory.list
done
## Output file "inventory.list"
# consul-1:10.211.55.85
# consul-2:10.211.55.89
# consul-3:10.211.55.90
# lb-1:10.211.55.87
# gw-1:10.211.55.88
# srv-1:10.211.55.86