由于 MalformedPolicyDocument,Boto3 脚本中的遗留解析错误

A legacy parsing error in Boto3 script due to MalformedPolicyDocument

我正在尝试在 AWS 上创建 IAM 用户并将其附加到具有 IAM 策略的用户组,但我收到“调用 CreatePolicy 操作时发生错误 (MalformedPolicyDocument):策略遗留解析失败”错误,我不确定这意味着什么。我觉得跟政策本身有关,但我不确定。

import boto3
import sys
import json
iam = boto3.client('iam')
sts = boto3.client('sts')

response = iam.create_user(
    UserName='GoodUser'
)
IDK = sts.get_caller_identity()
print(IDK['UserId'])
response = iam.create_group(
    GroupName='GoodGroup'
)

response = iam.add_user_to_group(
    GroupName='GoodGroup',
    UserName='GoodUser'
)

some_policy = {
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "ec2:RunInstances",
            "Resource": [
                "arn:aws:ec2:us-east-2:{}:instance/*".format(IDK),
                "arn:aws:ec2:us-east-2:{}:security-group/*".format(IDK),
                "arn:aws:ec2:us-east-2:{}:image/ami-0a91cd140a1fc148a".format(IDK)
            ],
        },
        {
            "Sid": "VisualEditor1",
            "Effect": "Allow",
            "Action": [
                "ec2:TerminateInstances",
                "ec2:StartInstances",
                "ec2:StopInstances"
            ],
            "Resource": "arn:aws:ec2:us-east-2:{}:instance/*".format(IDK),
            "Condition": {
                "ForAllValues:StringEquals": {
                    "ec2:InstanceType": "t2.micro"
                }
            }
        }
    ]
} 
response = iam.create_policy(
  PolicyName='GoodPolicy',
  PolicyDocument=json.dumps(some_policy)
)
print(response)

IDK1 = iam.attach_user_policy(
    UserName='GoodUser',
    PolicyArn='arn:aws:iam::{}:policy/some_policy'.format(IDK)
)

错误可能与您的 IDK 变量有关。

IDK = sts.get_caller_identity() returns 以下格式的字典:

{
    'UserId': 'string',
    'Account': 'string',
    'Arn': 'string'
}

稍后您使用此对象来格式化资源字符串:"arn:aws:ec2:us-east-2:{}:instance/*".format(IDK) 这将产生无效的委托人。我怀疑您可能打算做这样的事情:f"arn:aws:ec2:us-east-2:{IDK['Account']}:instance/*"(使用 f-string 而不是 str.format,结果是一样的)。