Last active
October 26, 2022 01:42
-
-
Save alitoufighi/879f0fef836ccbea21b7d133cbb44377 to your computer and use it in GitHub Desktop.
When using dynamic ip allocation with kvm, it's hard to find vm ips for ssh, etc. you can schedule this cron job to add dns records based on the allocated ip addresses (by dnsmasq) and their name. Then, you can access them via their names instead of ip.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
get_etc_hosts_contents() { | |
hosts_lines=$(cat /etc/hosts | wc -l) | |
grep "virsh-auto-hosts-updater" /etc/hosts -B $hosts_lines | |
if [[ $? -eq 1 ]]; then | |
contents=$(cat /etc/hosts) | |
contents="$contents\n\n\n#### virsh-auto-hosts-updater: Lines below are updated automatically. DO NOT EDIT THIS LINE\n" | |
printf "$contents" | |
fi | |
} | |
dhcp_leases=$(virsh net-dhcp-leases default | tail -n +3) | |
etc_hosts_contents=$(get_etc_hosts_contents) | |
mapping="" | |
while read -r vminfo | |
do | |
ip=$(echo $vminfo | awk '{print $5}' | cut -d/ -f1) | |
name=$(echo $vminfo | awk '{print $6}') | |
mapping="$mapping$ip\t$name\n" | |
done <<<$dhcp_leases | |
printf "$etc_hosts_contents\n$mapping" | sudo tee /etc/hosts |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment