如何使用python更改AWS信任用户“stsExternalId”?

sai*_*sai 5 python amazon-web-services python-2.7 python-3.x amazon-iam

在我的 IAM 策略中,信任关系显示如下

{
  "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="
        }
      }
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

现在我想aws :: sts:ExternalId使用以下命令将信任关系 id 更改为新值,如下所示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="
        }
      }
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

使用python我想改变

我尝试使用下面的代码:

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'
Run Code Online (Sandbox Code Playgroud)

Mar*_*cin 0

您可以按如下方式执行此操作:

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)
Run Code Online (Sandbox Code Playgroud)