优化后boto3 remove_user调用RevokeSecurityGroupIngress报错排查
AWS EC2安全组批量移除规则报错原因分析
场景说明
我正在编写Python工具,用于在AWS上为EC2安全组添加或移除用户,通过指定IP地址管控特定人员对私有服务端系统的访问权限。add_user()函数运行正常,原始remove_user()函数通过循环逐个调用AWS接口可正常工作,但为减少调用次数优化为批量收集规则ID后一次性调用时出现错误。
优化后的remove_user()代码
# remove the user from the security group def remove_user(self): ids = [] # searchs for the user's name in the security group and removes it if it exists for rule in self.rules: # apply to ingress rules only if (not rule['IsEgress']): # check if the rule is for the user if (rule['Description'] == self.user.name): ids.append(rule['SecurityGroupRuleId']) client.revoke_security_group_ingress(GroupId=self.group_id, SecurityGroupRuleIds=ids)
运行报错信息
Traceback (most recent call last): File "<stdin>", line 1, in <module> File "C:\host\src\tool_dir\tool.py", line 50, in remove_user client.revoke_security_group_ingress(GroupId=self.group_id, SecurityGroupRuleIds=rule_ids) File "C:\Users\me\AppData\Local\Programs\Python\Python311\Lib\site-packages\botocore\client.py", line 535, in _api_call return self._make_api_call(operation_name, kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "C:\Users\me\AppData\Local\Programs\Python\Python311\Lib\site-packages\botocore\client.py", line 980, in _make_api_call raise error_class(parsed_response, operation_name) botocore.exceptions.ClientError: An error occurred (MissingParameter) when calling the RevokeSecurityGroupIngress operation: Either 'ipPermissions' or 'securityGroupRuleIds' should be provided.
错误原因
核心原因是当未找到匹配指定用户的安全组规则时,ids列表为空。此时调用revoke_security_group_ingress接口时,传入的SecurityGroupRuleIds是一个空列表,不符合AWS API的参数要求——API明确要求必须提供ipPermissions或securityGroupRuleIds中的至少一个有效参数,空列表会被判定为未提供有效参数,从而触发MissingParameter错误。
另外代码中存在变量名不一致的小问题:函数内收集ID的变量是ids,但报错信息里调用API时用的是rule_ids,这也可能导致问题,但主要触发报错的原因还是空列表的情况。
修复方法
在调用AWS接口前先判断ids列表是否非空,只有当存在需要移除的规则ID时再执行撤销操作:
# remove the user from the security group def remove_user(self): ids = [] # searchs for the user's name in the security group and removes it if it exists for rule in self.rules: # apply to ingress rules only if (not rule['IsEgress']): # check if the rule is for the user if (rule['Description'] == self.user.name): ids.append(rule['SecurityGroupRuleId']) # 仅当有需要移除的规则时调用API if ids: client.revoke_security_group_ingress(GroupId=self.group_id, SecurityGroupRuleIds=ids)
内容的提问来源于stack exchange,提问作者amariani
相关产品推荐
相关产品推荐

