I am trying to get the details of a aws IAM Policy via boto to be able to backup or replicate IAM policies via script. I have searched the docs of boto 2 and 3 but did not find any possibility to get the json data of a configured policy.
What I (successfully) did:
But I cannot find a way to retrieve the associated JSON data ('Policy Document' in Management Console) to get it in boto.
What I tried with boto:
import boto.iam
REGION_NAME = 'eu-west-1'
iam_conn = boto.iam.connect_to_region(REGION_NAME)
arn = 'arn:myproperlyformattedarn'
p = iam_conn.get_policy(arn)
print p
result:
{
"get_policy_response": {
"response_metadata": {
"request_id": "XXXXX-XXXX-XXXX-XXXX-XXXX"
},
"get_policy_result": {
"policy": {
"update_date": "2016-04-15T12:51:21Z",
"create_date": "2016-04-15T12:51:21Z",
"is_attachable": "true",
"policy_name": "My_Policy_Name",
"default_version_id": "v1",
"attachment_count": "1",
"path": "/",
"arn": "arn:aws:iam::123456789:policy/VerticaTest_GetConfigsFromS3",
"policy_id": "XXXSOMELONGSTRINGXXXX"
}
}
}
}
What I am after is something like this (the policy document in Management Console):
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "s3:*",
"Resource": [
"arn:aws:s3:::mybucketname",
"arn:aws:s3:::mybucketname/*"
]
}
]
}
The AWS SDK for Python (Boto3) provides a Python API for AWS infrastructure services. Using the SDK for Python, you can build applications on top of Amazon S3, Amazon EC2, Amazon DynamoDB, and more.
Most policies are stored in AWS as JSON documents. Identity-based policies and policies used to set permissions boundaries are JSON policy documents that you attach to a user or role.
Please move to boto3.
Approach this from the policy side: Identify the Policy ARN, Identify the Policy DefaultVersionId using the ARN, Retrieve the PolicyDocument using ARN and DefaultVersionId.
import boto3
import json
arn = 'arn:aws:iam::aws:policy/AdministratorAccess'
iam = boto3.client('iam')
policy = iam.get_policy(
PolicyArn = arn
)
policy_version = iam.get_policy_version(
PolicyArn = arn,
VersionId = policy['Policy']['DefaultVersionId']
)
print(json.dumps(policy_version['PolicyVersion']['Document']))
print(json.dumps(policy_version['PolicyVersion']['Document']['Statement']))
Run this code and pipe the output to "jq ." and you get the following output:
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "*",
"Resource": "*",
"Effect": "Allow"
}
]
}
[
{
"Action": "*",
"Resource": "*",
"Effect": "Allow"
}
]
You specifically requested the Actions / Statement in your question. I printed the 'Document' and 'Statement' properties to show the differences.
http://boto3.readthedocs.io/en/latest/reference/services/iam.html#IAM.Client.get_policy http://boto3.readthedocs.io/en/latest/reference/services/iam.html#IAM.Client.get_policy_version
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With