I am trying to set up an S3 bucket policy in Terraform. I have written the following code in a module. The goal is to conditionally create the S3 bucket and the policy. The S3 bucket created just fine. However, I get this error for the aws_s3_bucket_policy. What am I doing wrong? Thanks!
resource "aws_s3_bucket" "bucket" {
bucket = var.bucket
bucket_prefix = var.bucket_prefix
acl = "log-delivery-write"
count = var.account != "" ? 1 : 0
server_side_encryption_configuration {
rule {
apply_server_side_encryption_by_default {
sse_algorithm = "AES256"
}
}
}
tags = {
account = var.account
}
}
resource "aws_s3_bucket_policy" "bucket" {
bucket = "${aws_s3_bucket.bucket[0].id}"
count = var.account != "" ? 1 : 0
policy = jsonencode(
{
"Id" : "SSLPolicy",
"Version" : "2012-10-17",
"Statement" : [
{
"Sid" : "AllowSSLRequestsOnly",
"Action" : "s3:*",
"Effect" : "Deny",
"Resource" : [
"${aws_s3_bucket.bucket[*].arn}",
"${aws_s3_bucket.bucket[0].arn}/*",
],
"Condition" : {
"Bool" : {
"aws:SecureTransport" : "false"
}
},
"Principal" : "*"
}
]
}
)
}
Error: Error putting S3 policy: MalformedPolicy: Invalid policy syntax.
│ status code: 400, request id: BN6FRWX8A6723GAP, host id: t3yhr16yMu7VOjLIdXup1O0SlDW062VLiYJXyZ5bR6+OwrP86wjzBe7iGNzIDzCqcB1H1WUn8Pk=
│
│ with module.test.aws_s3_bucket_policy.bucket[0],
│ on .terraform/modules/test/main.tf line 20, in resource "aws_s3_bucket_policy" "bucket":
│ 20: resource "aws_s3_bucket_policy" "bucket" {
│
The aws_s3_bucket.bucket[*].arn
returns a list of arn values, not the actual arn. Thus it should be:
resource "aws_s3_bucket_policy" "bucket" {
bucket = "${aws_s3_bucket.bucket[0].id}"
count = var.account != "" ? 1 : 0
policy = jsonencode(
{
"Id" : "SSLPolicy",
"Version" : "2012-10-17",
"Statement" : [
{
"Sid" : "AllowSSLRequestsOnly",
"Action" : "s3:*",
"Effect" : "Deny",
"Resource" : [
"${aws_s3_bucket.bucket[0].arn}",
"${aws_s3_bucket.bucket[0].arn}/*",
],
"Condition" : {
"Bool" : {
"aws:SecureTransport" : "false"
}
},
"Principal" : "*"
}
]
}
)
}