99 lines
2.7 KiB
Python
99 lines
2.7 KiB
Python
"""An AWS Python Pulumi program"""
|
|
|
|
import mimetypes
|
|
import os
|
|
import pulumi
|
|
import pulumi_aws as aws
|
|
|
|
project = pulumi.get_project()
|
|
stack = pulumi.get_stack()
|
|
prefix = f"{project}-{stack}"
|
|
|
|
TAGS = {
|
|
"project": project,
|
|
"env": stack,
|
|
}
|
|
|
|
bucket = aws.s3.Bucket(
|
|
f"{prefix}-site-bucket",
|
|
tags = TAGS,
|
|
website = aws.s3.BucketWebsiteArgs(
|
|
index_document = "index.html"
|
|
),
|
|
)
|
|
|
|
oai = aws.cloudfront.OriginAccessIdentity(
|
|
f"{prefix}-oai",
|
|
)
|
|
|
|
bucket_policy = aws.s3.BucketPolicy(
|
|
f"{prefix}-site-bucket-policy",
|
|
bucket = bucket.id,
|
|
policy = pulumi.Output.all(oai.iam_arn, bucket.id).apply(lambda args: f"""{{
|
|
"Version": "2012-10-17",
|
|
"Statement": [
|
|
{{
|
|
"Effect": "Allow",
|
|
"Principal": {{
|
|
"AWS": "{args[0]}"
|
|
}},
|
|
"Action": "s3:GetObject",
|
|
"Resource": "arn:aws:s3:::{args[1]}/*"
|
|
}}
|
|
]
|
|
}}""")
|
|
)
|
|
|
|
cdn = aws.cloudfront.Distribution(
|
|
f"{prefix}-cdn-distribution",
|
|
tags = TAGS,
|
|
origins=[{
|
|
"domain_name": bucket.bucket_regional_domain_name,
|
|
"origin_id": bucket.arn,
|
|
"s3_origin_config": {
|
|
"origin_access_identity": oai.cloudfront_access_identity_path,
|
|
}
|
|
}],
|
|
enabled=True,
|
|
default_root_object="index.html",
|
|
default_cache_behavior=aws.cloudfront.DistributionDefaultCacheBehaviorArgs(
|
|
allowed_methods=["GET", "HEAD"],
|
|
cached_methods=["GET", "HEAD"],
|
|
target_origin_id=bucket.arn,
|
|
viewer_protocol_policy="redirect-to-https",
|
|
forwarded_values=aws.cloudfront.DistributionDefaultCacheBehaviorForwardedValuesArgs(
|
|
query_string=False,
|
|
cookies=aws.cloudfront.DistributionDefaultCacheBehaviorForwardedValuesCookiesArgs(
|
|
forward="none",
|
|
),
|
|
),
|
|
),
|
|
price_class="PriceClass_100",
|
|
restrictions=aws.cloudfront.DistributionRestrictionsArgs(
|
|
geo_restriction=aws.cloudfront.DistributionRestrictionsGeoRestrictionArgs(
|
|
restriction_type="none",
|
|
),
|
|
),
|
|
viewer_certificate=aws.cloudfront.DistributionViewerCertificateArgs(
|
|
cloudfront_default_certificate=True,
|
|
),
|
|
)
|
|
|
|
def upload_directory(directory_path, bucket_name):
|
|
for root, dirs, files in os.walk(directory_path):
|
|
for file in files:
|
|
file_path = os.path.join(root, file)
|
|
relative_path = os.path.relpath(file_path, directory_path)
|
|
content_type, _ = mimetypes.guess_type(file_path)
|
|
aws.s3.BucketObject(
|
|
relative_path,
|
|
bucket=bucket_name,
|
|
source=pulumi.FileAsset(file_path),
|
|
content_type=content_type or "application/octet-stream",
|
|
key=relative_path,
|
|
)
|
|
upload_directory("./www", bucket.id)
|
|
|
|
pulumi.export("bucketName", bucket.bucket)
|
|
pulumi.export("cloudFrontDomain", cdn.domain_name)
|