Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 516
Yaron Idan Avatar asked Jun 30 '16 12:06

Yaron Idan


People also ask

What is the difference between Boto3 client and resource?

00:00 Boto3's primary function is to make AWS API calls for you. It extracts these APIs in two main ways: clients and resources. Clients give you low-level service access, while resources provide an object-oriented way of working with these services.

How do you create a security group on Boto3?

You can create a new security group using the create_security_group() method, and assign it to our VPC. Then you can define inbound rules to only allow SSH port number 22 as shown below.


1 Answers

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 !!

like image 167
Roshan Avatar answered Oct 03 '22 15:10

Roshan