sgargel
sgargel

Reputation: 1046

Python comparison operators in boto filters

Is it possible to use comparison operator in a boto3 filter?

I would like to list all ec2 instances filtered by a tag value "greater than" number.

    filters = [
        {
            'Name': 'tag:tag1',
            'Values': ['True']
        },
        {
            'Name': 'tag:tag2',
            'Values': # greater than integer
        }
    ]

Upvotes: 1

Views: 894

Answers (1)

Ethan Harris
Ethan Harris

Reputation: 1362

Short Answer: No

Boto3 ec2 client does not have comparison operators for filter values, however you can use wildcards:

import boto3

client = boto3.client('ec2')

FILTER_VALUE = [{
    'Name':'tag:tag2', 
    'Values': ['1*']}]

response = client.describe_instances(Filters=FILTER_VALUE)

Or just find all ec2 instances and filter out using your own python script:

response = client.describe_instances(Filters=FILTER_VALUE)
FILTERED_EC2S = []
TAG_NAME="tag2"
TAG_GT=2 #the integer value you want to filter on

for ec2 in response.get("Reservations", {}).get("Instances", []):
     for tag in ec2.get("Tags", []):
          if tag.get("Key")==TAG_NAME and tag.get("Value")>TAG_GT:
               FILTERED_EC2S.append(ec2)

Upvotes: 2

Related Questions