Search code examples
powershellamazon-web-servicesaws-powershellaws-resource-group

List of AWS instances by TAG value using powershell


We are taging our AWS instances, I will like to retrieve a list of ALL our instances (ELB, S3, EC2, Security Groups) by TAG reference. for instance we consistently TAG our resources with something like this: { "Key": "Project", "Value": "bananas" },

How can we obtain trough power-shell a list of ALL our resources that contain the TAG Project value "bananas"?

I was able to get all my EC2s using the below script:

$instance = Get-EC2Instance -Filter @( @{name='tag:Project'; values="bananas"}; @{name='instance-state-code'; values = 16} ) | Select-Object -ExpandProperty instances #Get instance ID ignoring any terminated instances $instance | Export-CSV "C:\ec2.csv"

But I'm not sure how to obtain all my tagged resources using one script.


Solution

  • Check out the AWS Resource Groups Tagging API cmdlets -- these are relatively new, so you may have to update your AWS Tools for PowerShell to the latest version to be able to use them.

    Example

    The example below calls Get-RGTResource for the tag Key=Project, Value=Bananas, and filters the response to all ResourceARNs that were retrieved. The ResourceARN is a unique identifier for each AWS resource, and you can use these as a starting point to call out to other AWS services to get more details about each associated resource.

    (Get-RGTResource -TagFilter @{Key="Project"; Values = @("bananas")}).ResourceARN
    

    Example Output

    arn:aws:ec2:us-east-1:<accountid>:instance/i-abcd1234
    arn:aws:ec2:us-west-2:<accountid>:vpc/vpc-abcd1234
    arn:aws:ec2:us-east-2:<accountid>:security-group/sg-abcd1234
    arn:aws:elasticloadbalancing:us-east-1:<accountid>:loadbalancer/abcd1234
    arn:aws:elasticmapreduce:us-east-1:<accountid>:cluster/abcd1234
    

    Further Reading