python boto3 允许入口安全组

Tom*_*Tom 6 python amazon-web-services aws-cli boto security-groups

我正在开发一个简单的 python 脚本来向安全组添加规​​则,我想知道 boto3 中可用的两种方法之间有什么区别:authorize_security_group_ingress(**kwargs)authorize_ingress(**kwargs)

描述相同:“向安全组添加一个或多个入口规则”

Nat*_*ath 10

这两个不同的类是关于不同抽象级别的。

  • 客户端类是每个 API 操作的低级包装器。IE。授权安全组入口
  • 资源类是面向对象的,您可以实例化一个对象来表示该组并以这种方式与之交互。它提供了更高级别的抽象,将您与各个 API 调用分离并提供了一些持久性

为了显示差异,让我们创建一个安全组并向 Internet 开放端口 80。

与客户

    ec2 = boto3.client('ec2')
    response = ec2.create_security_group(GroupName='testgroup2',Description='testme')
    ec2.authorize_security_group_ingress(GroupId=response['GroupId'],IpProtocol="tcp",CidrIp="0.0.0.0/0",FromPort=80,ToPort=80)
Run Code Online (Sandbox Code Playgroud)

有资源:

    ec2 = boto3.resource('ec2')
    mysg = ec2.create_security_group(GroupName="testgroup",Description='testme')
    mysg.authorize_ingress(IpProtocol="tcp",CidrIp="0.0.0.0/0",FromPort=80,ToPort=80) 
Run Code Online (Sandbox Code Playgroud)

The key difference here is that resource object eliminates the need for a "response" variable and takes care of remembering the Security group for later use. It doesn't seem like a big difference but it makes your code cleaner and more object oriented
see the boto docs: https://boto3.readthedocs.org/en/latest/guide/resources.html for more detail on them.