terraform,

How to attach AWS managed policy to an IAM role in Terraform

Mar 05, 2022 · 1 min read · Post a comment

AWS Managed Policies are IAM policies created and managed by AWS. Today I’m going to show you how to attach a managed policy in Terraform.

Prerequisites

  • Terraform
  • AWS account

Solution

AmazonECSTaskExecutionRolePolicy policy example:

data "aws_iam_policy" "ecs_task_execution_role_policy" {
  name = "AmazonECSTaskExecutionRolePolicy"
}
...

resource "aws_iam_role_policy_attachment" "ecs_task_execution_role_policy" {
  role       = aws_iam_role.ecs_task_execution_role.name
  policy_arn = data.aws_iam_policy.ecs_task_execution_role_policy.arn
}

First, not a huge fan of hardcoding things, but since Terraform doesn’t currently support a data source for fetching AWS managed policy information, using the data source and hardcoding the arn would be arguably the best suitable approach.

Conclusion

There are alternative solutions as well, depending on how much the value changes overtime, who manages it, where it’s stored, how it’s accessed and few others. On a side note, follow our official channel on Telegram.