【问题标题】:How can I get the value of the EC2 instance tag "Name" with boto?如何使用 boto 获取 EC2 实例标签“名称”的值?
【发布时间】:2020-10-22 01:17:11
【问题描述】:

我正在使用实例 ID。我可以获取标签,但我不知道如何过滤实例 ID 和标签“名称”或索引并返回名为“名称”的标签的值

我最终抓取了所有标签并遍历它们,直到找到我想要的标签,这不可能是正确的。

 tags = conn.get_all_tags({'resource-id': instance_id})
  for tag in tags:
    if 'Name' in tag.name:
      name = tag.value

【问题讨论】:

  • 上面的代码能用吗?
  • 是的,这似乎是一种非常迂回的方式。

标签: python amazon-ec2 boto


【解决方案1】:

你确实有更好的方法:

conn.get_all_tags(filters={'tag-key': 'Name', 'resource-id': instance_id})

【讨论】:

【解决方案2】:

我认为你这样做的方式很好。您总是可以将它作为抽象包装在函数调用中:

def get_instance_tag(all_tags, tag_name):
  for tag in all_tags:
    if tag_name == tag.name:
      return tag.value

  return None

name = get_instance_tag(conn.get_all_tags({'resource-id': instance_id}), 'Name')

请注意,if tag_name == tag.name: 比 if tag_name in tag.name: 更准确。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-04-17
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-25
    • 1970-01-01
    相关资源
    最近更新 更多