33
votes

My TF code is giving me an error:

  /*
   * Policy: AmazonEC2ReadOnlyAccess
   */
  assume_role_policy = <<EOF
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "ec2:Describe*",
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": "elasticloadbalancing:Describe*",
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": [
                "cloudwatch:ListMetrics",
                "cloudwatch:GetMetricStatistics",
                "cloudwatch:Describe*"
            ],
            "Resource": "*"
        },
        {
            "Effect": "Allow",
            "Action": "autoscaling:Describe*",
            "Resource": "*"
        }
    ]
}
EOF

I copied and pasted the Policy from https://console.aws.amazon.com/iam/home?region=us-west-2#/policies/arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess$jsonEditor

* aws_iam_role.<role name>: Error creating IAM Role <role name>: MalformedPolicyDocument: Has prohibited field Resource
status code: 400, request id: <request id>

Not sure why it's saying Resource is prohibited.

3
You're setting your policy stuff in the assume_role_policy, which is where you should be defining the policy of who can assume this role, not what this role can do. Try moving this policy to a aws_iam_policy resource and setting this assume_role_policy how @Gangaraju shows below.John Jones

3 Answers

26
votes

You need to mention sts:AssumeRole. You can directly attach policy using aws_iam_role_policy_attachment instead of duplicating existing policy.

resource "aws_iam_role" "ec2_iam_role" {
  name = "ec2_iam_role"
  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "",
      "Effect": "Allow",
      "Principal": {
        "Service": [
          "ec2.amazonaws.com"
        ]
      },
      "Action": "sts:AssumeRole"
    }
  ]
}
EOF
}

resource "aws_iam_role_policy_attachment" "ec2-read-only-policy-attachment" {
    role = "${aws_iam_role.ec2_iam_role.name}"
    policy_arn = "arn:aws:iam::aws:policy/AmazonEC2ReadOnlyAccess"
}
0
votes

I had faced similar issue when using role arn. When I tried using aws_iam_role_policy_attachment - I was getting error for role name having unsupported characters.

What worked for me for to create a aws_iam_role_policy as below:

resource "aws_iam_role_policy" "api-invoker" {
    provider = <some provider>
    role     = aws_iam_role.api-invoker.id
    policy   = data.aws_iam_policy_document.execute-api.json
}

data "aws_iam_policy_document" "execute-api" {
    statement {
     sid = "all"
     actions = [
       "execute-api:*",
     ]
     resources = [
       "*"
     ]
   }
}
0
votes

I have faced the same issue while i am creating a policy to assume role from another AWS account. So, I have added another AWS account Id in the trusted entities then the problem is resolved.