简体   繁体   English

带有过滤器的 boto3 中的 Describe_instances 不起作用

[英]Describe_instances in boto3 with filters is not working

I am developing a script in Python for deleting old AMIs and its snapshots.我正在 Python 中开发一个脚本,用于删除旧的 AMI 及其快照。 For testing purposes, I have been trying to create and right after deleting an AMI.出于测试目的,我一直在尝试创建并在删除 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:但是,当我尝试获取最近创建的 AMI 的信息时,我没有得到任何数据:

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.我试图在 Values 中显式放置一个字符串,但它也不起作用。 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.此外,即使它没有多大意义(因为我之前已经有一个过滤器在工作),我也在客户端中指定了区域(因为这些答案Boto3 ec2 describe_instances 总是返回 empty )并且它不起作用。 在此处输入图像描述 The tag is there as we can see in the following screenshot正如我们在以下屏幕截图中看到的那样,标签就在那里

Your code seems to be creating an image (AMI) and then putting a tag on the AMI.您的代码似乎正在创建一个图像 (AMI),然后在 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.这是有道理的,因为只有图像被标记,而不是实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM