Skip to content

Instantly share code, notes, and snippets.

@ktutnik
Last active August 23, 2021 06:40
Show Gist options
  • Save ktutnik/dda806a803b935bf76962520362a2644 to your computer and use it in GitHub Desktop.
Save ktutnik/dda806a803b935bf76962520362a2644 to your computer and use it in GitHub Desktop.
Shell script to create static website hosting on AWS S3 + CloudFront
#!/bin/bash
set -e
REGION="ap-southeast-1"
if [ -z "$1" ]
then
echo "The bucket name is not specified"
exit 1
fi
echo '{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "PublicReadGetObject",
"Effect": "Allow",
"Principal": "*",
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::'$1'/*"
}
]
}' > /tmp/bucket_policy.json
echo 'Hello World!' > /tmp/index.html
aws s3api create-bucket \
--no-cli-pager \
--output text \
--bucket $1 \
--region $REGION \
--create-bucket-configuration LocationConstraint=$REGION \
--query "join('', ['Bucket Url: ', Location])"
aws s3api put-bucket-policy \
--no-cli-pager \
--bucket $1 \
--policy file:///tmp/bucket_policy.json \
aws s3 website s3://$1/ \
--no-cli-pager \
--index-document index.html \
--error-document index.html \
aws s3 cp /tmp/index.html s3://$1/index.html \
--quiet
aws cloudfront create-distribution \
--no-cli-pager \
--output text \
--origin-domain-name $1.s3.$REGION.amazonaws.com \
--default-root-object index.html \
--query "join('', ['CloudFront Url: ', 'https://', Distribution.DomainName])"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment