Notification texts go here Contact Us Buy Now!

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

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:

  • The Action field should be singular (Action instead of Actions), even when providing a list of actions.
  • The redundant * 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.

    Post a Comment

    Cookie Consent
    We serve cookies on this site to analyze traffic, remember your preferences, and optimize your experience.
    Oops!
    It seems there is something wrong with your internet connection. Please connect to the internet and start browsing again.
    AdBlock Detected!
    We have detected that you are using adblocking plugin in your browser.
    The revenue we earn by the advertisements is used to manage this website, we request you to whitelist our website in your adblocking plugin.
    Site is Blocked
    Sorry! This site is not available in your country.