Yaron Idan
Yaron Idan

Reputation: 6765

Filter instances by state with boto3

Trying to use boto3 to describe all of my instances and filter every instance that is not currently running. Using this post as a reference for building my filter - http://rob.salmond.ca/filtering-instances-by-name-with-boto3/.

When I try to filter the instances by state using this filter -

filters = [{
'Name': 'tag:State',
'Values': ['running']
}]

The query comes back empty (which makes sense, since the state value is nested inside a dictionary of it's own.

My question is - how do I access a nested tag with the filters parameter?

Upvotes: 13

Views: 34547

Answers (1)

Roshan
Roshan

Reputation: 1390

session = boto3.Session(region_name="us-east-1")

ec2 = session.resource('ec2', region)

instances = ec2.instances.filter(
        Filters=[{'Name': 'instance-state-name', 'Values': ['stopped', 'terminated']}])

for instance in instances:
    print(instance.id, instance.instance_type)

Hope it helps !!

Upvotes: 37

Related Questions