AWS Cloudformation Error: Policy has invalid resource

I need to create an S3 bucket with public access, but restrict that access to only a specific IP.
I generated a policy using the policy generator for S3 buckets and then adapted it to my template by referencing the name of the bucket; however, CloudFormation keeps giving a "Policy has invalid resource" error.

Below is the relevant portion of the CloudFormation template I am using. "FirstS3BucketName" is the a parameter.

FirstS3BucketPolicy:
    Type: AWS::S3::BucketPolicy
    Properties: 
      Bucket: !Ref FirstS3BucketName
      PolicyDocument: |
                    {
                      "Id": "Policy1581542658034",
                      "Version": "2012-10-17",
                      "Statement": [
                        {
                          "Sid": "Stmt1581542655517",
                          "Action": "s3:*",
                          "Effect": "Allow",
                          "Resource": "arn:aws:s3:::${FirstS3BucketName}/*",
                          "Condition": {
                            "IpAddress": {
                              "aws:SourceIp": "3.132.69.181/32"
                            }
                          },
                          "Principal": "*"
                        }
                      ]
                    }

1 answer

  • answered 2020-02-12 23:01 Jason Wadsworth

    All you really need to do is add a !Sub on your PolicyDocument line. FYI, all that JSON can be turned into YAML as well.

    FirstS3BucketPolicy:
        Type: AWS::S3::BucketPolicy
        Properties: 
          Bucket: !Ref FirstS3BucketName
          PolicyDocument: !Sub |
                        {
                          "Id": "Policy1581542658034",
                          "Version": "2012-10-17",
                          "Statement": [
                            {
                              "Sid": "Stmt1581542655517",
                              "Action": "s3:*",
                              "Effect": "Allow",
                              "Resource": "arn:aws:s3:::${FirstS3BucketName}/*",
                              "Condition": {
                                "IpAddress": {
                                  "aws:SourceIp": "3.132.69.181/32"
                                }
                              },
                              "Principal": "*"
                            }
                          ]
                        }