Javier Lopez Tomas
Javier Lopez Tomas

Reputation: 2342

Describe_instances in boto3 with filters is not working

I am developing a script in Python for deleting old AMIs and its snapshots. For testing purposes, I have been trying to create and right after deleting an AMI. My code for creating the instance is the following (including the addition of tags at the end):

import boto3
from datetime import datetime, timedelta
import time

today = datetime.utcnow().strftime('%Y%m%d')

remove_on = (datetime.utcnow() + timedelta(days=3)).strftime('%Y%m%d')

session = boto3.session.Session(region_name='eu-west-1')
client = session.client('ec2')
ec2 = session.resource('ec2')

instance_info = client.describe_instances(Filters=[{'Name': 'tag:Name', 
'Values': ['Airflow']}]) #This filter DOES work
instance_id = instance_info['Reservations'][0]['Instances'][0]['InstanceId']
instance = ec2.Instance(instance_id)

image = instance.create_image(InstanceId=instance_id, Name=f"Airflow_{today}")
time.sleep(2)
image.create_tags(Tags=[{'Key': 'RemoveOn', 'Value': remove_on},
                        {'Key': 'BackupOf', 'Value': 'Airflow'}])

However, when I try to get the info of the recent created AMI, I get no data:

instances_to_delete = client.describe_instances(Filters=[{'Name': 'tag:RemoveOn', 
                                                      'Values':[remove_on]}])

I have tried to explicitly put a string in Values but it does not work either. Also, even though it didn't make much sense (since I already had one filter working previously), I specified the region in client also (because of these answers Boto3 ec2 describe_instances always returns empty) and it doesn't work. enter image description here The tag is there as we can see in the following screenshot

Upvotes: 0

Views: 430

Answers (1)

John Rotenstein
John Rotenstein

Reputation: 269101

Your code seems to be creating an image (AMI) and then putting a tag on the AMI.

Then, you are saying that it is unable to find the instance with that tag. That makes sense, because only the image was tagged, not the instance.

Upvotes: 2

Related Questions