使用Python boto3创建安全组标签

时间:2018-07-10 18:31:38

标签: python python-3.x amazon-web-services boto3

我正在使用以下代码创建安全组,并希望创建标签名称 = SECURITY_GROUP_NAME(使用第二个参数)。

${family}

我想使用security_group.create_tags,但不确定如何使它工作以及我将security_group定义为什么?

 #!/usr/bin/env python

import sys
import boto3
from botocore.exceptions import ClientError
region = "us-east-1"

VPC_ID=sys.argv[1]
SECURITY_GROUP_NAME=sys.argv[2]
DESCRIPTION=sys.argv[3]
IP_PROTOCOL_1=sys.argv[4]
FROM_PORT_1=sys.argv[5]
TO_PORT_1=sys.argv[6]
CIDR_IP_1=sys.argv[7]

ec2 = boto3.client('ec2')

response = ec2.describe_vpcs()

vpc_id = VPC_ID

try:
    response = ec2.create_security_group(GroupName=SECURITY_GROUP_NAME,Description=DESCRIPTION,VpcId=VPC_ID)
    security_group_id = response['GroupId']
    print('Security Group Created %s in vpc %s.' % (security_group_id, vpc_id))

    data = ec2.authorize_security_group_ingress(
        GroupId=security_group_id,
        IpPermissions=[
            {'IpProtocol': IP_PROTOCOL_1,
             'FromPort': int(FROM_PORT_1),
             'ToPort': int(TO_PORT_1),
             'IpRanges': [{'CidrIp': CIDR_IP_1}]}
        ]
    )
    print('Ingress Successfully Set %s' % data)
except ClientError as e:
    print(e)

1 个答案:

答案 0 :(得分:0)

在该示例中,security_groupsecurity group resource。您将这样创建:

ec2_resource = boto3.resource('ec2')
security_group = ec2_resource.SecurityGroup(security_group_id)