如何安全地从aws_iam_policy_attachment升级到aws_iam_role_policy_attachment?

How to upgrade from aws_iam_policy_attachment to aws_iam_role_policy_attachment safely?

资源 aws_iam_policy_attachment 有以下警告

WARNING: The aws_iam_policy_attachment resource creates exclusive attachments of IAM policies. Across the entire AWS account, all of the users/roles/groups to which a single policy is attached must be declared by a single aws_iam_policy_attachment resource. This means that even any users/roles/groups that have the attached policy via any other mechanism (including other Terraform resources) will have that attached policy revoked by this resource. Consider aws_iam_role_policy_attachment, aws_iam_user_policy_attachment, or aws_iam_group_policy_attachment instead. These resources do not enforce exclusive attachment of an IAM policy.

我们更改了一些代码

resource "aws_iam_policy_attachment" "logs" {
  name       = "${var.function_name}-logs"
  roles      = [aws_iam_role.lambda.name]
  policy_arn = aws_iam_policy.logs[0].arn
}

resource "aws_iam_role_policy_attachment" "logs" {
  name       = "${var.function_name}-logs"
  role       = aws_iam_role.lambda.name
  policy_arn = aws_iam_policy.logs[0].arn
}

上面的更改很简单,但现在 terraform 想要删除 aws_iam_policy_attachment 资源并添加 aws_iam_role_policy_attachment。以前,当我们使用共享托管 IAM 资源为模块应用 terraform 时,它会从 30 个不同的 IAM 角色中分离策略,迫使我们通过查找和重新应用我们的 terraform 模块来重新附加它们。

使用危险性较低的资源的安全策略是什么 aws_iam_role_policy_attachment

我们目前的策略

  1. 重新创建托管 IAM 策略作为内联策略并添加到角色

  2. 使用 AWS 控制台手动删除托管策略

    • 使用此 CLI 命令可能更容易。它只是出现在控制台中。

      aws iam detach-role-policy \
        --role-name my-role-name \
        --policy-arn arn:aws:iam:1234567890:role/logs
      
  3. 从状态中删除坏资源

    • 可能没有必要,因为它已在上一步中删除
    • terraform state rm aws_iam_policy_attachment.logs
  4. 目标应用新附件

    • target apply -target aws_iam_role_policy_attachment.logs
  5. 完整性检查

    • terraform plan
  6. 从第一步中删除内联策略

状态操作注意事项

每当我要进行状态手术时,我都会将状态更改为本地状态。做我所有的操作。然后 运行 一个确保我的更改没有引起差异的计划。然后将状态放回您的适当后端。这篇文章解释了如何做到这一点:

https://medium.com/faun/cleaning-up-a-terraform-state-file-the-right-way-ab509f6e47f3

但至少,至少要做到:terraform state pull > backup.tfstate

为您的任务陈述命令

首先,让 Terraform 停止跟踪您执行此操作的旧方法 terraform state rm aws_iam_policy_attachment.logs

然后只需导入新的关联资源即可:

terraform import aws_iam_role_policy_attachment.logs lambda-role/arn:aws:iam::xxxxxxxxxxxx:policy/policy-name

每个文档:https://registry.terraform.io/providers/hashicorp/aws/latest/docs/resources/iam_role_policy_attachment

做一个 terraform plan 你应该看不到差异。

结论

这允许您不触及您的实际 AWS 配置。你不会最终删除任何角色或权限,哪怕一分钟。如果您提前备份您的状态,它是安全且可验证的。