如何在 boto 程序中指定 aws 区域?

nag*_*eer 2 amazon-web-services python-3.x boto3

我想ec2使用 boto 模块列出aws 帐户中的实例。我遇到的问题是

“您必须指定一个区域”。这是程序。

import boto3
ec2 = boto3.resource('ec2')
for instance in ec2.instances.all()
print instance.id, instance.state
Run Code Online (Sandbox Code Playgroud)

我没有指定任何默认区域。如何以编程方式指定它?

Joh*_*ley 7

由于您使用的是资源接口,您的代码将如下所示:

import boto3
ec2 = boto3.resource('ec2', region_name = 'us-west-2')
for instance in ec2.instances.all()
    print instance.id, instance.state
Run Code Online (Sandbox Code Playgroud)


vis*_*l.k 6

这就是您的代码使用客户端而不是资源的样子

 import boto3
 ec2 = boto3.client('ec2',region_name='us-west-1')
 a = ec2.describe_instances()
 for i in a['Reservations']:
    for j in i['Instances']:
       print "state of the instance"+j['InstanceId']+" is:"+j['State']['Name']
Run Code Online (Sandbox Code Playgroud)

这只是其中一种方法,还有很多方法,大家自己尝试一下