/
apply_reshub_recommendations.yml
553 lines (508 loc) · 19.3 KB
/
apply_reshub_recommendations.yml
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
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
AWSTemplateFormatVersion: 2010-09-09
Description: >-
AWS CloudFormation Sample Template LAMP_Multi_AZ: Create a highly available,
scalable LAMP stack with an Amazon RDS database instance for the backend data
store. This template demonstrates using the AWS CloudFormation bootstrap
scripts to install the packages and files necessary to deploy the Apache web
server and PHP at instance launch time. **WARNING** This template creates one
or more Amazon EC2 instances, an Application Load Balancer and an Amazon RDS
DB instance. You will be billed for the AWS resources used if you create a
stack from this template.
Parameters:
VpcId:
Type: 'AWS::EC2::VPC::Id'
Description: VpcId of your existing Virtual Private Cloud (VPC)
ConstraintDescription: must be the VPC Id of an existing Virtual Private Cloud.
PublicSubnets:
Type: 'List<AWS::EC2::Subnet::Id>'
Description: The list of public SubnetIds in your Virtual Private Cloud (VPC) for the ALB
ConstraintDescription: >-
must be a list of at least two existing subnets associated with at least
two different availability zones. They should be residing in the selected
Virtual Private Cloud.
PrivateSubnets:
Type: 'List<AWS::EC2::Subnet::Id>'
Description: The list of private SubnetIds in your Virtual Private Cloud (VPC) for Ec2 and RDS
ConstraintDescription: >-
must be a list of at least two existing subnets associated with at least
two different availability zones. They should be residing in the selected
Virtual Private Cloud.
BackupRegion:
Default: us-east-1
Description: Enter the AWS region you need to use as your DR region. Select a region other than one you are creating the stack in.
Type: String
DBName:
Default: myDatabase
Description: MySQL database name
Type: String
MinLength: '1'
MaxLength: '64'
AllowedPattern: '[a-zA-Z][a-zA-Z0-9]*'
ConstraintDescription: must begin with a letter and contain only alphanumeric characters.
DBUser:
NoEcho: 'true'
Description: Username for MySQL database access
Type: String
MinLength: '1'
MaxLength: '16'
AllowedPattern: '[a-zA-Z][a-zA-Z0-9]*'
ConstraintDescription: must begin with a letter and contain only alphanumeric characters.
DBPassword:
NoEcho: 'true'
Description: Password for MySQL database access
Type: String
MinLength: '8'
MaxLength: '41'
AllowedPattern: '[a-zA-Z0-9]*'
ConstraintDescription: must contain only alphanumeric characters.
DBAllocatedStorage:
Default: '20'
Description: The size of the database (Gb)
Type: Number
MinValue: '20'
MaxValue: '1024'
ConstraintDescription: must be between 20 and 1024Gb.
DBInstanceClass:
Description: The database instance type
Type: String
Default: db.t3.small
ConstraintDescription: must select a valid database instance type.
MultiAZDatabase:
Default: 'false'
Description: Create a Multi-AZ MySQL Amazon RDS database instance
Type: String
AllowedValues:
- 'true'
- 'false'
ConstraintDescription: must be either true or false.
WebServerCapacity:
Default: '2'
Description: The initial number of WebServer instances
Type: Number
MinValue: '1'
MaxValue: '5'
ConstraintDescription: must be between 1 and 5 EC2 instances.
InstanceType:
Description: WebServer EC2 instance type
Type: String
Default: t3.small
ConstraintDescription: must be a valid EC2 instance type.
AmiID:
Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64
Description: The ID of the AMI used to launch web server EC2 Instances.
Type: 'AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>'
EnvironmentName:
Description: An environment name that is prefixed to resource names
Type: String
Default: res-hub
Resources:
ApplicationLoadBalancer:
Type: 'AWS::ElasticLoadBalancingV2::LoadBalancer'
Properties:
Subnets: !Ref PublicSubnets
SecurityGroups:
- !Ref ALBSecurityGroup
ALBSecurityGroup:
Type: 'AWS::EC2::SecurityGroup'
Properties:
GroupDescription: Open EFS file share access
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: '80'
ToPort: '80'
CidrIp: 0.0.0.0/0
VpcId: !Ref VpcId
ALBListener:
Type: 'AWS::ElasticLoadBalancingV2::Listener'
Properties:
DefaultActions:
- Type: forward
TargetGroupArn: !Ref ALBTargetGroup
LoadBalancerArn: !Ref ApplicationLoadBalancer
Port: '80'
Protocol: HTTP
ALBTargetGroup:
Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'
Properties:
HealthCheckIntervalSeconds: 10
HealthCheckTimeoutSeconds: 5
HealthyThresholdCount: 2
Port: 80
Protocol: HTTP
UnhealthyThresholdCount: 5
VpcId: !Ref VpcId
TargetGroupAttributes:
- Key: stickiness.enabled
Value: 'true'
- Key: stickiness.type
Value: lb_cookie
- Key: stickiness.lb_cookie.duration_seconds
Value: '30'
WebServerGroup:
Type: 'AWS::AutoScaling::AutoScalingGroup'
Properties:
VPCZoneIdentifier: !Ref PrivateSubnets
#VPCZoneIdentifier: [ !Select [ 0, !Ref PrivateSubnets ] ]
LaunchTemplate:
LaunchTemplateId: !Ref Ec2InstanceLaunchTemplate
Version: !GetAtt Ec2InstanceLaunchTemplate.LatestVersionNumber
MinSize: '1'
MaxSize: '3'
DesiredCapacity: !Ref WebServerCapacity
TargetGroupARNs:
- !Ref ALBTargetGroup
CreationPolicy:
ResourceSignal:
Timeout: PT10M
Count: !Ref WebServerCapacity
UpdatePolicy:
AutoScalingRollingUpdate:
MinInstancesInService: '1'
MaxBatchSize: '1'
PauseTime: PT15M
WaitOnResourceSignals: 'true'
Ec2InstanceLaunchTemplate:
Type: AWS::EC2::LaunchTemplate
Metadata:
AWS::CloudFormation::Init:
config:
files:
/var/www/inc/dbinfo.inc:
content: !Sub |
<?php
define('DB_SERVER', '${MySQLDatabase.Endpoint.Address}' );
define('DB_USERNAME', '${DBUser}');
define('DB_PASSWORD', '${DBPassword}');
define('DB_DATABASE', '${DBName}');
?>
/var/www/html/index.php:
content:
<?php include "../inc/dbinfo.inc"; ?>
<html>
<head>
<title>AWS CloudFormation PHP Sample</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<h1>Welcome to the AWS CloudFormation PHP Sample</h1>
<p/>
<?php
// Print out the current data and tie
print "The Current Date and Time is :<br/>";
print date("g:i A l, F j Y."); ?>
<p/>
<body>
<h1>Enter New Employee Details</h1>
<?php
/* Connect to MySQL and select the database. */
$connection = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD);
if (mysqli_connect_errno()) echo "Failed to connect to MySQL:" . mysqli_connect_error();
$database = mysqli_select_db($connection, DB_DATABASE);
/* Ensure that the EMPLOYEES table exists. */
VerifyEmployeesTable($connection, DB_DATABASE);
/* If input fields are populated, add a row to the EMPLOYEES table. */
$employee_name = htmlentities($_POST['NAME']);
$employee_address = htmlentities($_POST['ADDRESS']);
if (strlen($employee_name) || strlen($employee_address)) {
AddEmployee($connection, $employee_name, $employee_address);} ?>
<!-- Input form -->
<form action="<?PHP echo $_SERVER['SCRIPT_NAME'] ?>" method="POST">
<table border="0">
<tr>
<td>NAME</td>
<td>ADDRESS</td>
</tr>
<tr>
<td>
<input type="text" name="NAME" maxlength="45" size="30" />
</td>
<td>
<input type="text" name="ADDRESS" maxlength="90" size="60" />
</td>
<td>
<input type="submit" value="Add Data" />
</td>
</tr>
</table>
</form>
<!-- Display table data. -->
<table border="1" cellpadding="2" cellspacing="2">
<tr>
<td>ID</td>
<td>NAME</td>
<td>ADDRESS</td>
</tr>
<?php
$result = mysqli_query($connection, "SELECT * FROM EMPLOYEES");
while($query_data = mysqli_fetch_row($result)) {
echo "<tr>";
echo "<td>",$query_data[0], "</td>",
"<td>",$query_data[1], "</td>",
"<td>",$query_data[2], "</td>";
echo "</tr>"; } ?>
</table>
<!-- Clean up. -->
<?php
mysqli_free_result($result);
mysqli_close($connection); ?>
</body>
</html>
<?php
/* Add an employee to the table. */
function AddEmployee($connection, $name, $address) {
$n = mysqli_real_escape_string($connection, $name);
$a = mysqli_real_escape_string($connection, $address);
$query = "INSERT INTO EMPLOYEES (NAME, ADDRESS) VALUES ('$n', '$a');";
if(!mysqli_query($connection, $query)) echo("<p>Error adding employee data.</p>");}
/* Check whether the table exists and, if not, create it. */
function VerifyEmployeesTable($connection, $dbName) {
if(!TableExists("EMPLOYEES", $connection, $dbName)){
$query = "CREATE TABLE EMPLOYEES (
ID int(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
NAME VARCHAR(45),
ADDRESS VARCHAR(90)
)";
if(!mysqli_query($connection, $query)) echo("<p>Error creating table.</p>");}}
/* Check for the existence of a table. */
function TableExists($tableName, $connection, $dbName) {
$t = mysqli_real_escape_string($connection, $tableName);
$d = mysqli_real_escape_string($connection, $dbName);
$checktable = mysqli_query($connection,
"SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_NAME = '$t' AND TABLE_SCHEMA = '$d'");
if(mysqli_num_rows($checktable) > 0) return true;
return false;}?>
mode: '000600'
owner: apache
group: apache
/etc/cfn/cfn-hup.conf:
content: !Join
- ''
- - |
[main]
- stack=
- !Ref 'AWS::StackId'
- |+
- region=
- !Ref 'AWS::Region'
- |+
- interval=5
- |+
mode: '000400'
owner: root
group: root
/etc/cfn/hooks.d/cfn-auto-reloader.conf:
content: !Join
- ''
- - |
[cfn-auto-reloader-hook]
- |
triggers=post.update
- >
path=Resources.Ec2InstanceLaunchTemplate.Metadata.AWS::CloudFormation::Init
- 'action=/opt/aws/bin/cfn-init -v '
- ' --stack '
- !Ref 'AWS::StackName'
- ' --resource Ec2InstanceLaunchTemplate '
- ' --region '
- !Ref 'AWS::Region'
- |+
- |
runas=root
mode: '000400'
owner: root
group: root
services:
sysvinit:
cfn-hup:
enabled: 'true'
ensureRunning: 'true'
files:
- /etc/cfn/cfn-hup.conf
- /etc/cfn/hooks.d/cfn-auto-reloader.conf
commands:
01-add-efs-entry:
command: !Sub |
TOKEN=$(curl --request PUT "http://169.254.169.254/latest/api/token" --header "X-aws-ec2-metadata-token-ttl-seconds: 3600")
echo "$(curl -s http://169.254.169.254/latest/meta-data/placement/availability-zone --header "X-aws-ec2-metadata-token: $TOKEN").${FileSystem}.efs.${AWS::Region}.amazonaws.com:/ /efs nfs4 defaults" >> /etc/fstab
02_enable_httpd:
command: systemctl enable httpd cfn-hup crond.service
03_start_httpd:
command: systemctl start httpd cfn-hup crond.service
04-mount-efs:
command: sudo mount -a >/dev/null 2>&1
05-sync-log-files:
command: echo "*/5 * * * * rsync -avz /var/log/* /efs/logs" | crontab -
Properties:
LaunchTemplateData:
SecurityGroupIds:
- !GetAtt WebServerSecurityGroup.GroupId
InstanceInitiatedShutdownBehavior: terminate
ImageId: !Ref AmiID
InstanceType: !Ref InstanceType
UserData:
Fn::Base64:
!Sub |
#!/bin/bash -xe
yum install cronie -y
yum update -y aws-cfn-bootstrap
sudo dnf update -y
sudo dnf install -y httpd php php-mysqli mariadb105
mkdir /efs >/dev/null 2>&1
mkdir /var/www/inc
/opt/aws/bin/cfn-init -v --stack ${AWS::StackName} --resource Ec2InstanceLaunchTemplate --region ${AWS::Region}
/opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource WebServerGroup --region ${AWS::Region}
WebServerSecurityGroup:
Type: 'AWS::EC2::SecurityGroup'
Properties:
GroupDescription: Enable HTTP access via port 80 locked down to the ELB and SSH access
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: '80'
ToPort: '80'
SourceSecurityGroupId: !Select
- 0
- !GetAtt
- ApplicationLoadBalancer
- SecurityGroups
VpcId: !Ref VpcId
EFSSecurityGroup:
Type: AWS::EC2::SecurityGroup
Properties:
GroupDescription: Open EFS file share access
VpcId:
Ref: VpcId
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: '2049'
ToPort: '2049'
SourceSecurityGroupId:
Ref: WebServerSecurityGroup
FileSystem:
Type: AWS::EFS::FileSystem
Properties:
PerformanceMode: generalPurpose
BackupPolicy:
Status: ENABLED
LifecyclePolicies:
- TransitionToIA: AFTER_30_DAYS
- TransitionToPrimaryStorageClass: AFTER_1_ACCESS
Encrypted: true
FileSystemTags:
- Key: Name
Value: 'myefsvolume'
MountTarget1:
Type: AWS::EFS::MountTarget
Properties:
FileSystemId:
Ref: FileSystem
SubnetId: !Select [ 0, !Ref PublicSubnets ]
SecurityGroups:
- Ref: EFSSecurityGroup
MountTarget2:
Type: AWS::EFS::MountTarget
Properties:
FileSystemId:
Ref: FileSystem
SubnetId: !Select [ 1, !Ref PublicSubnets ]
SecurityGroups:
- Ref: EFSSecurityGroup
DBEC2SecurityGroup:
Type: 'AWS::EC2::SecurityGroup'
Properties:
GroupDescription: Open database for access
SecurityGroupIngress:
- IpProtocol: tcp
FromPort: '3306'
ToPort: '3306'
SourceSecurityGroupId: !Ref WebServerSecurityGroup
VpcId: !Ref VpcId
MySQLDatabase:
Type: 'AWS::RDS::DBInstance'
Properties:
Engine: MySQL
#BackupRetentionPeriod: 0
AutomaticBackupReplicationRegion: !Ref BackupRegion ##Enable For cross regional backup
BackupRetentionPeriod: 7
DBName: !Ref DBName
MultiAZ: !Ref MultiAZDatabase
DBSubnetGroupName: !Ref myDBSubnetGroup
MasterUsername: !Ref DBUser
MasterUserPassword: !Ref DBPassword
DBInstanceClass: !Ref DBInstanceClass
AllocatedStorage: !Ref DBAllocatedStorage
VPCSecurityGroups:
- !GetAtt
- DBEC2SecurityGroup
- GroupId
myDBSubnetGroup:
Type: 'AWS::RDS::DBSubnetGroup'
Properties:
DBSubnetGroupDescription: RDS subnet group
SubnetIds: !Ref PrivateSubnets
ResHubRole:
Type: 'AWS::IAM::Role'
Properties:
RoleName: 'AWSResilienceHubRole'
Description: 'IAM Role to be used by AWS Resielnce Hub Service'
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: Allow
Principal:
Service:
- resiliencehub.amazonaws.com
Action:
- 'sts:AssumeRole'
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/AWSResilienceHubAsssessmentExecutionPolicy'
BackupPlan:
Type: AWS::Backup::BackupPlan
Properties:
BackupPlan:
BackupPlanName: res-hub-backupplan
BackupPlanRule:
- RuleName: daily-backups
CopyActions:
- DestinationBackupVaultArn: !Sub 'arn:${AWS::Partition}:backup:${BackupRegion}:${AWS::AccountId}:backup-vault:Default'
TargetBackupVault: !Ref 'BackupVault'
ScheduleExpression: cron(15 * ? * * *)
StartWindowMinutes: 60
Lifecycle:
DeleteAfterDays: 60
BackupVault:
Type: AWS::Backup::BackupVault
Properties:
BackupVaultName: res-hub-backupvault
TestRole:
Type: "AWS::IAM::Role"
Properties:
AssumeRolePolicyDocument:
Version: "2012-10-17"
Statement:
- Effect: "Allow"
Principal:
Service:
- "backup.amazonaws.com"
Action:
- "sts:AssumeRole"
ManagedPolicyArns:
- !Sub "arn:${AWS::Partition}:iam::aws:policy/service-role/AWSBackupServiceRolePolicyForBackup"
BasicBackupSelection:
Type: 'AWS::Backup::BackupSelection'
Properties:
BackupPlanId: !Ref BackupPlan
BackupSelection:
SelectionName: 'default_selection'
IamRoleArn: !GetAtt TestRole.Arn
Resources:
- !GetAtt FileSystem.Arn
#- !GetAtt MySQLDatabase.DBInstanceArn
Outputs:
WebsiteURL:
Description: URL for newly created LAMP stack
Value: !Join
- ''
- - 'http://'
- !GetAtt
- ApplicationLoadBalancer
- DNSName