要查找并删除未使用的 IAM 角色,您可以使用 AWS CLI 和 AWS SDK 进行实现。以下是使用 AWS CLI 和 AWS SDK(Python)的解决方案示例:
使用 AWS CLI:
list-roles 命令列出所有 IAM 角色。aws iam list-roles
list-attached-role-policies 命令列出与每个角色关联的策略。aws iam list-attached-role-policies --role-name
delete-role 命令删除该角色。aws iam delete-role --role-name
使用 AWS SDK(Python):
import boto3
def find_unused_roles():
iam = boto3.client('iam')
response = iam.list_roles()
for role in response['Roles']:
response = iam.list_attached_role_policies(RoleName=role['RoleName'])
if len(response['AttachedPolicies']) == 0:
print('Role {} is not being used. Deleting...'.format(role['RoleName']))
iam.delete_role(RoleName=role['RoleName'])
print('Role {} deleted.'.format(role['RoleName']))
find_unused_roles()
请注意,执行此操作可能会删除正在使用的 IAM 角色,因此请谨慎操作。建议在进行任何删除操作之前,先进行适当的验证和测试。