简体   繁体   English

如何通过检查实例名称中的字符串来过滤实例

[英]How to Filter Instances by Checking for a String in the Instance Name

I am writing a python script to retrieve a list of instances that were incorrectly tagged. 我正在编写一个python脚本来检索未正确标记的实例列表。 I need to filter by checked if a specific string exists in the name. 我需要通过筛选来检查名称中是否存在特定的字符串。

What is the best way to do this? 做这个的最好方式是什么?

I was going to use describe_instances and use the tag filter (where the key is 'Name') but that filter requires that I provide the full value of the tag (ie the instance name) but I need to be able to search using a subset of the name. 我打算使用describe_instances并使用标签过滤器(其中键为“名称”),但是该过滤器要求我提供标签的完整值(即实例名称),但我需要能够使用子集进行搜索名称。

Can this be done using the client? 可以使用客户端完成此操作吗?

The easiest method is to call describe_instances() without a filter, then just loop through the results and perform your own filtering & fixup logic in Python. 最简单的方法是在不使用过滤器的情况下调用describe_instances() ,然后循环遍历结果并在Python中执行您自己的过滤和修复逻辑。

General logic would be: 一般逻辑为:

Create EC2 client
Call describe_instances
Loop through results['Reservations']['Instances']:
  Loop through instance['Tags']:
    if Key == 'Name' and "bad-string" in Value:
      Fix tag

If you have more than 1000 instances, you'll have to re-call describe-instances() with NextToken . 如果您有超过1000个实例,则必须使用NextToken调用describe-instances()

对于正在阅读本文的人,您可以执行John Rotenstein在其答案中建议的操作,或者,也可以在标签名称中使用通配符'*',因此过滤器将类似于:

filters = [{'Name':'tag:Name', 'Values':['string*']}]

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

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