Skip to content

Instantly share code, notes, and snippets.

@darvell
Created April 30, 2017 16:08
Show Gist options
  • Save darvell/3b4244e0f79ef1e7e8ee3b702d853bef to your computer and use it in GitHub Desktop.
Save darvell/3b4244e0f79ef1e7e8ee3b702d853bef to your computer and use it in GitHub Desktop.
Command to deploy to folder to an S3 bucket and hook up that bucket to a CNAME on cloudflare.
@goto py2cmd
#!/usr/bin/env python
import os
import sys
import CloudFlare
import tldextract
import boto3
import mimetypes
mimetypes.init()
CLOUDFLARE_KEY = os.environ["CLOUDFLARE_KEY"]
CLOUDFLARE_EMAIL = os.environ["CLOUDFLARE_EMAIL"]
BUCKET_POLICY_TEMPLATE = """{{
"Version": "2008-10-17",
"Statement": [
{{
"Sid": "AllowPublicRead",
"Effect": "Allow",
"Principal": {{
"AWS": "*"
}},
"Action": "s3:GetObject",
"Resource": "arn:aws:s3:::{0}/*"
}}
]
}}"""
def main(fqdn, folder):
domain_info = tldextract.extract(fqdn)
cf = CloudFlare.CloudFlare(email=CLOUDFLARE_EMAIL, token=CLOUDFLARE_KEY)
s3 = boto3.client('s3')
cf_zones = cf.zones.get()
intended_zone = next(iter([x for x in cf_zones if x["name"] == "{0}.{1}".format(domain_info.domain, domain_info.suffix)]), None)
if not intended_zone:
raise Exception("Domain name is not part of Cloudflare account.")
bucket = next(iter([x for x in s3.list_buckets()["Buckets"] if x["Name"] == fqdn]), None)
if bucket:
print "Existing bucket found."
else:
print "Creating bucket {0}".format(fqdn)
s3.create_bucket(Bucket=fqdn, CreateBucketConfiguration={'LocationConstraint': 'us-west-2'})
website_configuration = {
'IndexDocument': {'Suffix': 'index.html'}
}
s3.put_bucket_website(Bucket=fqdn, WebsiteConfiguration=website_configuration)
s3.put_bucket_policy(Bucket=fqdn, Policy=BUCKET_POLICY_TEMPLATE.format(fqdn))
# Why oh why can't they just tell me.
bucket_location = s3.get_bucket_location(Bucket=fqdn)["LocationConstraint"]
bucket_domain = "{0}.s3-website-{1}.amazonaws.com".format(fqdn,bucket_location)
records = cf.zones.dns_records.get(intended_zone['id'])
cname_record = next(iter([x for x in records if x["name"] == fqdn]), None)
if cname_record:
print "CNAME record already exists. Moving on."
else:
cf.zones.dns_records.post(intended_zone["id"], data={"name": domain_info.subdomain, "type": "CNAME", "content":bucket_domain, "proxied": True })
print "Added {0} CNAME to {1}.{2}".format(domain_info.subdomain, domain_info.domain, domain_info.suffix)
full_path = os.path.abspath(folder)
for root, dirs, files in os.walk(full_path):
for file in files:
local_file = "{0}\\{1}".format(root, file)
print "Uploading: {0}".format(local_file)
target = root[len(full_path) + 1:].replace("\\", "/")
if len(target) == 0:
target = file
else:
target = target + "/" + file
s3.upload_file(local_file, fqdn, target, ExtraArgs={'ContentType': mimetypes.types_map.get("." + target.split('.')[-1], "binary/octet-stream")})
if "__main__" in __name__:
main(sys.argv[1], sys.argv[2])
''':
:py2cmd
@python -x -B "%~f0" %*
@if NOT "%COMSPEC%" == "%SystemRoot%\system32\cmd.exe" goto endofscript
@if %errorlevel% == 9009 echo You do not have Python in your PATH.
@if errorlevel 1 goto script_failed_so_exit_with_non_zero_val 2>nul
:endofscript
:'''
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment