如何从python函数

时间:2016-06-01 07:39:48

标签: python boto3

我有一个小脚本如下:

import boto3
ACCESS_KEY= "XXXXXXXXXXXXX"
SECRET_KEY= "XXXXXXXXXXXX"
regions = ['us-east-1','us-west-1','us-west-2','eu-west-1','sa-east-1','ap-southeast-1','ap-southeast-2','ap-northeast-1']
for region in regions:
  client = boto3.client('ec2',aws_access_key_id=ACCESS_KEY,aws_secret_access_key=SECRET_KEY,region_name=region,)
  addresses_dict = client.describe_addresses()
  for eip_dict in addresses_dict['Addresses']:
     print eip_dict['PublicIp']

此代码工作正常并打印所有区域中所有EIP的列表,现在我尝试使用以下函数在我的另一个脚本中使用上述代码:

def gather_public_ip():
   ACCESS_KEY = config.get('aws','access_key')
   SECRET_KEY = config.get('aws','secret_key')
   regions = ['us-east-1','us-west-1','us-west-2','eu-west-1','sa-east-1','ap-southeast-1','ap-southeast-2','ap-northeast-1']
   all_EIP = []
   for region in regions:
      client = boto3.client('ec2',aws_access_key_id=ACCESS_KEY,aws_secret_access_key=SECRET_KEY,region_name=region,)
      addresses_dict = client.describe_addresses()
      for eip_dict in addresses_dict['Addresses']:
          print eip_dict['PublicIp']
          all_EIP.append(eip_dict['PublicIp'])
          return all_EIP

但是这仅在第一次迭代后中断(它只打印一个IP)并且没有将整个列表返回给调用者,我从__main__调用上述函数为如下:

       net_range =  gather_public_ip()
       r = s.run(net_range)
       s.save()   # save

基本上我想将返回的ip列表传递给run()。有人能帮我吗 ?

1 个答案:

答案 0 :(得分:3)

在嵌套for循环的第一次迭代中返回all_EIP。缩进返回,以便在外部for之后执行,并且您应该拥有应该附加的所有内容。

def gather_public_ip():
   ACCESS_KEY = config.get('aws','access_key')
   SECRET_KEY = config.get('aws','secret_key')
   regions = ['us-east-1','us-west-1','us-west-2','eu-west-1','sa-east-1','ap-southeast-1','ap-southeast-2','ap-northeast-1']
   all_EIP = []
   for region in regions:
      client = boto3.client('ec2',aws_access_key_id=ACCESS_KEY,aws_secret_access_key=SECRET_KEY,region_name=region,)
      addresses_dict = client.describe_addresses()
      for eip_dict in addresses_dict['Addresses']:
          print eip_dict['PublicIp']
          all_EIP.append(eip_dict['PublicIp'])
   return all_EIP