python - 尝试在 aws 中创建 iam 角色并在 assumeRolePolicyDocument 上出现错误

标签 python amazon-web-services single-sign-on amazon-iam federation

我正在尝试在 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/

相关文章:

python - Python代码解释——整数分割

python - Pandas - 根据具有重复名称的重复键值对列 reshape 数据框列

python - 如何使用 Python 在 Blender 2.61 中移动相机

python - Spark Structured Streaming - 新批处理上的空字典

amazon-web-services - S3 警告 : "No content length specified for stream data"

visual-studio - Windows 上的 AWS Beanstalk ebextensions

java - 从 EC2 访问 SQS - 实例配置文件与角色

jsp - java web app jsp - 事件目录和 tomcat SSO

java - 使用 Java 客户端进行单点登录

ASP.NET 与 Windows Azure Active Directory SSO