In the resources section, I’m creating an S3 bucket and I’m also creating the S3 bucket policy. In the bucket policy I need to specify the name of the created bucket. In straight CloudFormation this would be easy as I just do !Sub, paste the policy doc and use ${<my bucket resource logical id}.
In serverless I’m unable to do that as serverless uses ${} which is fine. However, I need to use the mappings section instead in Fn::Sub which all the docs call for using: MyBucket: !Ref <MyBucketLogicalResource>
. However serverless doesn’t support the shorthand since it gets converted to JSON under the hood.
At this point I’m not sure how to substitute the bucket name that’s getting created by CFN into this bucket policy, as I do not want to hard code a bucket name into this resource which would cause collisions.
CloudTrailBucket:
Type: AWS::S3::Bucket
CloudTrailBucketPolicy:
Type: "AWS::S3::BucketPolicy"
Properties:
Bucket:
Ref: CloudTrailBucket
PolicyDocument:
Fn::Sub:
- |
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AWSCloudTrailAclCheck20150319",
"Effect": "Allow",
"Principal": {
"Service": "cloudtrail.amazonaws.com"
},
"Action": "s3:GetBucketAcl",
"Resource": "arn:aws:s3:::${CloudTrailBucket}"
},
{
"Sid": "AWSCloudTrailWrite20150319",
"Effect": "Allow",
"Principal": {
"Service": "cloudtrail.amazonaws.com"
},
"Action": "s3:PutObject",
"Resource": "arn:aws:s3:::${CloudTrailBucket}/AWSLogs/*",
"Condition": {
"StringEquals": {
"s3:x-amz-acl": "bucket-owner-full-control"
}
}
}
]
}
- { CloudTrailBucket:
Ref: CloudTrailBucket }
Since I can’t use the shorthand syntax, the other option is to use the traditional Ref: which it doesn’t like here either.
I found this post from last year regarding this issue, but I’m not sure how he figured this out: Setting up S3 bucket policy