简体   繁体   中英

Edit an existing IAM Role trust policy using boto3

I need to update/append IAM role trust policy with Deny statement using boto3. If i use update_assume_role_policy , it is overwriting the previous policy instead of appending the new changes. So i tried to read existing policy using get_role and then append my statement to it, but running into below challenges

  1. If i do string replace - My code sample
    policy = '"Statement" : [ {"Sid": "Test","Effect": "Deny","Principal":{"AWS": "123456"},"Action": "*","Resource": "*"},{'        
            response = iam.get_role(RoleName= ResourceName)
            current_policy=str(response['Role']['AssumeRolePolicyDocument'])
            updated_policy = current_policy.replace('"Statement" : [ {', policy)

This works only if policy string matches '"Statement": [ {'. Its case sensitive and if the previous policy has single quote(') instead of double quote(") around Statement it doesn't work. I can use "re" module and write multiple conditions around it, but it adds too much complexity.

  1. If i take policy as dictionary and append value, it adds a " " around my update and it policy looks like
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::123456:root"
      },
      "Action": "sts:AssumeRole",
      "Condition": {}
    },
    "{
      "Effect": "Deny",
      "Principal": {
        "AWS": "arn:aws:iam::890123:root"
      },
      "Action": "sts:AssumeRole",
      "Condition": {}
    }"
  ]
}

Is there a better,easier way to update IAM Role trust policy?

I'm not sure why do you require string operation for that. You can just replace the individual components of your trust policy.

For example:

import boto3

iam = boto3.client('iam')

response = iam.get_role(RoleName='<role-name>') 

trust_policy = response['Role']['AssumeRolePolicyDocument']

print(trust_policy)

# change effect to `Deny`
trust_policy['Statement'][0]['Effect'] = 'Deny'

# change principle to '123456'
trust_policy['Statement'][0]['Principal']['AWS'] = '123456'

print(trust_policy)

You can do same for other components.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM