AWS Developer Blog

Tagging Amazon EC2 Instances at Launch

by Steve Roberts | on | in .NET | Permalink | Comments |  Share

In this guest post (by James Saull from the AWS Solutions Architects team), we will show how to launch EC2 instances, retrieve the new instances’ IDs, and apply tags to them.

Tagging EC2 instances allows you to assign metadata to instances to facilitate management – especially at scale. Canonical examples include tagging instances to identify which individual or department they belong to or which application they are part of. They are also a useful way to help with cost allocation of resources when it comes time to analyze or apportion the bill. Some organizations consider tagging so important to the management of their infrastructure that they terminate anything that is not appropriately tagged!

It makes good sense to apply the minimum set of tags at the time of launch. More can be applied later if required. In this short post, we will show how to launch and tag EC2 instances.

For simplicity, we will launch a pair of instances using the latest Windows 2012 Base image:

Set-DefaultAWSRegion eu-west-1
$NewInstanceResponse =  
"WINDOWS_2012_BASE" | Get-EC2ImageByName | New-EC2Instance -InstanceType t1.micro -MinCount 2 -MaxCount 2

Now to retrieve the Instance Ids:

$Instances = ($NewInstanceResponse.Instances).InstanceId 

Next we need to compose the collection of tags we wish to apply to these instances. When writing Windows PowerShell scripts, I prefer to avoid using New-Object where reasonable, but I will eschew my personal preferences and demonstrate with and without:

$Tags = @()
$CreatedByTag = New-Object Amazon.EC2.Model.Tag
$CreatedByTag.Key = "CreatedBy"
$CreatedByTag.Value = "James"
$Tags += $CreatedByTag
$DepartmentTag = New-Object Amazon.EC2.Model.Tag
$DepartmentTag.Key = "Department"
$DepartmentTag.Value = "Solutions Architecture"
$Tags += $DepartmentTag 

We can rewrite the above as an array of key-value pairs:

$Tags = @( @{key="CreatedBy";value="James"}, `
           @{key="Department";value="Solutions Architecture"} )

The final step is to apply the tags to the instances we launched:

New-EC2Tag -ResourceId $Instances -Tags $Tags

This can be rewritten using pipes instead:

$Instances | New-EC2Tag -Tags $Tags 

We can now look at our newly tagged instances:

((Get-EC2Instance -Instance $Instances).RunningInstance).Tags

It is tempting to condense this script into a single line, but it might be more robust to code more defensively and check at each stage that failures have not been encountered (e.g., zero instances launched due to reaching an account limit):

(("WINDOWS_2012_BASE" | Get-EC2ImageByName | New-EC2Instance -InstanceType t1.micro -MinCount 2 -MaxCount 2).Instances).InstanceId | New-EC2Tag -Tags $Tags

If you have been following along in your test account and you’ve launched some instances, be sure to terminate them when you no longer need them:

$Instances | Stop-EC2Instance -Terminate -Force