尝试在aws中创建iam角色并在assumeRolePolicyDocument
问题描述:
上获取错误我试图在AWS中为联合访问创建一个IAM角色,并使用boto或使用cli的powershell继续运行到python中的相同问题。尝试在aws中创建iam角色并在assumeRolePolicyDocument
这是我正在试图用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.
我已经通过运行JSON aws 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
)