Skip to content

Commit

Permalink
Update cloudformation template to use new aws s3 access policy
Browse files Browse the repository at this point in the history
  • Loading branch information
appsol committed May 12, 2023
1 parent 44e617b commit b8a04cf
Showing 1 changed file with 51 additions and 7 deletions.
58 changes: 51 additions & 7 deletions aws/cloudformation.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
# ==================================================
# This stack creates the API infrastructure.
# ==================================================
from troposphere import Template, Parameter, Ref, GetAtt, Join, Output
from troposphere.s3 import Bucket, OwnershipControls, OwnershipControlsRule, PublicAccessBlockConfiguration
from troposphere import Template, Parameter, Ref, GetAtt, Join, Sub, Output
from troposphere.s3 import Bucket, BucketPolicy, OwnershipControls, OwnershipControlsRule, PublicAccessBlockConfiguration
import troposphere.iam as iam
import troposphere.cloudfront as cloudfront
import uuid
Expand Down Expand Up @@ -71,19 +71,56 @@
'Bucket',
BucketName=bucket_name_variable,
PublicAccessBlockConfiguration=PublicAccessBlockConfiguration(
BlockPublicAcls=False,
BlockPublicPolicy=False,
IgnorePublicAcls=False,
RestrictPublicBuckets=False
BlockPublicAcls=True,
BlockPublicPolicy=True,
IgnorePublicAcls=True,
RestrictPublicBuckets=True
),
OwnershipControls=OwnershipControls(
Rules=[
OwnershipControlsRule(
ObjectOwnership="BucketOwnerPreferred"
)
]
),
)
)

cloudfront_oai = template.add_resource(
cloudfront.CloudFrontOriginAccessIdentity(
'CloudFrontOAI',
CloudFrontOriginAccessIdentityConfig=cloudfront.CloudFrontOriginAccessIdentityConfig(
Comment=Sub("Cloudfront OAI for ${Cname}")
)
)
)

bucket_policy = template.add_resource(
BucketPolicy(
'PublicBucketPolicy',
Bucket=Ref(bucket_resource),
PolicyDocument={
"Version": "2012-10-17",
"Statement": [
{
"Action": [
"s3:GetObject"
],
"Effect": "Allow",
"Resource": [
Join("", [
"arn:aws:s3:::",
Ref(bucket_resource),
"/*"
]
)
],
"Principal": {
'CanonicalUser': GetAtt(cloudfront_oai, 'S3CanonicalUserId')
}
}
]
}
)
)

Expand Down Expand Up @@ -111,6 +148,11 @@
ErrorCode=404,
ResponseCode=200,
ResponsePagePath='/index.html'
),
cloudfront.CustomErrorResponse(
ErrorCode=403,
ResponseCode=200,
ResponsePagePath='/index.html'
)
],
DefaultCacheBehavior=cloudfront.DefaultCacheBehavior(
Expand All @@ -127,7 +169,9 @@
cloudfront.Origin(
DomainName=GetAtt(bucket_resource, 'DomainName'),
Id=Join('-', ['S3', Ref(bucket_resource)]),
S3OriginConfig=cloudfront.S3OriginConfig()
S3OriginConfig=cloudfront.S3OriginConfig(
OriginAccessIdentity=Join('', ['origin-access-identity/cloudfront/', Ref(cloudfront_oai)])
)
)
],
ViewerCertificate=cloudfront.ViewerCertificate(
Expand Down

0 comments on commit b8a04cf

Please sign in to comment.