You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Terraform将现有策略附加到IAM角色及创建关联预定义AWS策略的IAM角色

How to Attach AWS Pre-defined AmazonSSMFullAccess Policy to an IAM Role with Terraform

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.

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)
  • Double-check your assume_role_policy variable is set correctly (it defines which entities can assume this role, e.g., EC2 instances, Lambda functions).

内容的提问来源于stack exchange,提问作者Sake

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.30 05:24:11