检查 Python 中是否存在安全组?

Check Security Group existence in Python?

我使用 aws-cli v1,我想检查 SG 是否存在某个 VPC。

我使用的命令 describe-security-groups 似乎是此任务唯一可用的命令:

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

问题是,当该组不存在时,它会在 shell

中抛出无法处理的错误

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

这会导致 Python 函数出现以下错误:

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.

是否有任何 aws-cli 命令可以检查是否存在?我只找到 security-group-exists, however it is a sub-command of wait 并且不适用独立。

在函数中捕获 subprocess.CalledProcessError 错误对我来说似乎不是很 Pythonic,最佳做法是什么?

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

它是 pythonic,你可以看看 this question 来处理不同的错误情况。类似于

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

这将是一种干净的处理方式。您还可以查看 aws sdk 它可能会更好地处理您的用例。

您可以使用 AWS CLI 查询所有安全组,获取结果并在 Python:

中处理比较,而不是查询特定的 SG 和处理异常
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()

正如其他答案中已经提到的,您也可以使用 boto3 (AWS SDK) 实现相同的功能。