如何通过Terraform将现有策略附加到IAM角色及创建关联预定义AWS策略的IAM角色
Got it, let's get this sorted for you! You already have a solid base Terraform setup for creating an IAM role—attaching AWS's pre-built AmazonSSMFullAccess policy just needs the right policy ARN reference. Here are two straightforward ways to do it:
1. Directly Use the Fixed Pre-defined Policy ARN
AWS's managed policies follow a consistent ARN format: arn:aws:iam::aws:policy/<PolicyName>. For AmazonSSMFullAccess, the ARN is static, so you can plug it directly into your aws_iam_role_policy_attachment resource:
# Your existing IAM role definition resource "aws_iam_role" "role" { name = var.name assume_role_policy = var.assume_role_policy max_session_duration = var.max_session_duration description = var.description } # Attach the pre-defined AmazonSSMFullAccess policy resource "aws_iam_role_policy_attachment" "attach_ssm_full_access" { policy_arn = "arn:aws:iam::aws:policy/AmazonSSMFullAccess" role = aws_iam_role.role.name }
This works because AWS hosts this policy globally under that exact ARN—no need to create the policy yourself; you're just linking your role to the existing managed one.
2. Use a Terraform Data Source to Dynamically Fetch the Policy ARN (Recommended)
For a more robust approach (avoids hardcoding ARNs and reduces manual errors), use a data "aws_iam_policy" block to let Terraform look up the policy's ARN automatically:
# Fetch the ARN of the pre-defined AmazonSSMFullAccess policy data "aws_iam_policy" "ssm_full_access" { name = "AmazonSSMFullAccess" } # Your existing IAM role definition resource "aws_iam_role" "role" { name = var.name assume_role_policy = var.assume_role_policy max_session_duration = var.max_session_duration description = var.description } # Attach the policy using the dynamically fetched ARN resource "aws_iam_role_policy_attachment" "attach_ssm_full_access" { policy_arn = data.aws_iam_policy.ssm_full_access.arn role = aws_iam_role.role.name }
This method is better practice because it abstracts away hardcoded values—if AWS ever updates the policy's ARN (unlikely for managed policies, but possible), Terraform will handle it automatically.
Quick Notes
- Make sure your Terraform AWS provider has permissions to:
- Create IAM roles (
iam:CreateRole) - Attach policies to roles (
iam:AttachRolePolicy) - Read IAM policies (for the data source method,
iam:GetPolicy)
- Create IAM roles (
- Double-check your
assume_role_policyvariable is set correctly (it defines which entities can assume this role, e.g., EC2 instances, Lambda functions).
内容的提问来源于stack exchange,提问作者Sake

