Wednesday, December 26, 2018

AWS Powershell Tools: Get Specific Tags

A quick AWS Powershell tools snippet post here. When you call Get-EC2Instance from the AWS Powershell tools it returns an instance object that has a Tags attribute, which is a Powershell list of EC2 Tag Objects.

I'm usually a fan of how the AWS Powershell Tools object models are setup, but this is one case where I feel there could be some improvement. Instead of using a list and forcing users to iterate the list to find the right tag, the EC2 objects "Tags" property should be a hashtable with the tag Key as the hash key so you can index directly to the object. But, this is was we have to work with for now.

So we came up with a simple function to generate a map of desired EC2 tags from an instance.


function Get-Ec2InstanceTag($instance, [array]$desiredTagKeys) {
    $instanceTags = $instance.Tags;
    $tagMap = @{};
    foreach ($desiredTagKey in $desiredTagKeys) {
        foreach ($instanceTag in $instanceTags) {
            if($desiredTagKey -eq $instanceTag.Key) {
                $tagMap[$desiredTagKey] = $instanceTag.Value;
            }
        }
    }
    return $tagMap;
}


Usage for this function looks like this:

No comments:

Post a Comment