3

I am trying to create an IAM role in AWS for federated access and keep running into the same issue in python using boto or powershell using the cli.

Here is what I am trying to do with 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
)

This referenced trustPolicy.json is constructed like this

{
   "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"
         }
      }
   ]
}

When I run this code with that file I get the following error

ClientError: An error occurred (ValidationError) when calling the CreateRole operation: The specified value for assumeRolePolicyDocument is invalid. It must contain only printable ASCII characters.

I have run the json through the aws json validator and it validates, and have also run the regex for allowable characters and it passes that as well. I have also tried copying an existing trust policy from a manually created role and using that content for my json file but that generates the same error as well.

Matthew Lee
  • 85
  • 2
  • 8

1 Answers1

1

AssumeRolePolicyDocument requires URL encoded contents of the file. We can use urllib.quote() for this:

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
)
Karthik
  • 1,721
  • 20
  • 24