如何将现有的S3桶策略转换为Terraform管理的策略

43次阅读
没有评论

问题描述

拥有一个由手动维护的大型S3桶策略,并希望将其迁移到CI/terraform中(用于策略维护),但不希望TF管理桶本身。用户想知道是否有办法让TF“导入”现有的大型策略并为其生成TF文件。

解决方案

请注意以下操作注意版本差异及修改前做好备份。
用户已有一个现有的S3桶和策略,我们可以通过以下步骤将其导入Terraform状态并在Terraform中管理策略。

  1. 首先,使用以下命令将策略导入Terraform状态:
$ terraform import aws_s3_bucket_policy.allow_access_from_another_account my-s3-bucket-name

其中,aws_s3_bucket_policy.allow_access_from_another_account 是Terraform的资源标识符,my-s3-bucket-name 是现有的S3桶的名称。

  1. 接下来,在你的 main.tf 文件中添加以下代码来确保Terraform中的策略与状态匹配,并在计划中显示是否与状态匹配:
resource "aws_s3_bucket_policy" "allow_access_from_another_account" {
  bucket = "enter the bucket ID from the portal"
  policy = data.aws_iam_policy_document.allow_access_from_another_account.json
}

data "aws_iam_policy_document" "allow_access_from_another_account" {
  statement {
    principals {
      type        = "AWS"
      identifiers = ["123456789012"]
    }
    actions = [
      "s3:GetObject",
      "s3:ListBucket",
    ]
    resources = [
      "arn for aws bucket",
    ]
}

请将 bucket = "enter the bucket ID from the portal" 中的 enter the bucket ID from the portal 替换为实际的S3桶ID。

这样,你就可以在Terraform中管理现有的S3桶策略。Terraform会确保策略状态与计划一致,以便在更新或应用时保持一致性。

用户还提到了一种使用CLI命令的方法,这是一个从CI中快速实现的方法,但不如Terraform管理灵活。你可以使用以下CLI命令来上传策略:

aws s3api put-bucket-policy --bucket <bucket> --policy file://<local-file>.json

通过上述步骤,你可以将现有的S3桶策略导入到Terraform中并在Terraform中进行管理,确保策略的一致性和可维护性。

正文完