How to change AWS trusted user "sts ExternalId" using python?

Viewed 364

In my IAM policy Trust Relationship is showing like below

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::279121212121212:user/ai-s-p57s13"
      },
      "Action": "sts:AssumeRole",
      "Condition": {
        "StringEquals": {
          "sts:ExternalId": "xxxxxxxxxxx=2_0vy+PyUFdt728JrFjqeCOau62zU="
        }
      }
    }
  ]
}

Now I want change Trust Relationship aws :: sts:ExternalId id to new values like below using python :

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::333333333333:user/ai-s-p57s13"
      },
      "Action": "sts:AssumeRole",
      "Condition": {
        "StringEquals": {
          "sts:ExternalId": "yyyyyyyyyy=2_0vy+PyUFdt728JrFjqeCOau62zU="
        }
      }
    }
  ]
}

using python i want to change

i have tried using below code :

import boto3

client = boto3.client('iam')
response = client.attach_role_policy(RoleName='testrole', PolicyArn='arn:aws:iam::279121212121212:user/testrole')
trust_policy = response['Role']['AssumeRolePolicyDocument']
trust_policy['Statement'][0]['Principal'] ['AWS']= 'arn:aws:iam::279121212121212:user/ai-s-p57s13'
1 Answers

You can do this as follows:

import json
import boto3

iam = boto3.client('iam')

role_name = "testrole"

# get existing role info
role_info = iam.get_role(RoleName = role_name)

# get trust policy
trust_policy = role_info['Role']['AssumeRolePolicyDocument']

#print(trust_policy)

# get external_id
exiting_external_id = trust_policy['Statement'][0]['Condition']['StringEquals']['sts:ExternalId']

#print(exiting_external_id)

new_prefix='yyyyyyyyyy'

# create new external id
new_external_id = new_prefix + "=" + exiting_external_id.split('=', 1)[1]

#print(new_external_id)

# update the trust policy
trust_policy['Statement'][0]['Condition']['StringEquals']['sts:ExternalId'] = new_external_id

print(trust_policy)

# update the role
response = iam.update_assume_role_policy(
    RoleName=role_name,
    PolicyDocument=json.dumps(trust_policy)
)

print(response)
Related