Search code examples
amazon-web-servicesterraformterraform-provider-aws

Issue provisioning bucket policy error: api error MalformedPolicy: Invalid policy syntax


this is my terraform code. Im provisioning bucket s3 and a policy to attach it.

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 = "cloudfront.amazonaws.com"
          Actions    = ["s3:GetObject", "s3:PutObject"]
          Resource  = "${aws_s3_bucket.bucket.arn}/**"
        }
      ]
   })
}

this is the error stack

api error MalformedPolicy:│ with aws_s3_bucket_policy.bucket_policy, │ on s3.tf line 32, in resource "aws_s3_bucket_policy" "bucket_policy": │ 32: resource "aws_s3_bucket_policy" "bucket_policy" {


Solution

  • I believe your error comes from your principal field, which should be a block that specifies that your value is an AWS Service:

    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}/*"
            }
          ]
       })
    }
    

    I have also removed the second *; as @Helder Sepulveda points out, it is redundant.


    As @Dave Ankin pointed out, Actions needs to be Action — even when providing a list of actions.