简体   繁体   English

使用 boto3 编辑现有 IAM 角色信任策略

[英]Edit an existing IAM Role trust policy using boto3

I need to update/append IAM role trust policy with Deny statement using boto3.我需要使用 boto3 使用 Deny 语句更新/附加 IAM 角色信任策略。 If i use update_assume_role_policy , it is overwriting the previous policy instead of appending the new changes.如果我使用update_assume_role_policy ,它会覆盖以前的策略,而不是附加新的更改。 So i tried to read existing policy using get_role and then append my statement to it, but running into below challenges所以我尝试使用get_role阅读现有政策,然后使用 append 我对它的声明,但遇到以下挑战

  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": [ {'.这仅在策略字符串匹配 '"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.它区分大小写,如果以前的策略在 Statement 周围有单引号(')而不是双引号(“),它就不起作用。我可以使用“re”模块并围绕它编写多个条件,但它增加了太多的复杂性。

  1. If i take policy as dictionary and append value, it adds a " " around my update and it policy looks like如果我将策略作为字典和 append 值,它会在我的更新周围添加一个“”,它的策略看起来像
{
  "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?是否有更好、更简单的方法来更新 IAM 角色信任策略?

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.您可以对其他组件执行相同操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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