Skip to content

Instantly share code, notes, and snippets.

@lorello
Last active February 9, 2020 14:11
Show Gist options
  • Select an option

  • Save lorello/49e0a1f4fbdc206cd8e880a77ddfb0e1 to your computer and use it in GitHub Desktop.

Select an option

Save lorello/49e0a1f4fbdc206cd8e880a77ddfb0e1 to your computer and use it in GitHub Desktop.
Customize EC2 hostname
#!/usr/bin/env bash
# set hostname to current name with the last 4 chars of instance id
#
id=$(ec2metadata --instance-id)
myname=${HOSTNAME}-${id:(-4)}
hostnamectl set-hostname $myname
sed -i "s/${HOSTNAME}/${myname}/g" /etc/hosts
echo "New hostname is $myname"
#!/usr/bin/env bash
#
# Set EC2 tag Name to the current HOSTNAME of the instance
#
# Required policy:
#
# {
# "Version": "2012-10-17",
# "Statement": [
# {
# "Sid": "VisualEditor0",
# "Effect": "Allow",
# "Action": [
# "ec2:DeleteTags",
# "ec2:DescribeTags",
# "ec2:CreateTags"
# ],
# "Resource": "*"
# }
# ]
# }
#
# Add this to the IAM Role of the EC2 host and this script will run smoothly!
#
# set -ex
if [[ -z $HOSTNAME ]]; then
echo "ERROR, cannot procede without a valid HOSTNAME"
exit 1
fi
region=$(http http://169.254.169.254/latest/dynamic/instance-identity/document | jq -c -r .region)
if [[ -z $region ]]; then
echo "ERROR, cannot get region info from metatags, am I an EC2 instance? Are httpie and jq installed?"
exit 2
fi
id=$(http http://169.254.169.254/latest/meta-data/instance-id)
if [[ ! -f ~/.aws/config ]]; then
[[ ! -d ~/.aws ]] && mkdir ~/.aws
echo -e "[default]\nregion = $region\n" > ~/.aws/config
echo "* Configured aws-cli with default region '$region'"
fi
echo "* Getting current tags..."
echo
if aws ec2 describe-tags --filters "Name=resource-id,Values=$id"; then
echo
else
echo "ERROR, cannot list tags on instance '$id', is there a policy that allow action ec2:DescribeTags in the instance ROLE?"
exit 3
fi
if aws ec2 delete-tags --resource "$id" --tag Key=Name; then
echo "* Removed tag Name"
else
echo "ERROR, cannot remove tag Name from instance '$id', is there a policy that allow action ec2:DeleteTags in the instance ROLE?"
exit 4
fi
if aws ec2 create-tags --resources "$id" --tag Key=Name,Value="$HOSTNAME"; then
echo "* Added tag Name=$HOSTNAME"
else
echo "ERROR, cannot add tag Name to instance '$id', is there a policy that allow action ec2:CreateTags in the instance ROLE?"
exit 5
fi
echo
echo "==> Finished successfully!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment