2017-09-07 40 views
0

尝试列出帐户中的所有角色,以便我可以附加策略。我正在阅读boto3文档,但我没有看到一种方法来返回帐户中的一组角色。AWS Boto显示所有角色

这可能吗?

+0

您无法找到它,因为与api相关的角色位于boto3 IAM之下。典型的api访问密钥没有被赋予处理IAM的权利。您需要授予IAM访问权限才能执行此操作。 http://boto3.readthedocs.io/en/latest/reference/services/iam.html – mootmoot

回答

0

这是我想出来的。用您的实际值替换CAPS值。

附加一个内嵌的政策,所有角色的帐户

#!/usr/bin/env python 
# Author: Nick Skitch 

import boto3 
import json 


def main(): 

    boto3.setup_default_session(profile_name=PROFILE_NAME) 
    client = boto3.client('iam') 
    policy_document = get_policy_body(IAM_POLICY_JSON) 

    roles = get_roles(client) 

    for role in roles: 
     update_role(role,client,"required_tags",policy_document) 

def get_policy_body(data_file): 
    with open(data_file) as data_file: 
     data = data_file.read() 
    return data 

def update_role(role_name, client,iam_policy_name,policy_document): 
    response = client.put_role_policy(
    RoleName=role_name, 
    PolicyName=iam_policy_name, 
    PolicyDocument=policy_document 
    ) 

    print response 

def get_roles(client): 
    client = boto3.client('iam') 
    response = None 
    role_names = [] 
    marker = None 

    # By default, only 100 roles are returned at a time. 
    # 'Marker' is used for pagination. 
    while (response is None or response['IsTruncated']): 
     # Marker is only accepted if result was truncated. 
     if marker is None: 
      response = client.list_roles() 
     else: 
      response = client.list_roles(Marker=marker) 

     roles = response['Roles'] 
     for role in roles: 
      print(role['Arn']) 
      role_names.append(role['RoleName']) 

     if response['IsTruncated']: 
      marker = response['Marker'] 

    return role_names 



if __name__ == "__main__": 
    main() 
1

按你的问题中 - 你需要的政策附加到角色。 为此,首先,您要从帐户获取所有角色。 您可能需要以下两件事情之一将策略附加到特定角色。

  • 角色名称
  • 阿恩

下面的代码可以帮助你 - 我想提出一个IAM连接,并得到从帐户中的所有角色。因为,您将以Dicts和Array的形式获得输出结果,您需要提取arn或名称

import boto3 
client = boto3.client('iam',aws_access_key_id="XXXXX",aws_secret_access_key="YYYYY") 
roles = client.list_roles() 
Role_list = roles['Roles'] 
for key in Role_list: 
    print key['RoleName'] 
    print key['Arn']