We use the AWS EC2Config service on our instances. This allows us to run a variety of tasks on startup or reboot, one of which is to display system information on the desktop background, giving an easily visible reference about the instance. We use papertrail as our logging tool, which logs against the HostName of the instance (which also displays on the desktop background). However in the AWS Console it doesn’t record the HostName, meaning extra steps are required to convert the HostName to the Instance ID which can then be found in the AWS Console.
Here is a .ebextension that will set the HostName as a tag against the instance and allow you to search in the AWS console for the HostName.
I’ve talked about using .ebextensions in some of my previous posts and included links to AWS resources, so please refer to this if you are new to using them.
The content of the set-hostname-tag.config file is as follows:
files: "c:\\init_scripts\\set_hostname_tag.ps1": content: | import-module "C:\Program Files (x86)\AWS Tools\PowerShell\AWSPowerShell\AWSPowerShell.psd1" Set-DefaultAWSRegion eu-west-1 $client = New-Object System.Net.WebClient $instanceId = $client.DownloadString("http://169.254.169.254/latest/meta-data/instance-id") $Tag = New-Object amazon.EC2.Model.Tag $Tag.Key = "HostName" $Tag.Value = $env:COMPUTERNAME New-EC2Tag -Resource $instanceId -Tag $Tag | out-null container_commands: 01_set_hostname_tag: command: powershell -ExecutionPolicy RemoteSigned -File .\\set_hostname_tag.ps1 cwd: c:\\init_scripts waitAfterCompletion: 0
There are two parts to this; the files section which is used to create a file on an ec2 instance (in our case the PowerShell set_hostname_tag.ps1), and the container_commands section is used to execute commands (in our case to run the PowerShell). The PowerShell script itself queries the instance Metadata and creates a new tag called HostName.
As before, confirm that any .config files confirm to YAML or JSON formatting standards and have been added to a .ebextensions directory in the top-level directory of your source bundle, add the .ebextensions as part of the project to be included in your archive, and ensure that your IAM EC2 Instance role running this has the correct permissions to create tags.
The AWS documentation regarding Metadata can be found here and details all the available categories, as well as some examples. Any of these Metadata categories can then be applied as a tag using the script above.