Choolai Raj
Choolai Raj

Reputation: 131

Attaching AWS Managed Policy to a Custom Role via Terraform

I am writing a tf script to create a role and attach an AWS Managed Policy to the Role. If my policy is a custom policy this works, If i need to use a an AWS managed policy, how do i attach my policy to the role. is there a way to use "data" to extrapolate the role ARN from AWS

resource "aws_iam_role" "CloudWatchAgentServerRole" {
  name               = "CloudWatchAgentServerRole"
  description        = "Role created to allow Memory metrics to CloudWatch "
  assume_role_policy = file("role.json")
}

#Create Policy - Not Required as its an AWS Managed Policy
/*resource "aws_iam_policy" "CloudWatchAgentServerPolicy" {
  name        = "CloudWatchAgentServerPolicy"
  description = "Permissions required to use AmazonCloudWatchAgent on servers"
  policy      = file("policy.json")
}*/

# Attach Policy 
resource "aws_iam_role_policy_attachment" "CloudWatchAgentServer" {
  role       = aws_iam_role.CloudWatchAgentServerRole.name
  policy_arn = aws_iam_policy.CloudWatchAgentServerPolicy.arn  
}

Thanks

Upvotes: 6

Views: 8008

Answers (1)

Mark B
Mark B

Reputation: 200476

The ARN for an AWS managed policy is going to be arn:aws:iam::aws:policy/ followed by the policy name. There's really no need to look it up using a data element, since it will always be in that format. So to attach the policy in your example you would use the following:

resource "aws_iam_role_policy_attachment" "CloudWatchAgentServer" {
  role       = aws_iam_role.CloudWatchAgentServerRole.name
  policy_arn = "arn:aws:iam::aws:policy/CloudWatchAgentServerPolicy"
}

Upvotes: 11

Related Questions