Last active
April 26, 2024 11:49
-
-
Save zachlankton/29777c1a477febff92423ac6fabe203d to your computer and use it in GitHub Desktop.
Find policies in AWS that contain some text
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 | |
iam = boto3.client('iam') | |
def find_policies_with_action(action): | |
policies = iam.list_policies()['Policies'] | |
for policy in policies: | |
policy_arn = policy['Arn'] | |
default_version_id = policy['DefaultVersionId'] | |
policy_version = iam.get_policy_version(PolicyArn=policy_arn, VersionId=default_version_id) | |
policy_document = policy_version['PolicyVersion']['Document'] | |
if 'Statement' in policy_document: | |
statements = policy_document['Statement'] | |
if isinstance(statements, dict): | |
statements = [statements] # Convert single statement object to a list | |
for statement in statements: | |
if 'Action' in statement: | |
actions = statement['Action'] | |
if isinstance(action, list): | |
if any(action in res for res in actions): | |
print(f"Policy: {policy['PolicyName']} (Action: {policy_arn})") | |
break | |
elif isinstance(actions, str): | |
if action in actions: | |
print(f"Policy: {policy['PolicyName']} (Action: {policy_arn})") | |
break | |
# Example usage | |
find_policies_with_action('sts:AssumeRole') |
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 | |
iam = boto3.client('iam') | |
def find_policies_with_arn(arn): | |
policies = iam.list_policies()['Policies'] | |
for policy in policies: | |
policy_arn = policy['Arn'] | |
default_version_id = policy['DefaultVersionId'] | |
policy_version = iam.get_policy_version(PolicyArn=policy_arn, VersionId=default_version_id) | |
policy_document = policy_version['PolicyVersion']['Document'] | |
if 'Statement' in policy_document: | |
statements = policy_document['Statement'] | |
if isinstance(statements, dict): | |
statements = [statements] # Convert single statement object to a list | |
for statement in statements: | |
if 'Resource' in statement: | |
resource = statement['Resource'] | |
if isinstance(resource, list): | |
if any(arn in res for res in resource): | |
print(f"Policy: {policy['PolicyName']} (ARN: {policy_arn})") | |
break | |
elif isinstance(resource, str): | |
if arn in resource: | |
print(f"Policy: {policy['PolicyName']} (ARN: {policy_arn})") | |
break | |
# Example usage | |
find_policies_with_arn('arn:aws:secretsmanager') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment