Saksham Agarwal
Saksham Agarwal

Reputation: 101

boto3 iam client: get policy by name

I am trying to get a policy from boto3 client but there is no method to do so using policy name. By wrapping the create_policy method in a try-except block i can check whether a policy exists or not. Is there any way to get a policy-arn by name using boto3 except for listing all policies and iterating over it.

Upvotes: 8

Views: 5064

Answers (2)

eric.frederich
eric.frederich

Reputation: 1668

The ARN should be deterministic given the prefix (if any, and the name).

iam = session.client('iam')
sts = session.client('sts')

# Slow and costly if you have many pages
paginator = iam.get_paginator('list_policies')
all_policies = [policy for page in paginator.paginate() for policy in page['Policies']]
[policy_1] = [p for p in all_policies if p['PolicyName'] == policy_name]

# Fast and direct
account_id = sts.get_caller_identity()['Account']
policy_arn = f'arn:aws:iam::{account_id}:policy/{policy_name}'
policy_2 = iam.get_policy(PolicyArn=policy_arn)['Policy']

# They're equal except with the direct method you'll also get description field
all(policy_1[k] == policy_2[k] for k in policy_1.keys() & policy_2.keys())

Upvotes: 7

John Hanley
John Hanley

Reputation: 81464

You will need to iterate over the policies to get policy names. I am not aware of a get-policy type api that uses policy names only policy ARNs.

Is there a reason that you do not want to get a list of policies? Other than to not download the list.

Upvotes: 1

Related Questions