Created
July 24, 2019 14:53
-
-
Save gene1wood/ad9083866a7d5cb68ef0543786c2fdf9 to your computer and use it in GitHub Desktop.
Function to return all AWS IAM policy documents (inline and managed) for a given IAM role
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import boto3 | |
def get_paginated_results(product, action, key, credentials=None, args=None): | |
args = {} if args is None else args | |
credentials = {} if credentials is None else credentials | |
return [y for sublist in [x[key] for x in boto3.client( | |
product, **credentials).get_paginator(action).paginate(**args)] | |
for y in sublist] | |
def get_policy_documents_for_role(role_name, credentials): | |
attached_policies = get_paginated_results( | |
'iam', 'list_attached_role_policies', 'AttachedPolicies', | |
credentials, {'RoleName': role_name}) | |
inline_policies = get_paginated_results( | |
'iam', 'list_role_policies', 'PolicyNames', | |
credentials, {'RoleName': role_name}) | |
policies = [] | |
client_iam = boto3.client( | |
'iam', **credentials) | |
for policy_arn in [x['PolicyArn'] for x in attached_policies]: | |
version_id = client_iam.get_policy( | |
PolicyArn=policy_arn)['Policy']['DefaultVersionId'] | |
response = client_iam.get_policy_version( | |
PolicyArn=policy_arn, VersionId=version_id) | |
# supposedly boto3 urldecodes and json parses the document | |
# https://docs.aws.amazon.com/code-samples/latest/catalog/python-iam-get_policy_version.py.html | |
policies.extend(response['PolicyVersion']['Document']) | |
for policy_name in inline_policies: | |
response = client_iam.get_role_policy( | |
RoleName=role_name, | |
PolicyName=policy_name) | |
# see if an IAM policy written in YAML in CloudFormation is correctly parsed and returned here as an object | |
policies.extend(response['PolicyDocument']) | |
return policies |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment