Skip to content

Instantly share code, notes, and snippets.

@dbvan
Last active August 1, 2021 11:40
Show Gist options
  • Save dbvan/b1f8ea840e1694fd76052aec87e58f8a to your computer and use it in GitHub Desktop.
Save dbvan/b1f8ea840e1694fd76052aec87e58f8a to your computer and use it in GitHub Desktop.
# Copyright 2021 Cloud Ace. All Rights Reserved.
# Author: Van Duong
# How To:
# /etc/NetworkManager/dispatcher.d/
# Centos: Copy file 99_google_set_hostname.sh to /etc/dhcp/dhclient.d/
# Debian: Copy file 99_google_set_hostname.sh to /etc/dhcp/dhclient-exit-hooks.d/
# Enable by add execute permission : chmod +x 99_google_set_hostname.sh
# Custom hostname by add metadata in GCE Instace: hostname: FQDN
#!/bin/bash
new_host_name=$(curl --fail --silent http://metadata.google.internal/computeMetadata/v1/instance/attributes/hostname -H "Metadata-Flavor: Google")
new_ip_address=$(curl --fail --silent http://metadata.google.internal/computeMetadata/v1/instance/network-interfaces/0/ip -H "Metadata-Flavor: Google")
if [ -n "$new_host_name" ] && [ -n "$new_ip_address" ]; then
# Don't allow DHCP responses with the MDS as the hostname.
# See: https://github.com/irsl/gcp-dhcp-takeover-code-exec
if [[ "$new_host_name" =~ "metadata.google.internal" ]]; then
echo 'not setting invalid hostname'
exit 0
fi
# Delete entries with new_host_name or new_ip_address in /etc/hosts.
sed -i"" '/Added by Google/d' /etc/hosts
# Add an entry for our new_host_name/new_ip_address in /etc/hosts.
echo "${new_ip_address} ${new_host_name} ${new_host_name%%.*} # Added by Google" >> /etc/hosts
echo "169.254.169.254 metadata.google.internal # Added by Google" >> /etc/hosts
fi
if [ -n "$new_host_name" ]; then
hostname "${new_host_name%%.*}"
nmcli=$(which nmcli 2> /dev/null)
if [ -x "$nmcli" ]; then
nmcli general hostname "${new_host_name%%.*}"
fi
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment