Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 views
in Technique[技术] by (71.8m points)

amazon iam - 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

question from:https://stackoverflow.com/questions/65890676/attaching-aws-managed-policy-to-a-custom-role-via-terraform

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...