如何遍历字典中Resource键对应的嵌套列表并验证资源取值
遍历AWS IAM策略Resource字段的实现方案
原代码问题排查
你当前的代码存在以下几个问题导致运行不符合预期:
- 如果你定义的
policy变量是你给出的单个权限声明字典结构,直接for value in policy会遍历字典的键名(字符串类型的'Action'/'Effect'/'Resource'),无法通过value['Resource']取到对应的资源列表 - 变量名拼写错误:你赋值的变量是
Resource,第二层循环写的是Resources多了后缀s - if判断语句末尾缺少冒号,属于Python语法错误
- 未兼容Resource字段为单个字符串的合法场景,直接遍历会出现按字符拆分的异常
正确实现代码
场景1:policy为单个权限声明字典(即你给出的结构)
def check_target_resource_exists(statement, target_res: str = "arn:aws:s3:::bucket") -> bool: resource_val = statement.get("Resource", []) # 兼容Resource为单个字符串的情况 resource_list = [resource_val] if isinstance(resource_val, str) else resource_val for resource in resource_list: if resource == target_res: return True return False # 调用示例 your_policy = { 'Action': ['s3:PutObject', 'kms:GenerateKey'], 'Effect': 'Allow', 'Resource': ['arn:aws:kms:us-west-2:<account_id>:key/*', 'arn:aws:s3:::bucket'] } print(check_target_resource_exists(your_policy)) # 输出True
场景2:policy为标准AWS IAM策略结构(外层带Statement列表)
标准AWS策略的结构会在外层嵌套Statement字段存储所有权限声明,适配代码如下:
def check_policy_resource(policy, target_res: str = "arn:aws:s3:::bucket") -> bool: statement_list = policy.get("Statement", []) for stmt in statement_list: # 跳过拒绝类型的权限声明,可根据需求调整 if stmt.get("Effect") != "Allow": continue resource_val = stmt.get("Resource", []) resource_list = [resource_val] if isinstance(resource_val, str) else resource_val for resource in resource_list: if resource == target_res: return True return False
扩展说明
如果需要支持AWS策略的通配符匹配(比如判断资源是否符合arn:aws:s3:::*这类通配规则),可以使用Python内置的fnmatch模块实现模式匹配:
import fnmatch def match_resource_pattern(resource: str, pattern: str) -> bool: return fnmatch.fnmatch(resource, pattern)
内容的提问来源于stack exchange,提问作者Mxvii
相关产品推荐
相关产品推荐

