boto3 instances filter

0

how do I filter based on instance IDs?

instances = conn.instances.filter(
    InstanceIds = [{  
    'Name': 'InstanceId',
    'Values': ['i-017357c1c4a1a96f8', 'i-07e399b452c7100c3']
    }]
)

is there something wrong with this?

asked 2 years ago2572 views
2 Answers
0

Here is an example of using filter to start and terminate instances. You will want to pass an array of instance ids.

Stopping and terminating multiple instances given a list of instance IDs uses Boto3 collection filtering:

ids = ['instance-id-1', 'instance-id-2', ...]

Boto 2.x

ec2_connection.stop_instances(instance_ids=ids)
ec2_connection.terminate_instances(instance_ids=ids)

Boto3

ec2.instances.filter(InstanceIds=ids).stop()
ec2.instances.filter(InstanceIds=ids).terminate()

More information on EC2 filter options. https://boto3.amazonaws.com/v1/documentation/api/latest/reference/services/ec2.html?highlight=filter#EC2.Client.describe_instances

profile pictureAWS
answered 2 years ago
0

Hello, I might need a little more context to be sure of just what your asking here, but in the meantime I'll see if I can help clear things up.

The documentation gives a few examples.

Every collection exposes a filter method that allows you to pass additional parameters to the underlying service API operation.

One attribute you can filter on is InstanceIds.

Where ec2.instances alone will return a list of all instances (in the configured account/region), applying .filter(InstanceIds=list_of_ec2_instance_ids) will limit the returned list to those in the list_of_ec2_instance_ids list. For instance, for a list of ids, you can filter then call an action on that filtered set.

ids = ['instance-id-1', 'instance-id-2', ...]
ec2.instances.filter(InstanceIds=ids).stop()

So from the example above, I think your example should be in this form:

instances = conn.instances.filter(
    InstanceIds = ['i-017357c1c4a1a96f8', 'i-07e399b452c7100c3']
)

I hope this is the information you were looking for and resolved your issue. If not please reply with more context and we'll dig in deeper.

AWS
SamKeen
answered 2 years ago

You are not logged in. Log in to post an answer.

A good answer clearly answers the question and provides constructive feedback and encourages professional growth in the question asker.

Guidelines for Answering Questions