Skip to content

Instantly share code, notes, and snippets.

@jjtroberts
Created October 12, 2022 22:00
Show Gist options
  • Save jjtroberts/4cc15171bb3559332f2fce731d90e550 to your computer and use it in GitHub Desktop.
Save jjtroberts/4cc15171bb3559332f2fce731d90e550 to your computer and use it in GitHub Desktop.
Bash script to generate an S3 redirect and R53 alias
#!/usr/bin/env bash
function makeBucket() {
echo "Making S3 bucket for ${DOMAIN}..."
aws s3 mb s3://${DOMAIN}
}
# Trim any erroneous whitespace from variable
DOMAIN="${DOMAIN//[[:space:]]/}"
# Create s3.json
cat <<EOF >> s3.json
{
"RedirectAllRequestsTo": {
"HostName": "www.${DOMAIN}"
}
}
EOF
# Test for s3 bucket existence
bucket_exists=$(aws s3 ls | grep -w ${DOMAIN} -c)
if [ $bucket_exists ne 0 ]; then
makeBucket
fi
# Configure the bucket to redirect all traffic to www.hostname
aws s3api put-bucket-website --bucket ${DOMAIN} --website-configuration file://s3.json
# Create the Route53 Hosted Zone
R53OP=$(aws route53 create-hosted-zone --name ${DOMAIN} --caller-reference gd-jenkins-$(date +%Y%m%dT%H%M%S) --hosted-zone-config Comment="${COMMENT}")
# Grab the new hosted zone id
HZ=$(echo $R53OP | grep -Eio '(hostedzone/([^"]*))' | head -1 | sed 's/hostedzone\///g')
sleep 4
# Add CNAME and ALIAS records
cat <<EOF >> r53batch.json
{
"Comment": "Add CNAME and ALIAS",
"Changes": [{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "${DOMAIN}",
"Type": "A",
"AliasTarget": {
"HostedZoneId": "Z3BJ6K6RIION7M",
"DNSName": "s3-website-us-west-2.amazonaws.com",
"EvaluateTargetHealth": false
}
}
},
{
"Action": "CREATE",
"ResourceRecordSet": {
"Name": "www.${DOMAIN}",
"Type": "CNAME",
"TTL": 300,
"ResourceRecords": [{
"Value": "unbouncepages.com"
}]
}
}
]
}
EOF
aws route53 change-resource-record-sets --hosted-zone-id ${HZ} --change-batch file://r53batch.json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment