-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathwebotron.py
126 lines (96 loc) · 2.8 KB
/
webotron.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""Webotron: Deploy websites with aws.
Webotron automates the process of deploying static websites
-Configure AWS S3 buckets
- Create them
- Set them up for static website hosting
- Deploy local files to them
- Configure DNS with Route 53
- COnfigure a Content Delivery Network and SSL with AWS Cloudfront
"""
from pathlib import Path
import mimetypes
import boto3
from botocore.exceptions import ClientError
import click
session = boto3.Session(profile_name='pythonAutomation')
s3 = session.resource('s3')
@click.group()
def cli():
"""Webotron deploys websites to AWS."""
pass
@cli.command('list-buckets')
def list_buckets():
"""List all s3 buckets."""
for bucket in s3.buckets.all():
print(bucket)
@cli.command('list-bucket-objects')
@click.argument('bucket')
def list_bucket_objects(bucket):
"""List objects in an s3 bucket."""
for obj in s3.Bucket(bucket).objects.all():
print(obj)
@cli.command('Setup-bucket')
@click.argument('bucket')
def setup_bucket(bucket):
"""Create and configure S3 bucket."""
s3_bucket = None
try:
s3_bucket = s3.create_bucket(
Bucket=bucket,
CreateBucketConfiguration={'LocationConstraint': session.region_name})
except ClientError as error:
if error.response['Error']['Code'] == 'BucketAlreadyOwnedByYou':
s3_bucket = s3.Bucket(bucket)
else:
raise error
policy= """
{
"Version":"2012-10-17",
"Statement":[{
"Sid":"PublicReadGetObject",
"Effect":"Allow",
"Principal": "*",
"Action":["s3:GetObject"],
"Resource":["arn:aws:s3:::%s/*"
]
}
]
}
""" % s3_bucket.name
policy =policy.strip()
pol = s3_bucket.Policy()
pol.put(Policy=policy)
s3_bucket.Website().put(WebsiteConfiguration=
{'ErrorDocument':{
'Key': 'error.html'
},
'IndexDocument': {
'Suffix': 'index.html'
}
})
return
def upload_file(s3_bucket, path, key):
"""Upload path to s3_bucket at key."""
content_type = mimetypes.guess_type(key)[0] or 'text/plain'
s3_bucket.upload_file(
path,
key,
ExtraArgs={'ContentType': content_type})
@cli.command('Sync')
@click.argument('pathname', type=click.Path(exists=True))
@click.argument('bucket')
def sync(pathname, bucket):
"""Sync contents of PATHNAME to BUCKET."""
s3_bucket = s3.Bucket(bucket)
root = Path(pathname).expanduser().resolve()
def handle_directory(target):
for p in target.iterdir():
if p.is_dir():\
handle_directory(p)
if p.is_file(): upload_file\
(s3_bucket, str(p), str(p.relative_to(root)))
handle_directory(root)
if __name__== '__main__':
cli()