forked from bemer/aws-serverless-workshops
-
Notifications
You must be signed in to change notification settings - Fork 0
/
webapp-static-hosting.yaml
186 lines (163 loc) · 5.85 KB
/
webapp-static-hosting.yaml
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
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
---
AWSTemplateFormatVersion: "2010-09-09"
Description:
Creates a static website using S3 for the Wild Rydes serverless web application workshop
Parameters:
BucketName:
Type: String
Description: The name for the bucket hosting your website, e.g. 'wildrydes-yourname'
AllowedPattern: ^[a-z0-9][a-z0-9-.]{1,61}[a-z0-9]$
CodeBucket:
Type: String
Default: wildrydes-us-east-1
Description: S3 bucket containing the code deployed by this template
AllowedPattern: ^[a-z0-9][a-z0-9-.]{1,61}[a-z0-9]$
CodeKeyPrefix:
Type: String
Default: WebApplication/1_StaticWebHosting
Description: Key prefix for resources referenced from the CodeBucket
Metadata:
AWS::CloudFormation::Interface:
ParameterGroups:
-
Label:
default: "Website Configuration"
Parameters:
- BucketName
-
Label:
default: "Advanced Configuration"
Parameters:
- CodeBucket
- CodeKeyPrefix
ParameterLabels:
BucketName:
default: "Website Bucket Name"
Resources:
WebsiteBucket:
Properties:
BucketName: !Ref BucketName
WebsiteConfiguration:
IndexDocument: index.html
Type: "AWS::S3::Bucket"
WebsiteBucketPolicy:
Properties:
Bucket: !Ref WebsiteBucket
PolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Principal: "*"
Action: s3:GetObject
Resource: !Sub "arn:aws:s3:::${WebsiteBucket}/*"
Type: "AWS::S3::BucketPolicy"
WebsiteContent:
Properties:
ServiceToken: !GetAtt CopyS3ObjectsFunction.Arn
SourceBucket: !Ref CodeBucket
SourcePrefix: !Sub "${CodeKeyPrefix}/website/"
Bucket: !Ref WebsiteBucket
Type: "Custom::S3Objects"
S3CopyRole:
Type: AWS::IAM::Role
Properties:
Path: /wildrydes/
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
-
Effect: Allow
Principal:
Service: lambda.amazonaws.com
Action: sts:AssumeRole
Policies:
-
PolicyName: S3Access
PolicyDocument:
Version: 2012-10-17
Statement:
-
Sid: AllowLogging
Effect: Allow
Action:
- "logs:CreateLogGroup"
- "logs:CreateLogStream"
- "logs:PutLogEvents"
Resource: "*"
-
Sid: SourceBucketReadAccess
Effect: Allow
Action:
- "s3:ListBucket"
- "s3:GetObject"
Resource:
- !Sub "arn:aws:s3:::${CodeBucket}"
- !Sub "arn:aws:s3:::${CodeBucket}/${CodeKeyPrefix}/*"
-
Sid: DestBucketWriteAccess
Effect: Allow
Action:
- "s3:ListBucket"
- "s3:GetObject"
- "s3:PutObject"
- "s3:PutObjectAcl"
- "s3:PutObjectVersionAcl"
- "s3:DeleteObject"
- "s3:DeleteObjectVersion"
Resource:
- !Sub "arn:aws:s3:::${WebsiteBucket}"
- !Sub "arn:aws:s3:::${WebsiteBucket}/*"
CopyS3ObjectsFunction:
Properties:
Description: Copies objects from a source S3 bucket to a destination
Handler: index.handler
Runtime: python2.7
Role: !GetAtt S3CopyRole.Arn
Timeout: 120
Code:
ZipFile: |
import os
import json
import cfnresponse
import boto3
from botocore.exceptions import ClientError
client = boto3.client('s3')
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def handler(event, context):
logger.info("Received event: %s" % json.dumps(event))
source_bucket = event['ResourceProperties']['SourceBucket']
source_prefix = event['ResourceProperties'].get('SourcePrefix') or ''
bucket = event['ResourceProperties']['Bucket']
prefix = event['ResourceProperties'].get('Prefix') or ''
result = cfnresponse.SUCCESS
try:
if event['RequestType'] == 'Create' or event['RequestType'] == 'Update':
result = copy_objects(source_bucket, source_prefix, bucket, prefix)
elif event['RequestType'] == 'Delete':
result = delete_objects(bucket, prefix)
except ClientError as e:
logger.error('Error: %s', e)
result = cfnresponse.FAILED
cfnresponse.send(event, context, result, {})
def copy_objects(source_bucket, source_prefix, bucket, prefix):
paginator = client.get_paginator('list_objects_v2')
page_iterator = paginator.paginate(Bucket=source_bucket, Prefix=source_prefix)
for key in {x['Key'] for page in page_iterator for x in page['Contents']}:
dest_key = os.path.join(prefix, os.path.relpath(key, source_prefix))
if not key.endswith('/'):
print 'copy {} to {}'.format(key, dest_key)
client.copy_object(CopySource={'Bucket': source_bucket, 'Key': key}, Bucket=bucket, Key = dest_key)
return cfnresponse.SUCCESS
def delete_objects(bucket, prefix):
paginator = client.get_paginator('list_objects_v2')
page_iterator = paginator.paginate(Bucket=bucket, Prefix=prefix)
objects = [{'Key': x['Key']} for page in page_iterator for x in page['Contents']]
client.delete_objects(Bucket=bucket, Delete={'Objects': objects})
return cfnresponse.SUCCESS
Type: AWS::Lambda::Function
Outputs:
WebsiteURL:
Value: !GetAtt WebsiteBucket.WebsiteURL