我正在尝试在 AWS 中创建一个 IAM 角色以进行联合访问,并在 python 中使用 boto 或使用 cli 的 powershell 继续遇到相同的问题。
这是我尝试用 python 做的事情。
import boto3
tpdoc = r'c:\folders\trustPolicy.json'
with open(tpdoc, 'r') as tpfile:
data = tpfile.read()
client = boto3.client('iam')
response = client.create_role(
RoleName="testrole",
AssumeRolePolicyDocument=data
)
这个引用的 trustPolicy.json 是这样构造的
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "sts:AssumeRoleWithSAML",
"Effect": "Allow",
"Condition": {
"StringEquals": {
"SAML:aud": "https://signin.aws.amazon.com/saml"
}
},
"Principal": {
"Federated": "arn:aws:iam::1234567890:saml-provider/myidp"
}
}
]
}
当我用那个文件运行这段代码时,我得到以下错误
ClientError: An error occurred (ValidationError) when calling the CreateRole operation: The specified value for assumeRolePolicyDocument is invalid. It must contain only printable ASCII characters.
我已经通过 aws json 验证器运行 json 并进行了验证,还运行了允许字符的正则表达式,它也通过了验证。我还尝试从手动创建的角色复制现有的信任策略并将该内容用于我的 json 文件,但这也会产生相同的错误。
最佳答案
AssumeRolePolicyDocument
需要文件的 URL 编码内容。
为此,我们可以使用 urllib.quote()
:
import boto3
import urllib
tpdoc = r'c:\folders\trustPolicy.json'
with open(tpdoc, 'r') as tpfile:
data = tpfile.read()
encodedPolicy = urllib.quote(data)
client = boto3.client('iam')
response = client.create_role(
RoleName="testrole",
AssumeRolePolicyDocument=encodedPolicy
)
关于python - 尝试在 aws 中创建 iam 角色并在 assumeRolePolicyDocument 上出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42841958/