We had the same issue. We build a lot of EC2 instances from CloudFormation automatically every day and needed a way to easily identify them individually in the console based on their hosthame.
Currently all the automatically built servers have the same name which is a fixed string in the cloud formation template.
We already had a "user data" based boot-strapping mechanism whereby the automatically created instances would run some PowerShell code when they first booted.
Therefore to get the hostname to show in the AWS console I figured the easiest way was to change the "name" tag, appending the hostname to the existing tag.
I added the following code to the bootstrap:
function Get-NameTagValue()
{
param(
[parameter(Mandatory)] [string] $InstanceId
)
$filter1 = New-Object -TypeName Amazon.EC2.Model.Filter -Property @{
Name = 'resource-id'
Values = $InstanceId
}
$filter2 = New-Object -TypeName Amazon.EC2.Model.Filter -Property @{
Name = 'key'
Values = 'Name'
}
$filters = $filter1, $filter2
$tag = Get-EC2Tag `
-Region $Region `
-ProfileName $ProfileName `
-Filter $filters
#Output the tag value
$tag.Value
}
function Set-InstanceNameTag()
{
$instanceId = (Invoke-RestMethod -Method Get -Uri http://169.254.169.254/latest/meta-data/instance-id)
#Get the current value of the name tag
$currentNameTagValue = Get-NameTagValue -InstanceId $instanceId
$newNameTagValue = "$currentNameTagValue - $env:COMPUTERNAME"
Remove-EC2Tag `
-Resource $instanceId `
-Tag @{ Key="Name" } `
-Region $Region `
-ProfileName $ProfileName `
-Force
New-EC2Tag `
-Resource $instanceId `
-Tag @{ Key="Name"; Value=$newNameTagValue } `
-Region $Region `
-ProfileName $ProfileName `
}
The code first gets the isnance id from the meta data, then using this id it finds the existing Name tag, removes it and adds a new Name tag containing the existing value followed by the hostname.
These two functions are contained within our Bootstrap script which has parameters for $Region
and $ProfileName
which are used in the functions.
We then just call the function Set-InstanceNameTag
from the main script and voilà, you have the existing Name tag followed by a hyphen and the hostname.
In order to make this work, the EC2 instance need to have a role that has permissions to: CreateTags, DeleteTags and DescribeTags.
You can achieve this using the following policy:
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"ec2:CreateTags",
"ec2:DeleteTags",
"ec2:DescribeTags"
],
"Resource": [
"*"
]
}
]
}
Hope that helps someone.
Carl