Home > OS >  How to create an AWS IAM role with JSON formatted trust policy string from a variable
How to create an AWS IAM role with JSON formatted trust policy string from a variable

Time:07-25

I am trying to create an AWS IAM role, supplying the assume role trust policy from a JSON formatted string instead of a JSON file. More specifically, in aws iam create-role command, when I use the option --assume-role-policy-document file://iam_role_trust_policy.json", the IAM role is created. However, when I try the option --assume-role-policy-document $IAM_ROLE_TRUST_POLICY, it fails with the following error:

Unknown options: "2012-10-17",, "Statement":, [, {, "Effect":, "Allow",, "Principal":, {, "AWS":, "arn:aws:iam::111111111111:user/svc-tooling-user", },, "Action":, "sts:AssumeRole", }, ], }, "Version":

The variable $IAM_ROLE_TRUST_POLICY contains the same JSON string as the file iam_role_trust_policy.json contains.

It can be reproduced in the following way:

$ IAM_ROLE_TRUST_POLICY=$(cat <<-END
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::111111111111:user/svc-tooling-user"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}
END
)

$ aws iam create-role \
    --role-name  myTestRole\
    --assume-role-policy-document $IAM_ROLE_TRUST_POLICY

Result:

Unknown options: "2012-10-17",, "Statement":, [, {, "Effect":, "Allow",, "Principal":, {, "AWS":, "arn:aws:iam::111111111111:user/svc-tooling-user", },, "Action":, "sts:AssumeRole", }, ], }, "Version":

The following, using the option file:// just works fine:

$ aws iam create-role \
    --role-name  myTestRole\
    --assume-role-policy-document file://iam_role_trust_policy.json

I compared the contents of the variable IAM_ROLE_TRUST_POLICY and the file iam_role_trust_policy.json. They are identical.

$ echo $IAM_ROLE_TRUST_POLICY
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::111111111111:user/svc-tooling-user"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}

$ cat iam_trust_policy.json 
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Principal": {
                "AWS": "arn:aws:iam::111111111111:user/svc-tooling-user"
            },
            "Action": "sts:AssumeRole"
        }
    ]
}

What could be the issue here and how can I fix this?

Note: In the code and output, I replaced the actual AWS account with 111111111111.

CodePudding user response:

You have to do it as follows (add quotes):

aws iam create-role \
    --role-name  myTestRole\
    --assume-role-policy-document "${IAM_ROLE_TRUST_POLICY}"
  • Related