简体   繁体   English

如何使用 boto3 列出附加到 IAM 角色的所有资源?

[英]How can I list the all the resources attached to a IAM role using boto3?

I wish to list down all the resources that is attached to a IAM role.我希望列出附加到 IAM 角色的所有资源。 I am writing a program that would clean up the IAM roles that are not associated with any resources(like ec2 resource, lambda, task definition etc.)我正在编写一个程序来清理与任何资源(如 ec2 资源、lambda、任务定义等)无关的 IAM 角色

import boto3
client = boto3.client('iam')
iam = boto3.resource('iam')
roles = client.list_roles()
role_name = []
Role_list = roles['Roles']
for key in Role_list:
    role_name.append(key['RoleName'])
print(*role_name,sep='\n')

for name in role_name:
    role = iam.Role( name )
    print(name)   
    print(role.get_available_subresources())

There is no command to list all resources that are "using" an IAM Role.没有命令可以列出“使用”IAM 角色的所有资源。

Instead, you would need to retrieve a list for each type of resource and then check the IAM Role that is assigned to each of them.相反,您需要为每种类型的资源检索一个列表,然后检查分配给每个类型的 IAM 角色。

Also, please note that applications can assume an IAM Role through an API call in their code.另请注意,应用程序可以通过其代码中的 API 调用承担 IAM 角色 Therefore, they are "using" an IAM Role, but there is no specific assignment of the role to the application.因此,他们“使用”了一个 IAM 角色,但没有将该角色具体分配给应用程序。

You can use get_role(RoleName="MyRoleName") to get the attached resources.您可以使用 get_role(RoleName="MyRoleName") 获取附加资源。

Boto3 Documentation Boto3 文档

iam = boto3.client('iam')
role_policy = iam.get_role(RoleName="MyRoleName")
print (role_policy)

Expected Output:预计 Output:

{
    'Role': {
        'Arn': 'arn:aws:iam::123456789012:role/Test-Role',
        'AssumeRolePolicyDocument': '<URL-encoded-JSON>',
        'CreateDate': datetime(2013, 4, 18, 5, 1, 58, 3, 108, 0),
        'Path': '/',
        'RoleId': 'AIDIODR4TAW7CSEXAMPLE',
        'RoleName': 'Test-Role',
    },
    'ResponseMetadata': {
        '...': '...',
    },
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM