0

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?

Suncatcher
  • 10,355
  • 10
  • 52
  • 90
  • Are you open to use the Python AWS SDK or you have reasons to stick with calling the AWS CLI from Python? – Andre.IDK Nov 30 '20 at 10:45
  • Yep, I'd rather stick to aws cli due to existing codebase, however if you have beautiful solution in AWS SDK, you are welcome – Suncatcher Nov 30 '20 at 10:55

2 Answers2

1

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).

Andre.IDK
  • 1,951
  • 13
  • 17
0

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

It is pythonic, you can take a look at this question to handle the different error cases. Something along the lines of

try:
    subprocess.checkout_ouput(...)
except subprocess.CalledProcessError as exception:
    if security_group_not_found(exception):
         handle_it()
    else:
        raise exception

Would be a clean way to handle it. you can also look at the aws sdk it might handle your use-case better.

Taek
  • 1,004
  • 7
  • 20