Terraform - attach policy to s3 bucket

不想你离开。 提交于 2019-12-12 06:39:33

问题


I created an earlier post to resolve an issue for creating multiple s3 buckets without trying to duplicate code. It worked well!

Terraform - creating multiple buckets

The aws_iam_policy looks like so:

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
}

Here's how I'm attaching the policy:

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

Unfortunately attaching a IAM user policy gives me an error since it has to iterate over the index:

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

回答1:


I don't think you can inline variables inside the policy like that. Instead you need to create a template_file, and feed the result of the template through to the policy.

This will create a policy for each bucket (names taken from the previous question)

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

You then need to attach each of the policies to the aws_iam_user.user.name by using count again. Like so

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)}"
}


来源:https://stackoverflow.com/questions/53770191/terraform-attach-policy-to-s3-bucket

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!