Encountering the "api error MalformedPolicy: Invalid policy syntax" error while provisioning an S3 bucket policy can be frustrating, but with a few adjustments, you can rectify this issue.
Typically, the error stems from an incorrect formatting of the Principal
field within your policy. To resolve this, ensure that you define the Principal
as a block that specifies the AWS Service
as its value.
Here's an example of how to define the Principal
field correctly:
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}/*"
}
]
})
}
Within the Principal
block, you've correctly specified the Service
value as cloudfront.amazonaws.com
, which allows CloudFront to access your S3 bucket.
Additionally, you've removed the redundant second *
from the Resource
field, ensuring that the policy applies to all objects within your bucket.
With these adjustments, you should be able to create the S3 bucket policy without encountering the "api error MalformedPolicy: Invalid policy syntax" error.