Terraform - 将策略附加到 s3 存储桶 [英] Terraform - attach policy to s3 bucket
问题描述
我创建了一篇较早的帖子来解决在不尝试复制代码的情况下创建多个 s3 存储桶的问题.效果很好!
I created an earlier post to resolve an issue for creating multiple s3 buckets without trying to duplicate code. It worked well!
aws_iam_policy 如下所示:
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}"
}
不幸的是,附加 IAM 用户策略会给我一个错误,因为它必须遍历索引:
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'
推荐答案
我不认为你可以像这样在策略中内联变量.相反,您需要创建一个 template_file,并提供结果从模板到政策.
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
然后,您需要再次使用 count
将每个策略附加到 aws_iam_user.user.name
.像这样
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)}"
}
这篇关于Terraform - 将策略附加到 s3 存储桶的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!