nrhode
nrhode

Reputation: 942

How to create roles in terraform

I would like to create a aws_iam_role with terraform but after running terraform applyI get the following error message: aws_iam_role.role: Error Updating IAM Role (edb_eb_role) Assume Role Policy: MalformedPolicyDocument: Has prohibited field Resource

That is my policy:

resource "aws_iam_role" "role" {
name = "edb_eb_role"

  assume_role_policy = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": "sts:AssumeRole",
      "Principal": {
        "Service": "ec2.amazonaws.com"
      },
      "Effect": "Allow",
      "Sid": ""
    },
    {
        "Action": [
            "logs:*"
        ],
        "Effect": "Allow",
        "Resource": "*"
    },
    {
        "Effect": "Allow",
        "Action": [
            "lambda:InvokeFunction"
        ],
        "Resource": [
            "*"
        ]
    }
  ]
}
EOF
}

What did I wrong? I also tried to do it only with Principals but then I get the message that "Principals" is also not prohibited?

Upvotes: 3

Views: 3489

Answers (1)

Mithilesh_Kunal
Mithilesh_Kunal

Reputation: 929

Assume_role_policy don't accept the aws policy json files. So the above code is not working.
For detailed explanation of assume_role_policy in aws_iam_role, see this thread.

Update the code as shown below and execute.

variable policy_arn{
    default = "arn:aws:iam::aws:policy/service-role/AWSLambdaRole"
}
resource "aws_iam_role" "edb_role" {
name = "edb_role"

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


resource "aws_iam_role_policy_attachment" "test-attach" {
    role       = "${aws_iam_role.edb_role.name}"
    policy_arn = "${var.policy_arn}"
}

output "role" {
  value = "${aws_iam_role.edb_role.name}"
}

Here, we are using the AWSLambdaRole Policy present in Policies section of IAM.

  • Add multiple policies to a role using aws_iam_role_policy_attach
  • Use the default policies provided by aws as show above. Else to create a new policy, see the docs here


Upvotes: 4

Related Questions