-
Notifications
You must be signed in to change notification settings - Fork 1
/
Amazon EC2 DynamoDB and Dockerized App
272 lines (266 loc) · 9.42 KB
/
Amazon EC2 DynamoDB and Dockerized App
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
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
Description:
This is a template that launches an EC2 instance and deploys a dockerized angular app
to a public EC2 instance. The EC2 instance is configured using files from
github repository here - https://github.com/linuxacademy/Content-AWS-Certified-Data-Analytics---Speciality
This template also sets up a DynamoDB table and populates it with some data.
Parameters:
LatestAmiId:
Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
Default: '/aws/service/ami-amazon-linux-latest/al2023-ami-minimal-kernel-default-x86_64'
Resources:
AccessKey:
Type: AWS::IAM::AccessKey
Properties:
UserName: cloud_user
LambdaRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: "/"
Policies:
- PolicyName: EC2AccessRole
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- ec2:*
Resource: "*"
- Effect: Allow
Action:
- logs:*
Resource: "*"
InitFunction:
Type: AWS::Lambda::Function
Properties:
Code:
ZipFile: |
import json
import boto3
import threading
import urllib3
SUCCESS = "SUCCESS"
FAILED = "FAILED"
http = urllib3.PoolManager()
def send(event, context, responseStatus, responseData, physicalResourceId=None, noEcho=False, reason=None):
responseUrl = event['ResponseURL']
print(responseUrl)
responseBody = {}
responseBody['Status'] = responseStatus
responseBody['Reason'] = reason or "See the details in CloudWatch Log Stream: {}".format(context.log_stream_name)
responseBody['PhysicalResourceId'] = physicalResourceId or context.log_stream_name
responseBody['StackId'] = event['StackId']
responseBody['RequestId'] = event['RequestId']
responseBody['LogicalResourceId'] = event['LogicalResourceId']
responseBody['NoEcho'] = noEcho
responseBody['Data'] = responseData
json_responseBody = json.dumps(responseBody)
print("Response body:\n" + json_responseBody)
headers = {
'content-type' : '',
'content-length' : str(len(json_responseBody))
}
try:
response = http.request('PUT',responseUrl,headers=headers,body=json_responseBody)
print("Status code: {}".format(str(response.status)))
except Exception as e:
print("send(..) failed executing requests.put(..): " + str(e))
def createDefault():
print("Creating default VPC")
ec2 = boto3.client('ec2')
response = ec2.create_default_vpc()
return response
def deleteDefault():
return ""
def timeout(event, context):
print('Timing out, sending failure response to CFN')
send(event, context, FAILED, {}, None)
def lambda_handler(event, context):
print(f'Received event: {json.dumps(event)}')
timer = threading.Timer((context.get_remaining_time_in_millis() / 1000.00) - 0.5, timeout, args=[event, context])
timer.start()
status = SUCCESS
responseData = {}
try:
if event['RequestType'] == 'Delete':
deleteDefault()
else:
response = createDefault()
print(response)
responseData['Data'] = response
except Exception as e:
print(e)
status = FAILED
finally:
timer.cancel()
send(event, context, status, responseData, None)
Handler: index.lambda_handler
Role: !GetAtt LambdaRole.Arn
Runtime: python3.9
Timeout: 60
InitializeVPC:
Type: Custom::InitFunction
Properties:
ServiceToken: !GetAtt InitFunction.Arn
LnDynamoDBUserTable:
Type: AWS::DynamoDB::Table
Properties:
AttributeDefinitions:
- AttributeName: user_id
AttributeType: S
KeySchema:
- AttributeName: user_id
KeyType: HASH
TableName: users-information
BillingMode: PAY_PER_REQUEST
LnLambdaExecutionAndDynamoRole:
Type: AWS::IAM::Role
DependsOn:
- LnDynamoDBUserTable
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service:
- lambda.amazonaws.com
Action:
- sts:AssumeRole
Path: "/"
Policies:
- PolicyName: root
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- logs:*
Resource: arn:aws:logs:*:*:*
- Effect: Allow
Action:
- dynamodb:PutItem
Resource: !GetAtt LnDynamoDBUserTable.Arn
LnPopulateDynamoDBTable:
Type: AWS::Lambda::Function
DependsOn:
- LnDynamoDBUserTable
- LnLambdaExecutionAndDynamoRole
Properties:
Code:
S3Bucket: 'das-c01-data-analytics-specialty'
S3Key: 'Lab_Joining_Enriching_Transforming_Streaming_Data_Amazon_Kinesis/create-users-dynamodb-lambda.zip'
Handler: index.handler
Runtime: nodejs18.x
Role: !GetAtt LnLambdaExecutionAndDynamoRole.Arn
Timeout: 60
LnPopulateDynamoDBTableInit:
Type: Custom::LnPopulateDynamoDBTable
Properties:
ServiceToken: !GetAtt LnPopulateDynamoDBTable.Arn
LnSecurityGroupWebserver:
Type: AWS::EC2::SecurityGroup
DependsOn:
- InitializeVPC
Properties:
GroupDescription: !Sub 'Security Group created with CF template for web servers.'
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: 0.0.0.0/0
Tags:
- Key: Name
Value: !Sub '${AWS::StackName}-kinesis-helper-webserver-sg'
- Key: Description
Value: !Sub 'Security Group created for kinesis web server with ${AWS::StackName}.'
LnCreateKinesisHelperServer:
Type: AWS::EC2::Instance
DependsOn:
- LnSecurityGroupWebserver
Properties:
InstanceType: 't3a.medium'
ImageId: !Ref LatestAmiId
Tags:
- Key: Name
Value: !Join [ '-', [!Sub '${AWS::StackName}', 'kinesis-helper-server'] ]
SecurityGroupIds:
- !Ref LnSecurityGroupWebserver
UserData:
Fn::Base64:
!Join [ "", [
"#!/bin/bash -xe\n",
"yum update -y\n",
"/bin/echo '%password%' | /bin/passwd cloud_user --stdin\n",
"/opt/aws/bin/cfn-init -v ", #use cfn-init to install packages in cloudformation init
!Sub "--stack ${AWS::StackName} ",
"--resource LnCreateKinesisHelperServer ",
"--configsets InstallAndConfigure ",
!Sub "--region ${AWS::Region}\n",
!Sub "/opt/aws/bin/cfn-signal -e $? ",
!Sub "--stack ${AWS::StackName} ",
"--resource LnCreateKinesisHelperServer ",
!Sub "--region ${AWS::Region}",
"\n"] ]
Metadata:
AWS::CloudFormation::Init:
configSets:
InstallAndConfigure:
- "install_docker"
- "start_docker"
- "install_git"
- "get_angular_app"
- "build_docker_image"
- "docker_run_app"
install_docker:
commands:
test:
command: amazon-linux-extras install docker
cwd: /home/ec2-user
start_docker:
commands:
test:
command: service docker start && usermod -a -G docker ec2-user
cwd: /home/ec2-user
install_git:
commands:
test:
command: yum install git -y
cwd: /home/ec2-user
get_angular_app:
commands:
test:
command: git clone https://github.com/ACloudGuru-Resources/Content-AWS-Certified-Data-Analytics---Speciality.git
cwd: /home/ec2-user
build_docker_image:
commands:
test:
command: docker image build -t ubuntu-angular .
cwd: /home/ec2-user/Content-AWS-Certified-Data-Analytics---Speciality/Lab_Joining_Enriching_Transforming_Streaming_Data_Amazon_Kinesis/dockerized-angular-app
docker_run_app:
commands:
test:
command: docker run -d -p 80:80 ubuntu-angular
cwd: /home/ec2-user/Content-AWS-Certified-Data-Analytics---Speciality/Lab_Joining_Enriching_Transforming_Streaming_Data_Amazon_Kinesis/dockerized-angular-app
CreationPolicy:
ResourceSignal:
Count: 1
Timeout: PT60M
Outputs:
pubIpAddress1:
Description: cloud_user Access Key
Value: !Ref AccessKey
pubIpAddress2:
Description: cloud_user Secret Access Key
Value: !GetAtt AccessKey.SecretAccessKey
pubIpAddress3:
Description: Public IP address of Kinesis Helper Server
Value: !GetAtt LnCreateKinesisHelperServer.PublicIp