IAM Create role malformed error via boto3

34 views Asked by At

Trying to set an IAM role for cross account access, wherein lambda from management account can run tasks on all other accounts by assuming cross account role. I was able to create the role n the non management account by console, but boto3 gives malformed policy document error.

LambdaCrossAccountRole is the role that has already been created in management account, and this role would need to be assumed by the role being created in non management account

The trust policy has been given as

trust_role="""
{
"Version":"2012-10-17",
"Statement":[{
           "Effect":"Allow",
           "Principal":{
                   "AWS":"arn:aws:iam::<management_account_id>:role/LambdaCrossAccountRole"},
    "Action":"sts.AssumeRole"}
]}"""

The iam role is being created by

iam-boto3.client("iam")
response_acct=iam.create_role(
RoleName="CrossAccountLambdaRole",
AssumeRolePolicyDocument=json.dumps(trust_role))

Error:

botocore.errorfactory.MalformedPolicyDocumentException: An error occurred(MalformedPolicyDocument) when calling CreateRole operation:This policy contains invalid Json

What maybe reasons for the error? Thanks

1

There are 1 answers

0
Tsal Troser On BEST ANSWER

From create_role documentation:

AssumeRolePolicyDocument (string) [REQUIRED] -

The trust relationship policy document that grants an entity permission to assume the role. In IAM, you must provide a JSON policy that has been converted to a string.

AssumeRolePolicyDocument should be a string, don't use json.dumps()

iam = boto3.client('iam')
iam.create_role(
    RoleName='TestRole',
    AssumeRolePolicyDocument=trust_role
)

Also update this:

# from this:
trust_role="""
{
...
}

# to this:
trust_role="""{
...
}

Otherwise it will throw an error:

An error occurred (MalformedPolicyDocument) when calling the CreateRole operation: JSON strings must not have leading spaces