简体   繁体   中英

Create security group tags using Python boto3

I'm creating a security group using the following code and would like to create a tag Name = SECURITY_GROUP_NAME (using my second argument).

 #!/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)

I would like to use security_group.create_tags but not sure how to get this to work and what do I define security_group as?

tag = security_group.create_tags(Tags=[{'Key': 'Name','Value': SECURITY_GROUP_NAME},])

In that example security_group is a security group resource . You would create that like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM