Skip to content

Instantly share code, notes, and snippets.

@nitinsatish
Forked from sahilsk/instance_filtering.md
Created November 2, 2022 11:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nitinsatish/cac064f9a95e68046283a1cad3a44f14 to your computer and use it in GitHub Desktop.
Save nitinsatish/cac064f9a95e68046283a1cad3a44f14 to your computer and use it in GitHub Desktop.
boto3, python, aws, instance filtering

Source

Russell Ballestrini

– Filtering AWS resources with Boto3

This post will be updated frequently when as I learn more about how to filter AWS resources using Boto3 library.

Filtering VPCs by tags

In this example we want to filter a particular VPC by the "Name" tag with the value of 'webapp01'.

>>> import boto3
>>> boto3.setup_default_session(profile_name='project1')
>>> ec2 = boto3.resource('ec2', region_name='us-west-2')
>>> filters = [{'Name':'tag:Name', 'Values':['webapp01']}]
>>> webapp01 = list(ec2.vpcs.filter(Filters=filters))[0]
>>> webapp01.vpc_id
'vpc-11111111'

You can also filter on the value of the 'tag-key' or the 'tag-value' like so:

>>> taco_key_filter = [{'Name':'tag-key', 'Values':['taco']}]
>>> nacho_value_filter = [{'Name':'tag-value', 'Values':['nacho']}]

You can also filter on multiple 'Values'. In this example want 2 VPCs named 'webapp01' and 'webapp02':

>>> filters = [{'Name':'tag:Name', 'Values':['webapp01','webapp02']}]
>>> list(ec2.vpcs.filter(Filters=filters))
[ec2.Vpc(id='vpc-11111111'), ec2.Vpc(id='vpc-22222222')]

You can also use the '*' wildcard to glob up results in your filter. In this example we want all 3 VPCs named 'webapp01', 'webapp02' and 'webapp03':

>>> filters = [{'Name':'tag:Name', 'Values':['webapp*']}]
>>> list(ec2.vpcs.filter(Filters=filters))
[ec2.Vpc(id='vpc-11111111'), ec2.Vpc(id='vpc-22222222'), ec2.Vpc(id='vpc-33333333')]

Thats all for now!

You should read my other Boto related posts for tricks to impress your friends. : )

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment