Terraform-将策略附加到S3存储桶

时间:2018-12-13 21:16:00

标签: amazon-web-services amazon-s3 terraform

我创建了较早的文章,以解决创建多个s3存储桶而无需尝试重​​复代码的问题。效果很好!

Terraform - creating multiple buckets

aws_iam_policy看起来像这样:

resource "aws_iam_policy" "user_policy" {
  count         = "${length(var.s3_bucket_name)}"
  name          = "UserPolicy"

policy                    = <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"s3:PutObject",
"s3:GetObject",
"s3:DeleteObject",
"s3:ListBucket",
"s3:GetLifecycleConfiguration",
"s3:PutLifecycleConfiguration",
"s3:PutObjectTagging",
"s3:GetObjectTagging",
"s3:DeleteObjectTagging"
],
"Resource": [
"arn:aws:s3:::${var.s3_bucket_name[count.index]}",
"arn:aws:s3:::${var.s3_bucket_name[count.index]}/*"
]
}
]
}
EOF
}

这是我附加政策的方式:

resource "aws_iam_user_policy_attachment" "user_policy_attach" {
    user       = "${aws_iam_user.user.name}"
    policy_arn = "${aws_iam_policy.user_policy.arn}"
}

不幸的是,附加IAM用户策略给我一个错误,因为它必须遍历索引:

Resource 'aws_iam_policy.user_policy' not found for variable 'aws_iam_policy.user_policy.arn'

1 个答案:

答案 0 :(得分:-1)

我认为您不能像这样在策略内联变量。相反,您需要创建一个template_file,并将模板结果传递到策略中。

这将为每个存储段创建一个策略(名称来自上一个问题)

  • UserPolicy-prod_bucket
  • UserPolicy-stage-bucket
  • UserPolicy-qa-bucket

然后,您需要再次使用aws_iam_user.user.name将每个策略附加到count。像这样

data "template_file" "policy" {
  count = "${length(var.s3_bucket_name)}"

  template = <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:PutObject",
        "s3:GetObject",
        "s3:DeleteObject",
        "s3:ListBucket",
        "s3:GetLifecycleConfiguration",
        "s3:PutLifecycleConfiguration",
        "s3:PutObjectTagging", "s3:GetObjectTagging", "s3:DeleteObjectTagging" ],
      "Resource": [
        "arn:aws:s3:::$${bucket}",
        "arn:aws:s3:::$${bucket}/*"
      ]
    }
  ]
}
EOF

  vars {
    bucket = "${var.s3_bucket_name[count.index]}"
  }
}

resource "aws_iam_policy" "user_policy" {
  count = "${length(var.s3_bucket_name)}"
  name  = "UserPolicy-${element(var.s3_bucket_name, count.index)}"

  policy = "${element(data.template_file.policy.*.rendered, count.index)}"
}

resource "aws_iam_user_policy_attachment" "user_policy_attach" {
  count      = "${length(var.s3_bucket_name)}"
  user       = "${aws_iam_user.user.name}"
  policy_arn = "${element(aws_iam_policy.user_policy.*.arn, count.index)}"
}