Skip to main content
 首页 » 编程设计

python之boto3 iam 客户端 : get policy by name

2025年01月19日17傻小

我正在尝试从 boto3 客户端获取策略,但没有使用策略名称的方法。通过将 create_policy 方法包装在 try-except block 中,我可以检查策略是否存在。除了列出所有策略并对其进行迭代之外,是否有任何方法可以使用 boto3 按名称获取策略-arn。

请您参考如下方法:

给定前缀(如果有的话,还有名称),ARN 应该是确定性的。

iam = session.client('iam') 
sts = session.client('sts') 
 
# Slow and costly if you have many pages 
paginator = iam.get_paginator('list_policies') 
all_policies = [policy for page in paginator.paginate() for policy in page['Policies']] 
[policy_1] = [p for p in all_policies if p['PolicyName'] == policy_name] 
 
# Fast and direct 
account_id = sts.get_caller_identity()['Account'] 
policy_arn = f'arn:aws:iam::{account_id}:policy/{policy_name}' 
policy_2 = iam.get_policy(PolicyArn=policy_arn)['Policy'] 
 
# They're equal except with the direct method you'll also get description field 
all(policy_1[k] == policy_2[k] for k in policy_1.keys() & policy_2.keys())