Search code examples
pythonamazon-web-servicesboto3amazon-vpcaws-security-group

unable to check and create aws security group with boto3


I'm trying to create a security groups and get the secutity group id as output using boto3. I want something like this:

  1. If the security group exists, get/return/output the groud id.

  2. If the security group doesn't exists create and authorize the group with the given rule and output the group id

This is my code so far:

ec2 = boto3.client('ec2', region_name='us-east-1')
for rds_security_group in ec2.describe_security_groups()['SecurityGroups']:
    if rds_security_group['GroupName'] == 'testgroup':
         print(rds_security_group['GroupId'])
         return (rds_security_group['GroupId'])
     else:
          rds_security_group_name = ec2.create_security_group(
                GroupName='testgroup',
                Description='rds-security-group',
                VpcId='vpc-12345')
          client.authorize_security_group_ingress(
                CidrIp=10.10.10.10/11,
                IpProtocol='tcp',
                FromPort=90,
                ToPort=90,
                GroupId=rds_security_group_name['GroupId'])
          print(rds_security_group_name['GroupId'])
          return(rds_security_group_name['GroupId'])

if security group doesn't exists code works perfectly by creating the group and returns the group id. but fails to return the group id if the security group already exists and throws up the existing error.

botocore.exceptions.ClientError: An error occurred (InvalidGroup.Duplicate) when calling the CreateSecurityGroup operation: The security group 'testgroup' already exists for VPC 'vpc-12345'

please help me on this ?


Solution

  • Your problem is that you are looping thru each security group and checking its group name. If the first security group is not called "testgroup" then you try to create it. Change your code to the following:

    ec2 = boto3.client('ec2', region_name='us-east-1')
    for rds_security_group in ec2.describe_security_groups()['SecurityGroups']:
        if rds_security_group['GroupName'] == 'testgroup':
             print(rds_security_group['GroupId'])
             return (rds_security_group['GroupId'])
    
    # Security Group was not found, create it
    rds_security_group_name = ec2.create_security_group(
          GroupName='testgroup',
          Description='rds-security-group',
          VpcId='vpc-12345')
    client.authorize_security_group_ingress(
          CidrIp=10.10.10.10/11,
          IpProtocol='tcp',
          FromPort=90,
          ToPort=90,
          GroupId=rds_security_group_name['GroupId'])
    print(rds_security_group_name['GroupId'])
    return(rds_security_group_name['GroupId'])