Search code examples
pythonpython-3.xsubprocessaws-cliaws-security-group

Check Security Group existence in Python?


I use aws-cli v1 and I want to check the SG existence is certain VPC.

I use the command describe-security-groups which seems to be the only available for this task:

aws ec2 describe-security-groups --region=us-east-2 --output=json --group-name=test

The problem is that when the group is non-existent it throws unhandleable error in shell

An error occurred (InvalidGroup.NotFound) when calling the DescribeSecurityGroups operation: The security group 'test' does not exist in default VPC 'vpc-xxxxxxxx'

which results in the following error in Python function:

File "script.py", line 93, in makesg
ap = subprocess.check_output(cmd)
File "/usr/lib64/python3.7/subprocess.py", line 411, in check_output
**kwargs).stdout
File "/usr/lib64/python3.7/subprocess.py", line 512, in run
output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['aws', 'ec2', 'describe-security-groups', '--region=eu-east-1', '--vpc-id=vpc-xxxxxxx', '--group-name=test']' returned non-zero exit status 255.

Is there any aws-cli command that allows checking existence? I found only security-group-exists, however it is a sub-command of wait and is not applicable standalone.

Catching subprocess.CalledProcessError error in the function doesn't seem very Pythonic for me, what is the best practice?


Solution

  • Instead of querying the specific SG and handling the exception, you could instead query all Security Groups with AWS CLI, get the result and handle the comparison in Python:

    security_group_names_str = subprocess.check_output(['aws', 'ec2', 'describe-security-groups', '--output=json', '--query=SecurityGroups[].GroupName'])
    security_group_names = json.loads(security_group_names_str)
    
    if SG_NAME_TO_FIND in security_group_names:
      handle_sg_found()
    else:
      handle_sg_not_found()
    

    As mentioned already in the other answer, you could implement the same also with boto3 (AWS SDK).