Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update IAM Policy using Boto3 Python

I have a S3 bucket read policy :

   {
      "Version":"2012-10-17",
      "Statement":[
        {
          "Effect":"Allow",
          "Action":["s3:GetObject"],
          "Resource":["arn:aws:s3:::examplebucket/*"]
        }
      ]
    }

Based on a cloud trail logs when new bucket is created , I am creating an event which will invoke a Lambda function.

Able to read json for the policy and add a new resource (bucket) to the same policy. Is there a direct python API to be invoked which will update an existing IAM policy with new resource ?

like image 448
K.Pil Avatar asked Jun 17 '26 18:06

K.Pil


1 Answers

I found the right way of doing it:

You have to create a policy version (including your policy changes) of your existing policy and tag it as default. As so the new version will replace the existing policy.

Get your existing policy :

policy = iam.Policy('arn:aws:iam::' + ACCOUNT_ID + ':policy/' + POLICY_NAME)

Get JSON from this policy:

policyJson = policy.default_version.document

Change it as you want:

policyJson['Statement'].append({  
'Action': '*',
'Resource': 'arn:aws:ec2:::*/*',
'Effect': 'Allow'
})

Create a policy version with the new JSON and the option SetAsDefault to True

response = client.create_policy_version(
    PolicyArn= 'arn:aws:iam::' + ACCOUNT_ID + ':policy/' + POLICY_NAME,
    PolicyDocument= json.dumps(policyJson),
    SetAsDefault= True
)

Delete the previous version (optional but recommanded max 5 versions ):

response = client.delete_policy_version(
    PolicyArn= 'arn:aws:iam::' + ACCOUNT_ID + ':policy/' + POLICY_NAME,
    VersionId= version.version_id
    ) 

And you're good to go!

Thomas.

Ref: IAM DOC

like image 182
MacPowered Avatar answered Jun 20 '26 08:06

MacPowered



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!