-
Notifications
You must be signed in to change notification settings - Fork 139
/
03-pipelinehelper.yaml
704 lines (633 loc) · 28.2 KB
/
03-pipelinehelper.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
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
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
---
AWSTemplateFormatVersion: 2010-09-09
Description: This templates helps creating CodeCommit repo, S3 Bucket and update repo with Moodle code & configurations.
Parameters:
PipelineSecurityGroup:
Description: Select the Pipeline security group Id
Type: AWS::EC2::SecurityGroup::Id
NumberOfSubnets:
AllowedValues:
- 1
- 2
- 3
Default: 2
Description: Number of subnets. This must match your selections in the list of Subnets below.
Type: String
PipelineSubnet:
Description: Select existing subnets.
Type: List<AWS::EC2::Subnet::Id>
InstanceType:
AllowedValues:
- t3.nano
- t3.micro
- t3.small
- t3.medium
- t3.large
- t3.xlarge
- t3.2xlarge
- m5.large
- m5.xlarge
- m5.2xlarge
- m5.4xlarge
- m5.8xlarge
- m5.12xlarge
- m5.16xlarge
- m5.24xlarge
- c5.large
- c5.xlarge
- c5.2xlarge
- c5.4xlarge
- c5.9xlarge
- c5.12xlarge
- c5.18xlarge
- c5.24xlarge
- r5.large
- r5.xlarge
- r5.2xlarge
- r5.4xlarge
- r5.8xlarge
- r5.12xlarge
- r5.16xlarge
- r5.24xlarge
- t3a.nano
- t3a.micro
- t3a.small
- t3a.medium
- t3a.large
- t3a.xlarge
- t3a.2xlarge
- m5a.large
- m5a.xlarge
- m5a.2xlarge
- m5a.4xlarge
- m5a.8xlarge
- m5a.12xlarge
- m5a.16xlarge
- m5a.24xlarge
- c5a.large
- c5a.xlarge
- c5a.2xlarge
- c5a.4xlarge
- c5a.9xlarge
- c5a.12xlarge
- c5a.18xlarge
- c5a.24xlarge
- r5a.large
- r5a.xlarge
- r5a.2xlarge
- r5a.4xlarge
- r5a.8xlarge
- r5a.12xlarge
- r5a.16xlarge
- r5a.24xlarge
- t4g.nano
- t4g.micro
- t4g.small
- t4g.medium
- t4g.large
- t4g.xlarge
- t4g.2xlarge
- m6g.large
- m6g.xlarge
- m6g.2xlarge
- m6g.4xlarge
- m6g.8xlarge
- m6g.12xlarge
- m6g.16xlarge
- m6g.24xlarge
- m7g.medium
- m7g.large
- m7g.xlarge
- m7g.2xlarge
- m7g.4xlarge
- m7g.8xlarge
- m7g.12xlarge
- m7g.16xlarge
- c6g.large
- c6g.xlarge
- c6g.2xlarge
- c6g.4xlarge
- c6g.9xlarge
- c6g.12xlarge
- c6g.18xlarge
- c6g.24xlarge
- r6g.large
- r6g.xlarge
- r6g.2xlarge
- r6g.4xlarge
- r6g.8xlarge
- r6g.12xlarge
- r6g.16xlarge
- r6g.24xlarge
- c7g.medium
- c7g.large
- c7g.xlarge
- c7g.2xlarge
- c7g.4xlarge
- c7g.8xlarge
- c7g.12xlarge
- c7g.16xlarge
ConstraintDescription: Must be a valid Amazon EC2 instance type.
Default: c7g.xlarge
Description: The Amazon EC2 instance type that dynamically adjusts thresholds based on permitted throughput changes.
Type: String
LatestAmiId:
Type : AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-x86_64
LatestArmAmiId :
Type : AWS::SSM::Parameter::Value<AWS::EC2::Image::Id>
Default: /aws/service/ami-amazon-linux-latest/al2023-ami-kernel-default-arm64
MoodleLocale:
Description: "The main language of the Moodle site, during initial configuration."
Type: String
Default: en
DomainName:
Description: '[ Optional ] The main domain name of the Moodle site (e.g. moodle.example.edu).'
Type: String
RDSInstanceSecretArn:
Description: 'Credentials for Moodle RDS instance'
Type: String
Default: ""
ProjectName:
AllowedPattern: ^([a-zA-Z0-9]*)$
Default: App
Description: The Moodle Project Name
Type: String
WebAsgMax:
AllowedPattern: ^((?!0$)[1-2]?[0-9]|30)$
ConstraintDescription: Must be a number between 1 and 30.
Default: 1
Description: Specifies the maximum number of EC2 instances in the Web Autoscaling Group.
Type: String
WebAsgMin:
AllowedPattern: ^([0-0]?[0-9]|10)$
ConstraintDescription: Must be a number between 0 and 10.
Default: 2
Description: Specifies the minimum number of EC2 instances in the Web Autoscaling Group.
Type: String
MoodleDirectDownloadURL:
Default: "https://download.moodle.org/download.php/direct/stable404/moodle-4.4.tgz"
Description: Specifies the TGZ Moodle direct download URL
Type: String
Conditions:
NumberOfSubnets1:
!Equals [ 1, !Ref NumberOfSubnets ]
NumberOfSubnets2:
!Equals [ 2, !Ref NumberOfSubnets ]
NumberOfSubnets3:
!Equals [ 3, !Ref NumberOfSubnets ]
Subnet0: !Or
- !Condition NumberOfSubnets1
- !Condition NumberOfSubnets2
- !Condition NumberOfSubnets3
Subnet1: !Or
- !Condition NumberOfSubnets2
- !Condition NumberOfSubnets3
Subnet2: !Condition NumberOfSubnets3
UsingGraviton2Ami: !Or
- !Equals ["t4",!Select [0, !Split [ "g.", !Ref WebInstanceType]]]
- !Equals ["c6",!Select [0, !Split [ "g.", !Ref WebInstanceType]]]
- !Equals ["c7",!Select [0, !Split [ "g.", !Ref WebInstanceType]]]
- !Equals ["m6",!Select [0, !Split [ "g.", !Ref WebInstanceType]]]
- !Equals ["m7",!Select [0, !Split [ "g.", !Ref WebInstanceType]]]
- !Equals ["r6",!Select [0, !Split [ "g.", !Ref WebInstanceType]]]
- !Equals ["r7",!Select [0, !Split [ "g.", !Ref WebInstanceType]]]
Resources:
########################### TODO put this in the codepipeline template
MoodleRepo:
Type: AWS::CodeCommit::Repository
Properties:
RepositoryName: !Sub '${ProjectName}-Repo'
RepositoryDescription: This is Moodle CodeCommit repository.
#This bucket is being used for storing Code artifacts for deployment.
CodeArtifactS3Bucket:
Type: AWS::S3::Bucket
DeletionPolicy: RetainExceptOnCreate
Properties:
PublicAccessBlockConfiguration:
BlockPublicAcls: true
BlockPublicPolicy: true
IgnorePublicAcls: true
RestrictPublicBuckets: true
BucketEncryption:
ServerSideEncryptionConfiguration:
- ServerSideEncryptionByDefault:
SSEAlgorithm: AES256
InstanceProfile:
Type: AWS::IAM::InstanceProfile
Properties:
Path: /
Roles:
- !Ref InstanceRole
InstanceRole:
Type: AWS::IAM::Role
Properties:
AssumeRolePolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Principal:
Service:
- ec2.amazonaws.com
Action:
- sts:AssumeRole
ManagedPolicyArns:
- 'arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore'
Path: /
Policies:
- PolicyName: MoodlePipelineHelperPolicy
PolicyDocument:
Version: 2012-10-17
Statement:
- Effect: Allow
Action:
- autoscaling:DescribeAutoScalingGroups
- autoscaling:DescribeAutoScalingInstances
- autoscaling:DescribePolicies
- autoscaling:UpdateAutoScalingGroup
Resource: '*'
- Effect: Allow
Action:
- codepipeline:StartPipelineExecution
Resource:
!Sub 'arn:aws:codepipeline:${AWS::Region}:${AWS::AccountId}:${ProjectName}-Pipeline'
- Effect: Allow
Action:
- codecommit:GitPull
- codecommit:GitPush
- codecommit:CreateBranch
- codecommit:CreateCommit
- codecommit:GetRepository
- codecommit:Get*
- codecommit:List*
- codecommit:PutFile
- codecommit:UploadArchive
- codecommit:GetUploadArchiveStatus
Resource:
- !GetAtt MoodleRepo.Arn
- !Join [ "", [ !GetAtt MoodleRepo.Arn, "/*" ] ]
PipelineHelperASGroup:
Type: AWS::AutoScaling::AutoScalingGroup
Properties:
Cooldown: 60
HealthCheckGracePeriod: 120
HealthCheckType: EC2
LaunchTemplate:
LaunchTemplateId: !Ref PipelineHelperLaunchTemplate
Version: !GetAtt PipelineHelperLaunchTemplate.LatestVersionNumber
MaxSize: 1
MinSize: 0
DesiredCapacity: 1
Tags:
- Key: Name
Value: !Join [ '', [ 'Moodle Pipeline Helper ', !GetAtt MoodleRepo.Name, ' ...will auto terminate' ] ]
PropagateAtLaunch: true
VPCZoneIdentifier:
!If
[ NumberOfSubnets1,
[ !Select [ 0, !Ref PipelineSubnet ] ],
!If
[ NumberOfSubnets2,
[ !Select [ 0, !Ref PipelineSubnet ], !Select [ 1, !Ref PipelineSubnet ] ],
[ !Select [ 0, !Ref PipelineSubnet ], !Select [ 1, !Ref PipelineSubnet ], !Select [ 2, !Ref PipelineSubnet ] ]
]
]
CreationPolicy:
ResourceSignal:
Count: 0
Timeout: PT15M
UpdatePolicy:
AutoScalingReplacingUpdate:
WillReplace: true
PipelineHelperLaunchTemplate:
Type: AWS::EC2::LaunchTemplate
Metadata:
AWS::CloudFormation::Init:
configSets:
moodle_git_config:
- moodle-git-config
moodle-git-config:
files:
/tmp/appspec.yml:
content: !Sub |
version: 0.0
os: linux
files:
- source: /
destination: /var/www/moodle/html/
hooks:
ApplicationStop:
- location: .pipeline/stop_application.sh
timeout: 300
AfterInstall:
- location: .pipeline/after_install.sh
timeout: 300
ApplicationStart:
- location: .pipeline/start_application.sh
timeout: 300
ValidateService:
- location: .pipeline/basic_health_check.sh
timeout: 300
mode: '000755'
owner: root
group: root
/tmp/start_application.sh:
content: !Sub |
#!/bin/bash
sudo systemctl start php-fpm
sudo systemctl start httpd
mode: '000755'
owner: root
group: root
/tmp/stop_application.sh:
content: !Sub |
#!/bin/bash
sudo systemctl stop httpd
sudo systemctl stop php-fpm
mode: '000755'
owner: root
group: root
/tmp/basic_health_check.sh:
content: !Sub |
#!/bin/bash
for i in `seq 1 10`;
do
HTTP_CODE=`curl --write-out '%{http_code}' -o /dev/null -m 10 -q -s http://localhost:80/status.txt`
if [ "$HTTP_CODE" == "200" ]; then
echo "Successfully pulled root page."
exit 0;
fi
echo "Attempt to curl endpoint returned HTTP Code $HTTP_CODE. Backing off and retrying."
sleep 10
done
echo "Server did not come up after expected time. Failing."
exit 1
mode: '000755'
owner: root
group: root
/tmp/config.php:
content: !Sub |
<?php
require 'lib/aws.phar';
use Aws\SecretsManager\SecretsManagerClient;
use Aws\Exception\AwsException;
use Aws\Iam\IamClient;
$client = new SecretsManagerClient([
'version' => '2017-10-17',
'region' => '${AWS::Region}',
]);
$secretName = '${RDSInstanceSecretArn}';
try {
$result = $client->getSecretValue([
'SecretId' => $secretName,
]);
} catch (AwsException $e) {
$error = $e->getAwsErrorCode();
}
// Decrypts secret using the associated KMS CMK.
// Depending on whether the secret is a string or binary, one of these fields will be populated.
if (isset($result['SecretString'])) {
$secret = $result['SecretString'];
}
$CFG = new stdClass;
$CFG->getremoteaddrconf = 0;
$CFG->dbtype = 'pgsql';
$CFG->dblibrary = 'native';
$CFG->dbhost = getenv('EnvDatabaseClusterEndpointAddress');
$CFG->dbname = getenv('EnvDatabaseName');
$CFG->dbuser = json_decode($secret)->{'username'};
$CFG->dbpass = json_decode($secret)->{'password'};
$CFG->prefix = 'mdl_';
$CFG->lang = '${MoodleLocale}';
$CFG->dboptions = array(
'dbpersist' => false,
'dbsocket' => false,
'dbport' => '',
'dbhandlesoptions' => false,
'dbcollation' => 'utf8mb4_unicode_ci',
'connecttimeout' => 300,
'readonly' => [
'instance' => 'db-cluster-readonly-endpoint',
'connecttimeout' => 300,
'latency' => 2,
'exclude_tables' => [
'config',
],
]
);
// Hostname definition //
$hostname = '${DomainName}';
$hostwithprotocol = strtolower($hostname);
if(substr($hostwithprotocol, 0, 4) === 'http'){} else {
$hostwithprotocol = 'http://'.strtolower($hostwithprotocol);
}
$CFG->wwwroot = strtolower($hostwithprotocol);
$CFG->sslproxy = (substr($hostwithprotocol,0,5)=='https' ? true : false);
// Moodledata location //
$CFG->dataroot = '/var/www/moodle/data';
$CFG->tempdir = '/var/www/moodle/temp';
$CFG->cachedir = '/var/www/moodle/cache';
$CFG->localcachedir = '/var/www/moodle/local';
$CFG->directorypermissions = 02777;
$CFG->admin = 'admin';
// Configure Session Cache
$SessionsCacheType = 'Memcached';
$SessionEndpoint = '';
if ($SessionEndpoint != '') {
$CFG->dbsessions = false;
if($SessionsCacheType == 'Redis') {
$CFG->session_handler_class = '\core\session\redis';
$CFG->session_redis_host = $SessionEndpoint;
$CFG->session_redis_port = 6379; // Optional.
$CFG->session_redis_database = 0; // Optional, default is db 0.
//$CFG->session_redis_auth = ''; // Optional, default is don't set one.
//$CFG->session_redis_prefix = ''; // Optional, default is don't set one.
$CFG->session_redis_acquire_lock_timeout = 120; // Default is 2 minutes.
$CFG->session_redis_acquire_lock_warn = 0; // If set logs early warning if a lock has not been acquried.
$CFG->session_redis_lock_expire = 7200; // Optional, defaults to session timeout.
$CFG->session_redis_lock_retry = 100; // Optional wait between lock attempts in ms, default is 100.
$CFG->session_redis_serializer_use_igbinary = false; // Optional, default is PHP builtin serializer.
$CFG->session_redis_compressor = 'none';
} else {
$CFG->session_handler_class = '\core\session\memcached';
$CFG->session_memcached_save_path = $SessionEndpoint;
$CFG->session_memcached_prefix = 'memc.sess.key.';
$CFG->session_memcached_acquire_lock_timeout = 120;
$CFG->session_memcached_lock_expire = 7100;
$CFG->session_memcached_lock_retry_sleep = 150;
}
}
//@error_reporting(E_ALL | E_STRICT); // NOT FOR PRODUCTION SERVERS!
//@ini_set('display_errors', '1'); // NOT FOR PRODUCTION SERVERS!
//$CFG->debug = (E_ALL | E_STRICT); // === DEBUG_DEVELOPER - NOT FOR PRODUCTION SERVERS!
//$CFG->debugdisplay = 1;
require_once(__DIR__ . '/lib/setup.php');
// END OF CONFIG //
?>
mode: '000755'
owner: root
group: root
/tmp/after_install.sh:
content:
!Sub |
#!/bin/bash -xe
# Setting up access ownership to apache:apache
chown -R apache:apache /var/www/moodle/html
chown -R apache:apache /var/www/moodle/data
chown -R apache:apache /var/www/moodle/cache
chown -R apache:apache /var/www/moodle/temp
chown -R apache:apache /var/www/moodle/local
availabilityzone=$(ec2-metadata -z | awk '{print $2}' | sed 's/(.)//')
region=$(ec2-metadata -z | awk '{print $2}' | sed 's/[a-z]$//')
export EnvDatabaseType=$(aws ssm get-parameters --region $region --names /Moodle/${ProjectName}/DB/Type --query Parameters[0].Value)
export EnvDatabaseType=`echo $EnvDatabaseType | sed -e 's/^"//' -e 's/"$//'`
if [ "$EnvDatabaseType" == "MySQL" ]; then
sed -i "s/\$CFG->dbtype = .*/\$CFG->dbtype = 'auroramysql';/" /var/www/moodle/html/config.php
else
sed -i "s/\$CFG->dbtype = .*/\$CFG->dbtype = 'pgsql';/" /var/www/moodle/html/config.php
fi
export EnvDatabaseName=$(aws ssm get-parameters --region $region --names /Moodle/${ProjectName}/DB/Name --query Parameters[0].Value)
export EnvDatabaseName=`echo $EnvDatabaseName | sed -e 's/^"//' -e 's/"$//'`
sed -i "s/\$CFG->dbname.*/\$CFG->dbname = '"$EnvDatabaseName"';/" /var/www/moodle/html/config.php
export EnvDatabaseClusterEndpointAddress=$(aws ssm get-parameters --region $region --names /Moodle/${ProjectName}/DB/ClusterEndpoint --query Parameters[0].Value)
export EnvDatabaseClusterEndpointAddress=`echo $EnvDatabaseClusterEndpointAddress | sed -e 's/^"//' -e 's/"$//'`
sed -i "s/\$CFG->dbhost.*/\$CFG->dbhost = '"$EnvDatabaseClusterEndpointAddress"';/" /var/www/moodle/html/config.php
export EnvDatabaseClusterReadOnlyEndpointAddress=$(aws ssm get-parameters --region $region --names /Moodle/${ProjectName}/DB/ClusterReadOnlyEndpoint --query Parameters[0].Value)
export EnvDatabaseClusterReadOnlyEndpointAddress=`echo $EnvDatabaseClusterReadOnlyEndpointAddress | sed -e 's/^"//' -e 's/"$//'`
sed -i "s/'instance' => '.*/'instance' => '"$EnvDatabaseClusterReadOnlyEndpointAddress"',/" /var/www/moodle/html/config.php
export EnvDnsName=$(aws ssm get-parameters --region $region --names /Moodle/${ProjectName}/Network/DomainName --query Parameters[0].Value)
export EnvDnsName=`echo $EnvDnsName | sed -e 's/^"//' -e 's/"$//'`
sed -i'' -e "s,\$hostname = .*,\$hostname = '"$EnvDnsName"';," /var/www/moodle/html/config.php
export EnvIsMoodleSetupCompleted=$(aws ssm get-parameters --region $region --names /Moodle/${ProjectName}/IsMoodleSetupCompleted --query Parameters[0].Value)
export EnvIsMoodleSetupCompleted=`echo $EnvIsMoodleSetupCompleted | sed -e 's/^"//' -e 's/"$//'`
export EnvElastiCacheClusterEndpointAddress=$(aws ssm get-parameters --region $region --names /Moodle/${ProjectName}/Cache/session/ElastiCacheClusterEndpoint --query Parameters[0].Value)
export EnvElastiCacheClusterEndpointAddress=`echo $EnvElastiCacheClusterEndpointAddress | sed -e 's/^"//' -e 's/"$//' | cut -f1 -d":"`
export EnvElastiCacheEngine=$(aws ssm get-parameters --region $region --names /Moodle/${ProjectName}/Cache/session/Engine --query Parameters[0].Value)
export EnvElastiCacheEngine=`echo $EnvElastiCacheEngine | sed -e 's/^"//' -e 's/"$//'`
# Setting up ElastiCache dependencies for cache
if [ "$EnvIsMoodleSetupCompleted" != "No" ] && [ "$EnvElastiCacheClusterEndpointAddress" != "null" -a "$EnvElastiCacheClusterEndpointAddress" != "" ]; then
sed -i "s/\$SessionEndpoint = .*/\$SessionEndpoint = '"$EnvElastiCacheClusterEndpointAddress"';/" /var/www/moodle/html/config.php
if [ "$EnvElastiCacheEngine" == "Redis" ]; then
sed -i "s/\$SessionsCacheType = .*/\$SessionsCacheType = '"$EnvElastiCacheEngine"';/" /var/www/moodle/html/config.php
#else
# Below commented out because we don't use the ElastiCache client anymore
#update Moodle source to use DYNAMIC_CLIENT_MODE so Moodle can detect changes to the elasticache cluster membership
#sed -i '/\$this->options\[Memcached::OPT_BUFFER_WRITES\] = \$bufferwrites;/a \ \ \ \ \ \ \ \ $this->options[Memcached::OPT_CLIENT_MODE] = Memcached::DYNAMIC_CLIENT_MODE;' /var/www/moodle/html/cache/stores/memcached/lib.php
fi
else
sed -i "s/\$SessionEndpoint = .*/\$SessionEndpoint = '';/" /var/www/moodle/html/config.php
fi
mode: 000500
owner: root
group: root
/tmp/moodle-git-config.sh:
content: !Sub |
#!/bin/bash -x
git config --system user.name 'AWS User'
git config --system user.email [email protected]
git config --system credential.helper '!aws codecommit credential-helper $@'
git config --system credential.UseHttpPath true
DIR="/tmp/moodle"
if [ -d "$DIR" ]; then
cd /tmp/moodle
else
mkdir /tmp/moodle
mkdir /tmp/moodle/.pipeline
# Get Latest Moodle stable version
wget -O /tmp/moodle.tgz ${MoodleDirectDownloadURL}
tar -xvzf /tmp/moodle.tgz --strip-components=1 -C /tmp/moodle/
wget -O /tmp/moodle/lib/aws.phar https://docs.aws.amazon.com/aws-sdk-php/v3/download/aws.phar
cd /tmp/moodle
git init
git checkout -b main
git add .
git commit -m "Moodle original code commit."
git remote add origin ${MoodleRepo.CloneUrlHttp}
fi
#Added code scripts for CodePipeline
cp -f /tmp/appspec.yml /tmp/moodle/
cp -f /tmp/start_application.sh /tmp/moodle/.pipeline/
cp -f /tmp/stop_application.sh /tmp/moodle/.pipeline/
cp -f /tmp/basic_health_check.sh /tmp/moodle/.pipeline/
cp -f /tmp/config.php /tmp/moodle/
cp -f /tmp/before_install.sh /tmp/moodle/.pipeline/
cp -f /tmp/setup_efs.sh /tmp/moodle/.pipeline/
cp -f /tmp/configure_opcache.sh /tmp/moodle/.pipeline/
cp -f /tmp/install_mysql_dependencies.sh /tmp/moodle/.pipeline/
cp -f /tmp/install_pgsql_dependencies.sh /tmp/moodle/.pipeline/
cp -f /tmp/install_cacheclient.sh /tmp/moodle/.pipeline/
cp -f /tmp/after_install.sh /tmp/moodle/.pipeline/
git add --all
git commit -m "Moodle Code pipeline commits"
git push -u origin main
# get instance id
instance_id=$(ec2-metadata -i | awk '{print $2}' | sed 's/(.)//')
# get region from instance meta-data
availabilityzone=$(ec2-metadata -z | awk '{print $2}' | sed 's/(.)//')
region=$(ec2-metadata -z | awk '{print $2}' | sed 's/[a-z]$//')
# wait for Moodle setup to be completed
echo "Start checking whether Moodle setup completed or not"
counter=0
while true
do
sleep 60
export EnvIsMoodleSetupCompleted=$(aws ssm get-parameters --region $region --names /Moodle/${ProjectName}/IsMoodleSetupCompleted --query Parameters[0].Value)
export EnvIsMoodleSetupCompleted=`echo $EnvIsMoodleSetupCompleted | sed -e 's/^"//' -e 's/"$//'`
if [ "$EnvIsMoodleSetupCompleted" == "No" ]; then
((counter++))
echo "Waiting for 1 more minute, running for the $counter time."
else
break
fi
done
# script to update Moodle pipeline release
aws codepipeline start-pipeline-execution --name ${ProjectName}-Pipeline --region $region
# set ASG to zero which terminates instance
export EnvWebAppASGName=$(aws ssm get-parameters --region $region --names /Moodle/${ProjectName}/WebAppASGName --query Parameters[0].Value)
export EnvWebAppASGName=`echo $EnvWebAppASGName | sed -e 's/^"//' -e 's/"$//'`
aws autoscaling update-auto-scaling-group --auto-scaling-group-name $EnvWebAppASGName --desired-capacity ${WebAsgMin} --min-size ${WebAsgMin} --max-size ${WebAsgMax} --region $region
# Shutting down pipeline-helper instance
# get autoscaling group name
asg_name=$(aws autoscaling describe-auto-scaling-instances --instance-ids $instance_id --region $region --output text --query 'AutoScalingInstances[0].AutoScalingGroupName')
# set pipeline-helper ASG to zero which terminates instance
aws autoscaling update-auto-scaling-group --auto-scaling-group-name $asg_name --min-size 0 --desired-capacity 0 --region $region
mode: '000755'
owner: root
group: root
commands:
update-moodle-repo:
command: ./moodle-git-config.sh
cwd: /tmp
ignoreErrors: false
Properties:
LaunchTemplateData:
BlockDeviceMappings:
- DeviceName: /dev/xvda
Ebs:
DeleteOnTermination: true
VolumeSize: 10
VolumeType: gp3
IamInstanceProfile:
Arn: !GetAtt InstanceProfile.Arn
ImageId: !If [UsingGraviton2Ami, !Ref LatestArmAmiId, !Ref LatestAmiId]
InstanceType: !Ref InstanceType
SecurityGroupIds:
- !Ref PipelineSecurityGroup
UserData:
"Fn::Base64":
!Sub |
#!/bin/bash -xe
sudo systemctl enable amazon-ssm-agent
sudo systemctl start amazon-ssm-agent
dnf install -y git
/opt/aws/bin/cfn-init --configsets moodle_git_config --verbose --stack ${AWS::StackName} --resource PipelineHelperLaunchTemplate --region ${AWS::Region}
/opt/aws/bin/cfn-signal -e $? --stack ${AWS::StackName} --resource PipelineHelperASGroup --region ${AWS::Region}
Outputs:
CodeArtifactS3BucketArn:
Value: !GetAtt CodeArtifactS3Bucket.Arn
CodeArtifactS3BucketName:
Value: !Ref CodeArtifactS3Bucket
MoodleRepoName:
Value: !GetAtt MoodleRepo.Name
MoodleRepoArn:
Value: !GetAtt MoodleRepo.Arn