Muhammad Awais
Muhammad Awais

Reputation: 93

Filter instance based on multiple tags in Lambda Python code

I want to check if a certain instance has list of tags on it. Tags I am interested in are Environment, Env, and environment. And their values are Production, Prod, and production. I am using a lambda function for checking it and I have this so far:

response = ec2.describe_tags(
Filters=[
    {
        'Name': 'tag:Environment|Env|environment',
        'Values': [
            'Production|production|Prod',
        ]
    },
    {
        'Name': 'resource-id',
        'Values': [
            instance_id,
        ],
    }
])
print(response)

But this doesn't catch proper tags on instance. I believe the problem is me trying to catch multiple tags in "Key1|Key2|Key3" format. Can anyone please advise correct way of filtering through multiple tags? Thanks!

Upvotes: 1

Views: 1229

Answers (2)

Adiii
Adiii

Reputation: 60104

It seems that you are trying to work base on EC2 event using lambda, then you better to get instance base on Instance ID that is available in EC2 event, get the tags and perform the further operation.

ec2 = boto3.client('ec2')
specificinstance = ec2.describe_instances(Filters=[
{
    'Name': 'instance-id',
    'Vdataalues': [
        event["detail"]["EC2InstanceId"]
        ],
}])
TAGS=specificinstance["Reservations"][0]["Instances"][0]["Tags"]
pprint(TAGS) 

Or I did not find a way to filter instance base on different tag-key but here is the example that might help, which filter base on a different value.

import boto3  
client = boto3.client('ec2') 
filters = [{  
    'Name': "tag:environment",
    'Values': ['prod','production','Production']
    }]
response = client.describe_instances(Filters=filters)
print response

This will filter if it container environment like prod,production,Production

To filter with instance IP, or reservation ID

import boto3  
client = boto3.client('ec2') 
filters = [{  
    'Name': "tag:environment",
    'Values': ['prod,production,Production']
    },
    {
    'Name': 'instance-id',
    'Values': [
        'i-123456789',
        ],
}]
response = client.describe_instances(Filters=filters)
print response

Upvotes: 0

Marcin
Marcin

Reputation: 238877

I think you have to do in three separate calls. At least this is what I can conclude from my exterminates on several instances.

An example that I used is below:

import boto3

from pprint import pprint

ec2 = boto3.client('ec2')

tag_values = ['production', 'Prod', 'Production']
tag_names = ['Env', 'Environment', 'environment']

results = []

for tag_name in tag_names:

    r=ec2.describe_tags(
            Filters=[{
                    'Name':'tag:' + tag_name,
                    'Values': tag_values
          }])

    pprint(r)

    results.append(r)


pprint(results)

Upvotes: 1

Related Questions