Create a security group and rules using Boto3 module.

0 votes

Hi Guys,

I have configured boto3 module so that it can connect to AWS account. Now I want to create a security group with Boto3 module. How can I do that?

Oct 8 in AWS by akhtar
• 33,470 points
56 views

1 answer to this question.

0 votes

Hi@akhtar,

A security group is for use with instances either in the EC2-Classic platform or in a specific VPC. You can create a security group in AWS in different way. Boto3 module also has the ability to create a security group as shown below.

import boto3
from botocore.exceptions import ClientError
ec2 = boto3.client('ec2')
response = ec2.describe_vpcs()
vpc_id = response.get('Vpcs', [{}])[0].get('VpcId', '')
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': 'tcp',
             'FromPort': 80,
             'ToPort': 80,
             'IpRanges': [{'CidrIp': '0.0.0.0/0'}]},
            {'IpProtocol': 'tcp',
             'FromPort': 22,
             'ToPort': 22,
             'IpRanges': [{'CidrIp': '0.0.0.0/0'}]}
        ])
    print('Ingress Successfully Set %s' % data)
except ClientError as e:
    print(e)

answered Oct 8 by MD
• 79,390 points

Related Questions In AWS

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How to delete a security group using Boto3 module?

Hi@akhtar, If you attempt to delete a security ...READ MORE

answered Oct 8 in AWS by MD
• 79,390 points
51 views
0 votes
1 answer

How to create a security group in AWS with Boto3?

Hi@akhtar, You can create a new security group ...READ MORE

answered Oct 10 in AWS by MD
• 79,390 points
116 views