首页 > 解决方案 > 使用 pythonboto3 在 ec2 实例列表中重复

问题描述

我制作了一个需要重新启动 aws ec2 实例的工具,重新启动工作正常,但是当我列出我在实例 ID 中有重复的服务器时,我如何列出没有重复的实例? https://gist.github.com/jacobamar8/7aa4367ed44c2d7235bc6e0c86ac0056 谢谢

标签: pythonpython-3.xboto3

解决方案


这里:

for instance in instances:
    instancename = ''
    for tag in instance.tags:
        if tag["Key"] == 'Name':
            instancename = tag["Value"]
            break;
    t.add_rows([['InstanceID', 'InstanceName', 'IP'], [instance.id, 
     instancename, instance.private_ip_address]])

为了按实例名称排序,我必须将实例添加到列表中并对其进行排序。之后将其添加到 TextTable。

import boto3
from texttable import Texttable
t = Texttable()
client = boto3.client('ec2')
ec2 = boto3.resource('ec2')
describe_instance = []
instance = ec2.Instance('id')
instances = ec2.instances.filter(
    Filters=[{'Name': 'instance-state-name', 'Values': ['running', 'stopped']}])


instanceList = []
for instance in instances:
    instancename = ''
    for tag in instance.tags:
        if tag["Key"] == 'Name':
            instancename = tag["Value"]
            row = [['InstanceID', 'InstanceName', 'IP'], [
                        instance.id, instancename, instance.private_ip_address]]
            instanceList.append(row)

instanceList.sort(key=lambda x: x[1][1])

for instanceListItem in instanceList:
  t.add_rows(instanceListItem)

print(t.draw())

推荐阅读