Facing the issue of "api error MalformedPolicy: Invalid policy syntax" while setting up a bucket policy in your Terraform configuration? Let's delve into the root cause and provide a comprehensive solution.
The error message suggests that there's an issue with the policy syntax. Specifically, the problem lies in the principal
field, where you've defined the AWS service that you want to grant access to.
resource "aws_s3_bucket_policy" "bucket_policy" {
bucket = aws_s3_bucket.bucket.id
policy = jsonencode({
Version = "2012-10-17"
Id = "AllowGetObjects"
Statement = [
{
Sid = "AllowPublic"
Effect = "Allow"
Principal = {
Service = "cloudfront.amazonaws.com"
}
Action = ["s3:GetObject", "s3:PutObject"]
Resource = "${aws_s3_bucket.bucket.arn}/*"
}
]
})
}
The principal
field should be a block that specifies the AWS service as the value. Here's the corrected code:
resource "aws_s3_bucket_policy" "bucket_policy" {
bucket = aws_s3_bucket.bucket.id
policy = jsonencode({
Version = "2012-10-17"
Id = "AllowGetObjects"
Statement = [
{
Sid = "AllowPublic"
Effect = "Allow"
Principal = {
Service = "cloudfront.amazonaws.com"
}
Action = "s3:GetObject"
Resource = "${aws_s3_bucket.bucket.arn}/*"
}
]
})
}
Additionally, make sure that you have the following points covered:
Action
field should be singular (Action
instead of Actions
), even when providing a list of actions.*
in the Resource
field has been removed.With these corrections in place, you should be able to successfully provision the bucket policy without encountering the "MalformedPolicy" error.