代码之家  ›  专栏  ›  技术社区  ›  Putnik

无法使用boto3撤销非默认专有网络的\u入口

  •  0
  • Putnik  · 技术社区  · 6 年前

    AWS Lambda/python 2.7/boto3版本

    我正在试图从一个安全组的许多规则中撤销一个规则( SG_we_are_working_with )但接收错误

    发生了一个错误(InvalidGroup.NotFound)打电话给 RevokeSecurityGroupIngress操作:安全组“sg-xxxxx”

    SG_we_are_working_with = 'sg-xxxxx'
    SG_which_is_the_source_of_the_traffic = 'sg-11111111'
    VpcId = 'vpc-2222222'
    
    #first I load the group to find the necessary rule
    ec2 = boto3.resource('ec2')
    security_group = ec2.SecurityGroup(SG_we_are_working_with)
    security_group.load()   # get current data
    
    # here is loop over rules
    for item in security_group.ip_permissions:
    

    { 
    "PrefixListIds": [], 
    "FromPort": 6379, 
    "IpRanges": [], 
    "ToPort": 11211, 
    "IpProtocol": "tcp", 
    "UserIdGroupPairs": [ { 
        "UserId": "00111111111", 
        "Description": "my descr", 
        "GroupId": "sg-11111111" 
    } ], 
    "Ipv6Ranges": [] 
    }
    

    # now attempt to delete, the necessary data is in 'item' variable:
    IpPermissions=[
        {
            'FromPort': item['FromPort'],
            'ToPort': item['ToPort'],
            'IpProtocol': 'tcp',
            'UserIdGroupPairs': [
                {
                    'Description': item['UserIdGroupPairs'][0]["Description"],
                    'GroupId': item['UserIdGroupPairs'][0]["GroupId"],
                    'UserId': item['UserIdGroupPairs'][0]["UserId"],
                    'VpcId': str(VpcId)
                },
            ]
        }
    ]
    security_group.revoke_ingress(
        FromPort =  item['FromPort'],
        GroupName = SG_we_are_working_with,
        IpPermissions = IpPermissions,
        IpProtocol = 'tcp',
        SourceSecurityGroupName = SG_which_is_the_source_of_the_traffic,
        ToPort = item['ToPort']
    )
    

    我用的是 here

    我做错什么了?

    非常感谢。

    2 回复  |  直到 6 年前
        1
  •  0
  •   John Rotenstein    6 年前

    我发现撤销权限的最简单方法是传入安全组上已有的权限:

    import boto3
    
    # Connect to the Amazon EC2 service
    ec2 = boto3.resource('ec2')
    
    # Retrieve the security group
    security_groups = ec2.security_groups.filter(GroupNames=['MY-GROUP-NAME'])
    
    # Delete all rules in the group
    for group in security_groups:
        group.revoke_ingress(IpPermissions = group.ip_permissions)
    
        2
  •  0
  •   Putnik    6 年前

    上面的代码除了最后一部分外都是正确的,不知道为什么没有在文档中解释。

    security_group.revoke_ingress(
        IpPermissions = IpPermissions,
    )
    

    所以,所有这些东西

    FromPort =  item['FromPort'],
    GroupName = SG_we_are_working_with,
    IpProtocol = 'tcp',
    SourceSecurityGroupName = SG_which_is_the_source_of_the_traffic,
    ToPort = item['ToPort']
    

    过多并导致错误。