Skip to content

Instantly share code, notes, and snippets.

Created February 7, 2019 18:12
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save lukeyeager/af9f605976829df6bf10d0b4acafc6ef to your computer and use it in GitHub Desktop.
AWS EC2: set a node's hostname to it's tagged name
set -ex
# Sanity check
hostname="$(hostname --fqdn)"
if [[ "$hostname" != ip-*.internal ]]; then
echo hostname already updated
exit 0
# Install requirements
apt update
apt install -y --no-install-recommends jq python3-pip python3-wheel
pip3 install awscli
# Configure awscli
export AWS_DEFAULT_REGION="$(hostname --fqdn | cut -d. -f2)"
# Get tagged hostname
current_hostname="$(hostname --fqdn)"
instanceid="$(aws ec2 describe-instances --filter Name=private-dns-name,Values="$current_hostname" | jq -r .Reservations[0].Instances[0].InstanceId)"
new_hostname="$(aws ec2 describe-tags --filters Name=resource-id,Values="$instanceid" | jq -r '.Tags[] | select(.Key == "Name") | .Value')"
if [ -z "$new_hostname" ]; then
echo new hostname not found
exit 1
# Update hostname
hostname "$new_hostname"
echo "$new_hostname" >/etc/hostname
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment