If you need to rename your EC2 instances based on the tags set, you can use the below code snippets. This can be particularly useful if you use a hardened AMI with a name already set in. To apply them, you can just use a cron job or a Task Scheduler job, or even cloudwatch events and SSM Run Command when the instance is launched.
Linux (Just change the region based on your need, or even parameterize it)
#/bin/bash
INSTANCE_ID=$(curl -s http://169.254.169.254/latest/meta-data/instance-id)
NAME_FROM_TAG=$(/usr/local/bin/aws ec2 describe-tags --filters "Name=resource-id,Values=$INSTANCE_ID" "Name=key,Values=Name" --region=ap-southeast-1 --output=text | cut -f5)
HOST_NAME=$(hostname)
if [ -z "$NAME_FROM_TAG" ]
then
echo "no name set in tags..exiting"
exit 0
else
if [ $NAME_FROM_TAG != $HOST_NAME ]
then
echo "name changing.."
hostnamectl set-hostname $NAME_FROM_TAG
fi
fi
Windows
$instanceId = (Invoke-WebRequest -usebasicparsing -Uri http://169.254.169.254/latest/meta-data/instance-id).Content
Write-Output "Instance ID Found:$instanceId"
$ec2_name = hostname
Write-Output "Local hostname found:$ec2_name"
$hostNameFromTag = aws ec2 describe-instances --instance-ids $instanceId --query 'Reservations[].Instances[].Tags[?Key==`Name`].Value' --output text
if (!$hostNameFromTag) {
Write-Output "tags not found or permission denied. exiting"
exit 1
}
Write-Output "Hostname required:$hostNameFromTag"
if ($ec2_name -ne $hostNameFromTag){
Write-Output "The name set in the instance is different from the name from EC2 tags.."
Write-Output "current name is $ec2_name, but the name from tag is $hostNameFromTag"
Write-Output "Initiating the name change.."
try {
Rename-Computer -NewName $hostNameFromTag -Force -ErrorAction Stop
}
catch {
Write-Output "An error occurred:"
Write-Output $_.ScriptStackTrace
Write-Output $PSItem.Exception.Message
exit 1
}
Write-Output "Restarting to effect the name change.."
shutdown /r /f /t 0
}
else {
Write-Output "The name set in the instance is same as the name from the name from EC2 tags.."
}