Skip to main content
 首页 » 编程设计

python之如何使用 Python 字典按标签名称对 AWS 实例进行分组

2025年01月19日9落叶

例如: 我有 50 个 AWS 实例。 这些实例的 key in tags 名称是 AP1 , AP2 , AP3 , AP4 , AP5

现在我想使用 Python 字典按标签名称对 AWS 实例进行分组。 像这样:{AP1:[1,2,3....10] , AP2:[11,12.....20] , AP3:[21,22,....30], AP4:[ 31.......40] , AP5:[41,42,.......50]}

根据这篇文章: Obtaining tags from AWS instances with boto

我像这样使用这个 python 脚本:

#!/usr/bin/env python 
# -*- encoding: utf8 -*- 
 
import boto.ec2 
conn = boto.ec2.connect_to_region('us-west-1') 
reservations = conn.get_all_instances() 
InstanceMap={} 
for reservation in reservations: 
    for instance in reservation.instances: 
        if 'Name' in instance.tags: 
            InstanceMap[instance.tags['Name']].append(instance.id) 

当我运行这个脚本时,它显示: [root@Redhat 脚本]# python group.py

追溯(最近的调用最后):

文件“group.py”,第 11 行,在

InstanceMap[instance.tags['Name']].append(instance.id) 

KeyError: u'AP1'

我的脚本有什么问题? 请提供正确的 python 脚本。

请您参考如下方法:

当您尝试附加到 InstanceMap[instance.tags['Name']] 时,您正在尝试附加到一个列表,该列表包含键 (instance.tags['Name'] ) 在 InstanceMap 中还不存在,因为它是空的。
首先,您需要检查该键是否已存在于 InstanceMap 中,如果存在,请使用追加。否则,创建它。

#!/usr/bin/env python 
# -*- encoding: utf8 -*- 
 
import boto.ec2 
conn = boto.ec2.connect_to_region('us-west-1') 
reservations = conn.get_all_instances() 
InstanceMap={} 
for reservation in reservations: 
    for instance in reservation.instances: 
        if 'Name' in instance.tags: 
            tag_name = instance.tags['Name'] 
            if tag_name in InstanceMap 
                InstanceMap[tag_name].append(instance.id) 
            else: 
                InstanceMap[tag_name] = [instance.id,]