如何使用boto和python循环遍历区域?

时间:2016-03-09 16:55:59

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

Python新手.. 我试图编写一个脚本,使用我给它的键连接到我的AWS账户,然后它将列出那里的实例,并通过循环遍历每个区域来实现。所以我希望它连接并在区域和列表中开始,然后转到下一个区域和列表,依此类推。 如果我注释掉以下行,则下面的代码有效,但它仅适用于us-east-1,这是我框中我的AWS凭证文件中的默认区域。 “regions = 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

1 个答案:

答案 0 :(得分:4)

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