Error: Error putting S3 policy: MalformedPolicy: Invalid policy syntax. │ status code: 400, request id: 9X3877V8AR2EVQ99

I am able to create the s3 bucket successfully. But when I try to provision the s3 bucket policy it throws error.

  required_version = "> 0.14.4" # which means any version equal & above 0.14 like 0.15, 0.16 etc and < 1.xx
  #Provider requirements
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 3.0"
    }
  }
resource "aws_s3_bucket" "client_host_bucket" {
  bucket = "bucket-demo"
  acl    = "private"

  versioning {
    enabled = true
  }
  website {
    index_document = "index.html"
  }

}
resource "aws_s3_bucket_policy" "bucket_policy" {

  bucket = aws_s3_bucket.client_host_bucket.id

  policy = jsonencode({
    Version = "2012-10-17"
    Id      = "MYBUCKETPOLICY"
    Statement = [
      {

        Effect    = "Allow"
        Principal = "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E1DH5IWVP378YX"
        Action    = "s3:GetObject"
        Resource = [
          "arn:aws:s3:::dsdsdd-host-bucket/*"
        ]

      },
    ]
  })

}

Hiya, see if this works for you -

resource "aws_s3_bucket_policy" "bucket_policy" {

  bucket = aws_s3_bucket.client_host_bucket.id

  policy = jsonencode({
    "Version": "2012-10-17",
    "Id": "MYBUCKETPOLICY",
    "Statement": [
      {
        "Effect": "Allow",
        "Principal": {
           "AWS": "arn:aws:iam::cloudfront:user/CloudFront Origin Access Identity E1DH5IWVP378YX"
},
        "Action": "s3:GetObject",
        "Resource": 
          "arn:aws:s3:::dsdsdd-host-bucket/*"
      }
    ]
  })

}

You were using the incorrect assignment operator (=) instead of (:slight_smile: and your fields were not enclosed with ("").
I don’t have time to test this at the moment, so forgive me if I’ve made some mistakes, but you get the idea.

Hope this helps!