Rename Windows and Linux EC2 instances based on tag

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)

INSTANCE_ID=$(curl -s
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)
if [ -z "$NAME_FROM_TAG" ]
      echo "no name set in tags..exiting"
          exit 0
      if [ $NAME_FROM_TAG != $HOST_NAME ]
                echo "name changing.."
                hostnamectl set-hostname $NAME_FROM_TAG


$instanceId = (Invoke-WebRequest -usebasicparsing -Uri
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.."