Last active
November 20, 2024 15:17
-
-
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 hidden or 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 | |
''' | |
This gist is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. | |
This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. | |
You should have received a copy of the GNU General Public License along with this program. If not, see <https://www.gnu.org/licenses/>. | |
''' | |
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