Boto:如何通过id获取安全组?

时间:2016-04-12 13:35:17

标签: amazon-web-services amazon-ec2 boto aws-ec2 ec2-api-tools

我正在尝试按组ID获取安全组。

以下是代码:

#!/usr/bin/env python2.7
import boto.ec2
import argparse

parser = argparse.ArgumentParser(description="")
parser.add_argument('sec_group_id', help='Security group id')
parser.add_argument('region_name', help='Region name')
args = parser.parse_args()
sec_group_id = args.sec_group_id
region_name = args.region_name

conn = boto.ec2.connect_to_region(region_name);

GivenSecGroup=conn.get_all_security_groups(sec_group_id)

执行此操作时:

./sec_groups.py sg-45b9a12c eu-central-1

我得到了输出:

Traceback (most recent call last):
  File "./sec_groups.py", line 22, in <module>
    GivenSecGroup=conn.get_all_security_groups(sec_group_id)
  File "/usr/lib/python2.7/dist-packages/boto/ec2/connection.py", line 2969, in get_all_security_groups
    [('item', SecurityGroup)], verb='POST')
  File "/usr/lib/python2.7/dist-packages/boto/connection.py", line 1182, in get_list
    raise self.ResponseError(response.status, response.reason, body)
boto.exception.EC2ResponseError: EC2ResponseError: 400 Bad Request
<?xml version="1.0" encoding="UTF-8"?>
<Response><Errors><Error><Code>InvalidGroup.NotFound</Code><Message>The security group 'sg-45b9a12c' does not exist in default VPC 'vpc-d289c0bb'</Message></Error></Errors><RequestID>edf2afd0-f552-4bdf-938e-1bccef798145</RequestID></Response>

所以基本上它说“安全组'sg-45b9a12c'在默认VPC中不存在'vpc-d289c0bb'”

但是这个安全组确实存在于默认的VPC中!这是证明: AWS console screenshot

我该如何使用?

我很感激你的回答。

2 个答案:

答案 0 :(得分:2)

简答:

只需更改

GivenSecGroup=conn.get_all_security_groups(sec_group_id)

GivenSecGroup=conn.get_all_security_groups(group_ids=[sec_group_id])

长答案:

get_all_security_groups第一个参数是安全组名称列表,第二个参数是id列表:

def get_all_security_groups(self, groupnames=None, group_ids=None,
                            filters=None, dry_run=False):
    """
    Get all security groups associated with your account in a region.

    :type groupnames: list
    :param groupnames: A list of the names of security groups to retrieve.
                       If not provided, all security groups will be
                       returned.

    :type group_ids: list
    :param group_ids: A list of IDs of security groups to retrieve for
                      security groups within a VPC.

答案 1 :(得分:1)

我将在@Vor旁边显示另一个boto3答案。

恕我直言,你应该切换到boto3,开发人员已经明确表示boto不支持新功能。您不需要指定区域,您可以将区域绑定在凭证文件中等。

import boto3
import argparse
ec2=boto3.client("ec2")
parser = argparse.ArgumentParser(description="")
parser.add_argument('sec_group_id', help='Security group id')
args = parser.parse_args()
sec_group_id = args.sec_group_id

my_sec_grp = ec2.describe_security_groups(GroupIds = [sec_group_id])

Boto3与AWS Cli密切相关。当前的AWS cli已经显示了诸如&#34; - query&#34;允许用户过滤结果返回。如果AWS实现了该功能,那将是boto3,而不是boto。