【问题标题】:How do I loop through regions using boto with python?如何使用 boto 和 python 遍历区域?
【发布时间】:2016-03-10 01:14:02
【问题描述】:

Python 新手.. 我正在尝试编写一个脚本,该脚本将使用我提供的密钥连接到我的 AWS 账户,然后它将列出其中的实例,并通过遍历每个区域来实现。所以我希望它连接并在一个区域和列表中开始,然后转到下一个区域和列表,依此类推。 如果我注释掉以下行,则下面的代码有效,但它仅适用于 us-east-1,这是我在我的盒子上的 AWS 凭证文件中的默认区域。 “区域 = boto.ec2.regions() 对于区域中的 x:" 如果我取消注释这些行,脚本将为每个区域返回一次我的所有实例。因此,我最终得到了大量重复的相同实例列表。我错过了什么会让这做我想要的?很简单,我对 Python 很陌生。 谢谢。

import boto.ec2
import os
import sys

ACCESS_KEY = raw_input("Enter your access key > ")
SECRET_KEY = raw_input("Enter your secret key > ")
if not ACCESS_KEY:
    sys.exit("ERROR: You did not enter anything for ACCESS KEY or SECRET KEY. Exiting...")

ec2_conn = boto.connect_ec2(ACCESS_KEY, SECRET_KEY)

regions = boto.ec2.regions()
for x in regions:
    reservations = ec2_conn.get_all_reservations()
    for r in reservations:
        for i in r.instances:
            print r.instances
            print 'Tags: ',i.tags['Name']
            print 'Public IP Address: ',i.ip_address
            print 'Private IP address: ',i.private_ip_address
            if (i.virtualization_type == 'hvm'):
                platform = 'Windows'
            else:
                platform = 'Linux'
                print 'Platform: ',platform
            print 'State: ',i.state
            print

【问题讨论】:

    标签: python amazon-web-services amazon-ec2 boto


    【解决方案1】:

    boto.connect_ec2 移动到第一个 for 循环中,并将区域传递给它。像这样的:

    import boto.ec2
    import os
    import sys
    
    ACCESS_KEY = raw_input("Enter your access key > ")
    SECRET_KEY = raw_input("Enter your secret key > ")
    if not ACCESS_KEY:
        sys.exit("ERROR: You did not enter anything for ACCESS KEY or SECRET KEY. Exiting...")
    
    regions = boto.ec2.regions()
    for x in regions:
        ec2_conn = boto.connect_ec2(ACCESS_KEY, SECRET_KEY, region=x)
        reservations = ec2_conn.get_all_reservations()
        for r in reservations:
            for i in r.instances:
                print r.instances
                print 'Tags: ',i.tags['Name']
                print 'Public IP Address: ',i.ip_address
                print 'Private IP address: ',i.private_ip_address
                if (i.virtualization_type == 'hvm'):
                    platform = 'Windows'
                else:
                    platform = 'Linux'
                    print 'Platform: ',platform
                print 'State: ',i.state
                print
    

    【讨论】:

    • 谢谢。这让我到达了我需要的地方。
    • 嗯......有点。它适用于一个帐户,但我认为这是因为我在一个区域中只有 4 个实例。当我在另一个帐户上运行脚本时,它被炸毁并引发错误。它列出了一个区域(us-east-1)中的所有内容,并且看起来像当它试图转到下一个区域时它没有正确连接。我需要在那里的某个地方重新建立连接吗?错误:'ssl.SSLError:[Errno 1] _ssl.c:492:错误:14090086:SSL 例程:SSL3_GET_SERVER_CERTIFICATE:证书验证失败'
    • @TheRedSeth 这是一个单独的问题。您的 Boto 证书已过期。我认为您需要更新 boto 文件夹中的 cacerts.txt。
    猜你喜欢
    • 1970-01-01
    • 2011-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-08-06
    • 1970-01-01
    • 2011-08-14
    • 2011-03-09
    相关资源
    最近更新 更多