-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
jenkins2-ha-agents.yaml
2429 lines (2429 loc) · 100 KB
/
jenkins2-ha-agents.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
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
---
# Copyright 2018 widdix GmbH
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
AWSTemplateFormatVersion: '2010-09-09'
Description: 'Jenkins 2: highly available Jenkins master and dynamic agents, a cloudonaut.io template'
Metadata:
'AWS::CloudFormation::Interface':
ParameterGroups:
- Label:
default: 'Parent Stacks'
Parameters:
- ParentVPCStack
- ParentSSHBastionStack
- ParentAuthProxyStack
- ParentAlertStack
- ParentS3StackAccessLog
- ParentZoneStack
- Label:
default: 'EC2 Parameters'
Parameters:
- KeyName
- IAMUserSSHAccess
- SystemsManagerAccess
- SubDomainNameWithDot
- ManagedPolicyArns
- Label:
default: 'EFS Parameters'
Parameters:
- EFSProvisionedThroughputInMibps
- EFSBackupRetentionPeriod
- EFSBackupScheduleExpression
- Label:
default: 'Master Parameters'
Parameters:
- MasterSubnetsReach
- MasterELBScheme
- MasterInstanceType
- MasterAdminPassword
- MasterLogsRetentionInDays
- MasterVolumeSize
- MasterLoadBalancerIdleTimeout
- Label:
default: 'Agent Parameters'
Parameters:
- AgentSubnetsReach
- AgentInstanceType
- AgentVolumeSize
- AgentMaxSize
- AgentMinSize
- AgentMaxBuildWaitTimeInSeconds
- AgentLogsRetentionInDays
- Label:
default: 'Permission Parameters'
Parameters:
- PermissionsBoundary
Parameters:
ParentVPCStack:
Description: 'Stack name of parent VPC stack based on vpc/vpc-*azs.yaml template.'
Type: String
ParentSSHBastionStack:
Description: 'Optional but recommended stack name of parent SSH bastion host/instance stack based on vpc/vpc-*-bastion.yaml template.'
Type: String
Default: ''
ParentAuthProxyStack:
Description: 'Optional stack name of parent auth proxy stack based on security/auth-proxy-*.yaml template.'
Type: String
Default: ''
ParentAlertStack:
Description: 'Optional but recommended stack name of parent alert stack based on operations/alert.yaml template.'
Type: String
Default: ''
ParentS3StackAccessLog:
Description: 'Optional stack name of parent s3 stack based on state/s3.yaml template (with Access set to ElbAccessLogWrite) to store access logs.'
Type: String
Default: ''
ParentZoneStack:
Description: 'Optional stack name of parent zone stack based on vpc/zone-*.yaml template.'
Type: String
Default: ''
PermissionsBoundary:
Description: 'Optional ARN for a policy that will be used as the permission boundary for all roles created by this template.'
Type: String
Default: ''
KeyName:
Description: 'Optional key pair of the ec2-user to establish a SSH connection to the Jenkins master and agents.'
Type: String
Default: ''
IAMUserSSHAccess:
Description: 'Synchronize public keys of IAM users to enable personalized SSH access (Doc: https://cloudonaut.io/manage-aws-ec2-ssh-access-with-iam/).'
Type: String
Default: false
AllowedValues:
- true
- false
SystemsManagerAccess:
Description: 'Enable AWS Systems Manager agent and authorization.'
Type: String
Default: true
AllowedValues:
- true
- false
MasterSubnetsReach:
Description: 'Should the master have direct access to the Internet or do you prefer private subnets with NAT?'
Type: String
Default: Public
AllowedValues:
- Public
- Private
MasterELBScheme:
Description: 'Indicates whether the load balancer in front of the Jenkins master is Internet-facing or internal.'
Type: String
Default: 'internet-facing'
AllowedValues:
- 'internet-facing'
- internal
MasterInstanceType:
Description: 'The instance type of the Jenkins master.'
Type: String
Default: 't2.micro'
MasterAdminPassword:
Description: 'A password for the Jenkins master admin. Must not be changed!'
Type: String
NoEcho: true
MinLength: 8
MaxLength: 32
MasterLogsRetentionInDays:
Description: 'Specifies the number of days you want to retain log events in the specified log group.'
Type: Number
Default: 14
AllowedValues: [1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653]
MasterVolumeSize:
Description: 'The root volume size, in Gibibytes (GiB). Keep in mind that Jenkins home lives on EFS.'
Type: Number
Default: 8
ConstraintDescription: 'Must be in the range [8-1024]'
MinValue: 8
MaxValue: 1024
MasterLoadBalancerIdleTimeout:
Description: 'The idle timeout value, in seconds.'
Type: Number
Default: 60
MinValue: 1
MaxValue: 4000
AgentSubnetsReach:
Description: 'Should the agents have direct access to the Internet or do you prefer private subnets with NAT?'
Type: String
Default: Public
AllowedValues:
- Public
- Private
AgentInstanceType:
Description: 'The instance type of the Jenkins agents.'
Type: String
Default: 't2.micro'
AgentVolumeSize:
Description: 'The root volume size, in Gibibytes (GiB). Keep in mind that Jenkins home lives on EFS.'
Type: Number
Default: 8
ConstraintDescription: 'Must be in the range [8-1024]'
MinValue: 8
MaxValue: 1024
AgentMaxSize:
Description: 'The maximum size of the agents Auto Scaling group.'
Type: Number
Default: 2
ConstraintDescription: 'Must be >= 1'
MinValue: 1
AgentMinSize:
Description: 'The minimum size of the agents Auto Scaling group.'
Type: Number
Default: 0
ConstraintDescription: 'Must be >= 0'
MinValue: 0
AgentMaxBuildWaitTimeInSeconds:
Description: 'Maximum time in seconds an agent can continue with a build although it should be scaled down.'
Type: Number
Default: 600
ConstraintDescription: 'Must be in the range [600-7200]'
MinValue: 600
MaxValue: 7200
AgentLogsRetentionInDays:
Description: 'Specifies the number of days you want to retain log events in the specified log group.'
Type: Number
Default: 14
AllowedValues: [1, 3, 5, 7, 14, 30, 60, 90, 120, 150, 180, 365, 400, 545, 731, 1827, 3653]
SubDomainNameWithDot:
Description: 'Name that is used to create the DNS entry with trailing dot, e.g. §{SubDomainNameWithDot}§{HostedZoneName}. Leave blank for naked (or apex and bare) domain. Requires ParentZoneStack parameter!'
Type: String
Default: 'jenkins.'
ManagedPolicyArns:
Description: 'Optional comma-delimited list of IAM managed policy ARNs to attach to the instance''s IAM role'
Type: String
Default: ''
EFSProvisionedThroughputInMibps:
Description: 'The provisioned throughput for the Elastic File System (EFS) in Mibps. Default is 0 which enables the bursting mode and disables provisioned throughput.'
Type: Number
Default: 0
EFSBackupRetentionPeriod:
Description: 'The number of days to keep backups of the EFS file system (set to 0 to disable).'
Type: Number
MinValue: 0
MaxValue: 35
Default: 30
EFSBackupScheduleExpression:
Description: 'A CRON expression specifying when AWS Backup initiates a backup job.'
Type: String
Default: 'cron(0 5 ? * * *)'
Mappings:
RegionMap:
'ap-south-2':
AMI: 'ami-0ab51832ad0357955'
'ap-south-1':
AMI: 'ami-0d6eab68a2aa4419b'
'eu-south-1':
AMI: 'ami-0c17f1490200f1b98'
'eu-south-2':
AMI: 'ami-0a8f09e218768d19d'
'me-central-1':
AMI: 'ami-07e91783d8a16e1f2'
'il-central-1':
AMI: 'ami-04ee358ea26a28621'
'ca-central-1':
AMI: 'ami-06aa9bf8acd13295e'
'eu-central-1':
AMI: 'ami-0b26dd07b92ba60b5'
'eu-central-2':
AMI: 'ami-08b6d5c9e5f65725a'
'us-west-1':
AMI: 'ami-0b301738029f9f48e'
'us-west-2':
AMI: 'ami-076e3756930a93fbb'
'af-south-1':
AMI: 'ami-04c86004365f50376'
'eu-north-1':
AMI: 'ami-05668410ca8bbacb3'
'eu-west-3':
AMI: 'ami-0e240183bb3096e67'
'eu-west-2':
AMI: 'ami-08ceb58c67626d304'
'eu-west-1':
AMI: 'ami-064857453c447bed5'
'ap-northeast-3':
AMI: 'ami-0806b1119517557f0'
'ap-northeast-2':
AMI: 'ami-00252d017d66f9cdd'
'me-south-1':
AMI: 'ami-05263463386d9b3a5'
'ap-northeast-1':
AMI: 'ami-08aa3b50f80805e20'
'sa-east-1':
AMI: 'ami-0cd4a737dad460342'
'ap-east-1':
AMI: 'ami-0a97c2677505cda75'
'ca-west-1':
AMI: 'ami-01c7593ec24183809'
'ap-southeast-1':
AMI: 'ami-083068d1edaf8af18'
'ap-southeast-2':
AMI: 'ami-094ff1d74ab636074'
'ap-southeast-3':
AMI: 'ami-08990191cc9b187ac'
'ap-southeast-4':
AMI: 'ami-0d9704c67691a5331'
'us-east-1':
AMI: 'ami-046eeba8a7f7bbefd'
'us-east-2':
AMI: 'ami-02c4f64d0cbab1731'
Conditions:
HasPermissionsBoundary: !Not [!Equals [!Ref PermissionsBoundary, '']]
HasZeroAgents: !Equals [!Ref AgentMinSize, '0']
HasKeyName: !Not [!Equals [!Ref KeyName, '']]
HasIAMUserSSHAccess: !Equals [!Ref IAMUserSSHAccess, 'true']
HasSystemsManagerAccess: !Equals [!Ref SystemsManagerAccess, 'true']
HasSSHBastionSecurityGroup: !Not [!Equals [!Ref ParentSSHBastionStack, '']]
HasNotSSHBastionSecurityGroup: !Equals [!Ref ParentSSHBastionStack, '']
HasAuthProxySecurityGroup: !Not [!Equals [!Ref ParentAuthProxyStack, '']]
HasNotAuthProxySecurityGroup: !Equals [!Ref ParentAuthProxyStack, '']
HasMasterELBSchemeInternetFacing: !Equals [!Ref MasterELBScheme, 'internet-facing']
HasMasterELBSchemeInternal: !Equals [!Ref MasterELBScheme, 'internal']
HasAlertTopic: !Not [!Equals [!Ref ParentAlertStack, '']]
HasS3Bucket: !Not [!Equals [!Ref ParentS3StackAccessLog, '']]
HasZone: !Not [!Equals [!Ref ParentZoneStack, '']]
HasZoneAndMasterELBSchemeInternetFacing: !And [!Condition HasZone, !Condition HasMasterELBSchemeInternetFacing]
HasManagedPolicyArns: !Not [!Equals [!Ref ManagedPolicyArns, '']]
HasEFSProvisionedThroughput: !Not [!Condition HasNotEFSProvisionedThroughput]
HasNotEFSProvisionedThroughput: !Equals [!Ref EFSProvisionedThroughputInMibps, '0']
HasAlertTopicAndNotEFSProvisionedThroughput: !And [!Condition HasAlertTopic, !Condition HasNotEFSProvisionedThroughput]
HasEFSBackupRetentionPeriod: !Not [!Equals [!Ref EFSBackupRetentionPeriod, 0]]
Resources:
MasterStorageSG:
Type: 'AWS::EC2::SecurityGroup'
Properties:
GroupDescription: 'jenkins-master'
VpcId: {'Fn::ImportValue': !Sub '${ParentVPCStack}-VPC'}
SecurityGroupIngress:
- SourceSecurityGroupId: !Ref MasterSG
FromPort: 2049
ToPort: 2049
IpProtocol: tcp
MasterStorage:
Type: 'AWS::EFS::FileSystem'
Properties:
ThroughputMode: !If [HasEFSProvisionedThroughput, 'provisioned', 'bursting']
ProvisionedThroughputInMibps: !If [HasEFSProvisionedThroughput, !Ref EFSProvisionedThroughputInMibps, !Ref 'AWS::NoValue']
FileSystemTags:
- Key: Name
Value: 'jenkins-master-storage'
PerformanceMode: generalPurpose
MasterStorageBurstCreditBalanceTooLowAlarm:
Condition: HasAlertTopicAndNotEFSProvisionedThroughput
Type: 'AWS::CloudWatch::Alarm'
Properties:
AlarmDescription: 'Average burst credit balance over last 10 minutes too low, expect a significant performance drop soon.'
Namespace: 'AWS/EFS'
MetricName: BurstCreditBalance
Statistic: Average
Period: 600
EvaluationPeriods: 1
ComparisonOperator: LessThanThreshold
Threshold: 192000000000 # 192 GB in Bytes (last ~30 minutes where you can burst at 100 MB/sec)
AlarmActions:
- {'Fn::ImportValue': !Sub '${ParentAlertStack}-TopicARN'}
Dimensions:
- Name: FileSystemId
Value: !Ref MasterStorage
MasterStoragePercentIOLimitTooHighAlarm:
Condition: HasAlertTopicAndNotEFSProvisionedThroughput
Type: 'AWS::CloudWatch::Alarm'
Properties:
AlarmDescription: 'I/O limit has been reached, consider using Max I/O performance mode.'
Namespace: 'AWS/EFS'
MetricName: PercentIOLimit
Statistic: Maximum
Period: 600
EvaluationPeriods: 3
ComparisonOperator: GreaterThanThreshold
Threshold: 95
AlarmActions:
- {'Fn::ImportValue': !Sub '${ParentAlertStack}-TopicARN'}
Dimensions:
- Name: FileSystemId
Value: !Ref MasterStorage
MasterStorageThroughputAlarm: # https://docs.aws.amazon.com/efs/latest/ug/monitoring-metric-math.html#metric-math-throughput-utilization
Condition: HasAlertTopic
Type: 'AWS::CloudWatch::Alarm'
Properties:
AlarmDescription: 'Reached 80% of the permitted throughput 6 times over last 10 minutes.'
Metrics:
- Id: m1
Label: MeteredIOBytes
MetricStat:
Metric:
Namespace: 'AWS/EFS'
MetricName: MeteredIOBytes
Dimensions:
- Name: FileSystemId
Value: !Ref MasterStorage
Period: 60
Stat: Sum
Unit: Bytes
ReturnData: false
- Id: m2
Label: PermittedThroughput
MetricStat:
Metric:
Namespace: 'AWS/EFS'
MetricName: PermittedThroughput
Dimensions:
- Name: FileSystemId
Value: !Ref MasterStorage
Period: 60
Stat: Sum
Unit: 'Bytes/Second'
ReturnData: false
- Expression: '(m1/1048576)/PERIOD(m1)'
Id: e1
Label: e1
ReturnData: false
- Expression: 'm2/1048576'
Id: e2
Label: e2
ReturnData: false
- Expression: '((e1)*100)/(e2)'
Id: e3
Label: 'Throughput utilization (%)'
ReturnData: true
EvaluationPeriods: 10
DatapointsToAlarm: 6
ComparisonOperator: GreaterThanThreshold
Threshold: 80
AlarmActions:
- {'Fn::ImportValue': !Sub '${ParentAlertStack}-TopicARN'}
MasterStorageMountTargetA:
Type: 'AWS::EFS::MountTarget'
Properties:
FileSystemId: !Ref MasterStorage
SecurityGroups:
- !Ref MasterStorageSG
SubnetId: {'Fn::ImportValue': !Sub '${ParentVPCStack}-SubnetA${MasterSubnetsReach}'}
MasterStorageMountTargetB:
Type: 'AWS::EFS::MountTarget'
Properties:
FileSystemId: !Ref MasterStorage
SecurityGroups:
- !Ref MasterStorageSG
SubnetId: {'Fn::ImportValue': !Sub '${ParentVPCStack}-SubnetB${MasterSubnetsReach}'}
MasterELBSG:
Type: 'AWS::EC2::SecurityGroup'
Properties:
GroupDescription: 'jenkins-elb-master'
VpcId: {'Fn::ImportValue': !Sub '${ParentVPCStack}-VPC'}
MasterELBSGInWorld:
Type: 'AWS::EC2::SecurityGroupIngress'
Condition: HasNotAuthProxySecurityGroup
Properties:
GroupId: !Ref MasterELBSG
IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIp: '0.0.0.0/0'
MasterELBSGInWorldIPv6:
Type: 'AWS::EC2::SecurityGroupIngress'
Condition: HasNotAuthProxySecurityGroup
Properties:
GroupId: !Ref MasterELBSG
IpProtocol: tcp
FromPort: 80
ToPort: 80
CidrIpv6: '::/0'
MasterELBSGInAuthProxy:
Type: 'AWS::EC2::SecurityGroupIngress'
Condition: HasAuthProxySecurityGroup
Properties:
GroupId: !Ref MasterELBSG
IpProtocol: tcp
FromPort: 80
ToPort: 80
SourceSecurityGroupId: {'Fn::ImportValue': !Sub '${ParentAuthProxyStack}-SecurityGroup'}
MasterHTTPCodeELB5XXTooHighAlarm:
Condition: HasAlertTopic
Type: 'AWS::CloudWatch::Alarm'
Properties:
AlarmDescription: 'Application load balancer returns 5XX HTTP status codes'
Namespace: 'AWS/ApplicationELB'
MetricName: HTTPCode_ELB_5XX_Count
Statistic: Sum
Period: 60
EvaluationPeriods: 1
ComparisonOperator: GreaterThanThreshold
Threshold: 0
AlarmActions:
- {'Fn::ImportValue': !Sub '${ParentAlertStack}-TopicARN'}
Dimensions:
- Name: LoadBalancer
Value: !GetAtt MasterELB.LoadBalancerFullName
TreatMissingData: notBreaching
MasterHTTPCodeTarget5XXTooHighAlarm:
Condition: HasAlertTopic
Type: 'AWS::CloudWatch::Alarm'
Properties:
AlarmDescription: 'Application load balancer receives 5XX HTTP status codes from targets'
Namespace: 'AWS/ApplicationELB'
MetricName: HTTPCode_Target_5XX_Count
Statistic: Sum
Period: 60
EvaluationPeriods: 1
ComparisonOperator: GreaterThanThreshold
Threshold: 0
AlarmActions:
- {'Fn::ImportValue': !Sub '${ParentAlertStack}-TopicARN'}
Dimensions:
- Name: LoadBalancer
Value: !GetAtt MasterELB.LoadBalancerFullName
TreatMissingData: notBreaching
MasterRejectedConnectionCountTooHighAlarm:
Condition: HasAlertTopic
Type: 'AWS::CloudWatch::Alarm'
Properties:
AlarmDescription: 'Application load balancer rejected connections because the load balancer had reached its maximum number of connections'
Namespace: 'AWS/ApplicationELB'
MetricName: RejectedConnectionCount
Statistic: Sum
Period: 60
EvaluationPeriods: 1
ComparisonOperator: GreaterThanThreshold
Threshold: 0
AlarmActions:
- {'Fn::ImportValue': !Sub '${ParentAlertStack}-TopicARN'}
Dimensions:
- Name: LoadBalancer
Value: !GetAtt MasterELB.LoadBalancerFullName
TreatMissingData: notBreaching
MasterTargetConnectionErrorCountTooHighAlarm:
Condition: HasAlertTopic
Type: 'AWS::CloudWatch::Alarm'
Properties:
AlarmDescription: 'Application load balancer could not connect to targets'
Namespace: 'AWS/ApplicationELB'
MetricName: TargetConnectionErrorCount
Statistic: Sum
Period: 60
EvaluationPeriods: 1
ComparisonOperator: GreaterThanThreshold
Threshold: 0
AlarmActions:
- {'Fn::ImportValue': !Sub '${ParentAlertStack}-TopicARN'}
Dimensions:
- Name: LoadBalancer
Value: !GetAtt MasterELB.LoadBalancerFullName
TreatMissingData: notBreaching
RecordSet:
Condition: HasZone
Type: 'AWS::Route53::RecordSet'
Properties:
AliasTarget:
HostedZoneId: !GetAtt 'MasterELB.CanonicalHostedZoneID'
DNSName: !GetAtt 'MasterELB.DNSName'
HostedZoneId: {'Fn::ImportValue': !Sub '${ParentZoneStack}-HostedZoneId'}
Name: !Sub
- '${SubDomainNameWithDot}${HostedZoneName}'
- SubDomainNameWithDot: !Ref SubDomainNameWithDot
HostedZoneName: {'Fn::ImportValue': !Sub '${ParentZoneStack}-HostedZoneName'}
Type: A
RecordSetIPv6:
Condition: HasZoneAndMasterELBSchemeInternetFacing
Type: 'AWS::Route53::RecordSet'
Properties:
AliasTarget:
HostedZoneId: !GetAtt 'MasterELB.CanonicalHostedZoneID'
DNSName: !GetAtt 'MasterELB.DNSName'
HostedZoneId: {'Fn::ImportValue': !Sub '${ParentZoneStack}-HostedZoneId'}
Name: !Sub
- '${SubDomainNameWithDot}${HostedZoneName}'
- SubDomainNameWithDot: !Ref SubDomainNameWithDot
HostedZoneName: {'Fn::ImportValue': !Sub '${ParentZoneStack}-HostedZoneName'}
Type: AAAA
MasterELB:
Type: 'AWS::ElasticLoadBalancingV2::LoadBalancer'
Properties:
IpAddressType: !If [HasMasterELBSchemeInternal, 'ipv4', 'dualstack']
LoadBalancerAttributes:
- Key: 'idle_timeout.timeout_seconds'
Value: !Ref MasterLoadBalancerIdleTimeout
- Key: 'routing.http2.enabled'
Value: 'true'
- Key: 'access_logs.s3.enabled'
Value: !If [HasS3Bucket, 'true', 'false']
- !If [HasS3Bucket, {Key: 'access_logs.s3.prefix', Value: !Ref 'AWS::StackName'}, !Ref 'AWS::NoValue']
- !If [HasS3Bucket, {Key: 'access_logs.s3.bucket', Value: {'Fn::ImportValue': !Sub '${ParentS3StackAccessLog}-BucketName'}}, !Ref 'AWS::NoValue']
Scheme: !Ref MasterELBScheme
SecurityGroups:
- !Ref MasterELBSG
Subnets: !If
- HasMasterELBSchemeInternal
- - {'Fn::ImportValue': !Sub '${ParentVPCStack}-SubnetAPrivate'}
- {'Fn::ImportValue': !Sub '${ParentVPCStack}-SubnetBPrivate'}
- - {'Fn::ImportValue': !Sub '${ParentVPCStack}-SubnetAPublic'}
- {'Fn::ImportValue': !Sub '${ParentVPCStack}-SubnetBPublic'}
Tags:
- Key: Name
Value: 'jenkins-master'
MasterELBTargetGroup: # not monitored, but MasterELB is monitored!
Type: 'AWS::ElasticLoadBalancingV2::TargetGroup'
Properties:
HealthCheckIntervalSeconds: 30
HealthCheckPath: '/login'
HealthCheckPort: '8080'
HealthCheckProtocol: HTTP
HealthCheckTimeoutSeconds: 25
HealthyThresholdCount: 2
UnhealthyThresholdCount: 10
Matcher:
HttpCode: '200-299'
Port: 8080
Protocol: HTTP
Tags:
- Key: Name
Value: 'jenkins-master'
VpcId: {'Fn::ImportValue': !Sub '${ParentVPCStack}-VPC'}
TargetGroupAttributes:
- Key: 'deregistration_delay.timeout_seconds'
Value: '30'
MasterELBListener:
Type: 'AWS::ElasticLoadBalancingV2::Listener'
Properties:
DefaultActions:
- TargetGroupArn: !Ref MasterELBTargetGroup
Type: forward
LoadBalancerArn: !Ref MasterELB
Port: 80
Protocol: HTTP
MasterIP:
Type: 'AWS::IAM::InstanceProfile'
Properties:
Roles:
- !Ref MasterIAMRole
MasterIAMRole:
Type: 'AWS::IAM::Role'
Properties:
AssumeRolePolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Principal:
Service: 'ec2.amazonaws.com'
Action: 'sts:AssumeRole'
ManagedPolicyArns: !If [HasManagedPolicyArns, !Split [',', !Ref ManagedPolicyArns], !Ref 'AWS::NoValue']
PermissionsBoundary: !If [HasPermissionsBoundary, !Ref PermissionsBoundary, !Ref 'AWS::NoValue']
Policies:
- !If
- HasSystemsManagerAccess
- PolicyName: ssm
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- 'ssmmessages:*' # SSM Agent by https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-setting-up-messageAPIs.html
- 'ssm:UpdateInstanceInformation' # SSM agent by https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-setting-up-messageAPIs.html
- 'ec2messages:*' # SSM Session Manager by https://docs.aws.amazon.com/systems-manager/latest/userguide/systems-manager-setting-up-messageAPIs.html
Resource: '*'
- !Ref 'AWS::NoValue'
- PolicyName: cloudwatch
PolicyDocument:
Version: '2012-10-17'
Statement:
- Sid: write
Effect: Allow
Action: 'cloudwatch:PutMetricData'
Resource: '*'
- PolicyName: autoscaling
PolicyDocument:
Version: '2012-10-17'
Statement:
- Sid: write
Effect: Allow
Action: 'autoscaling:CompleteLifecycleAction'
Resource: '*'
- PolicyName: sqs
PolicyDocument:
Version: '2012-10-17'
Statement:
- Sid: write
Effect: Allow
Action:
- 'sqs:DeleteMessage'
- 'sqs:ReceiveMessage'
- 'sqs:ChangeMessageVisibility'
Resource: !GetAtt 'AgentTerminatingLifecycleHookQueue.Arn'
- PolicyName: logs
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- 'logs:CreateLogGroup'
- 'logs:CreateLogStream'
- 'logs:PutLogEvents'
- 'logs:DescribeLogStreams'
Resource: !GetAtt 'MasterLogs.Arn'
- PolicyName: sts
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action: 'sts:AssumeRole'
Resource: '*'
MasterIAMPolicySSHAccess:
Type: 'AWS::IAM::Policy'
Condition: HasIAMUserSSHAccess
Properties:
Roles:
- !Ref MasterIAMRole
PolicyName: iam
PolicyDocument:
Version: '2012-10-17'
Statement:
- Effect: Allow
Action:
- 'iam:ListUsers'
Resource:
- '*'
- Effect: Allow
Action:
- 'iam:ListSSHPublicKeys'
- 'iam:GetSSHPublicKey'
Resource:
- !Sub 'arn:aws:iam::${AWS::AccountId}:user/*'
MasterSG:
Type: 'AWS::EC2::SecurityGroup'
Properties:
GroupDescription: 'jenkins-master'
VpcId: {'Fn::ImportValue': !Sub '${ParentVPCStack}-VPC'}
SecurityGroupIngress:
- SourceSecurityGroupId: !Ref MasterELBSG
FromPort: 8080
ToPort: 8080
IpProtocol: tcp
- SourceSecurityGroupId: !Ref AgentSG
FromPort: 8080
ToPort: 8080
IpProtocol: tcp
- SourceSecurityGroupId: !Ref AgentSG
FromPort: 49817
ToPort: 49817
IpProtocol: tcp
MasterSGInSSHBastion:
Type: 'AWS::EC2::SecurityGroupIngress'
Condition: HasSSHBastionSecurityGroup
Properties:
GroupId: !Ref MasterSG
IpProtocol: tcp
FromPort: 22
ToPort: 22
SourceSecurityGroupId: {'Fn::ImportValue': !Sub '${ParentSSHBastionStack}-SecurityGroup'}
MasterSGInSSHWorld:
Type: 'AWS::EC2::SecurityGroupIngress'
Condition: HasNotSSHBastionSecurityGroup
Properties:
GroupId: !Ref MasterSG
IpProtocol: tcp
FromPort: 22
ToPort: 22
CidrIp: '0.0.0.0/0'
MasterLogs:
Type: 'AWS::Logs::LogGroup'
Properties:
RetentionInDays: !Ref MasterLogsRetentionInDays
MasterLaunchTemplate:
Type: 'AWS::EC2::LaunchTemplate'
Metadata:
'AWS::CloudFormation::Init':
configSets:
default: [awslogs, !If [HasIAMUserSSHAccess, ssh-access, !Ref 'AWS::NoValue'], mount, extras, epel, dependencies, install, setup, custom_before, run, custom_after]
awslogs:
packages:
yum:
awslogs: []
files:
'/etc/awslogs/awscli.conf':
content: !Sub |
[default]
region = ${AWS::Region}
[plugins]
cwlogs = cwlogs
mode: '000644'
owner: root
group: root
'/etc/awslogs/awslogs.conf':
content: !Sub |
[general]
state_file = /var/lib/awslogs/agent-state
[/var/log/amazon/ssm/amazon-ssm-agent.log]
datetime_format = %Y-%m-%d %H:%M:%S
file = /var/log/amazon/ssm/amazon-ssm-agent.log
log_stream_name = {instance_id}/var/log/amazon/ssm/amazon-ssm-agent.log
log_group_name = ${MasterLogs}
[/var/log/amazon/ssm/errors.log]
datetime_format = %Y-%m-%d %H:%M:%S
file = /var/log/amazon/ssm/errors.log
log_stream_name = {instance_id}/var/log/amazon/ssm/errors.log
log_group_name = ${MasterLogs}
[/var/log/audit/audit.log]
file = /var/log/audit/audit.log
log_stream_name = {instance_id}/var/log/audit/audit.log
log_group_name = ${MasterLogs}
[/var/log/awslogs.log]
datetime_format = %Y-%m-%d %H:%M:%S
file = /var/log/awslogs.log
log_stream_name = {instance_id}/var/log/awslogs.log
log_group_name = ${MasterLogs}
[/var/log/boot.log]
file = /var/log/boot.log
log_stream_name = {instance_id}/var/log/boot.log
log_group_name = ${MasterLogs}
[/var/log/cfn-hup.log]
datetime_format = %Y-%m-%d %H:%M:%S
file = /var/log/cfn-hup.log
log_stream_name = {instance_id}/var/log/cfn-hup.log
log_group_name = ${MasterLogs}
[/var/log/cfn-init-cmd.log]
datetime_format = %Y-%m-%d %H:%M:%S
file = /var/log/cfn-init-cmd.log
log_stream_name = {instance_id}/var/log/cfn-init-cmd.log
log_group_name = ${MasterLogs}
[/var/log/cfn-init.log]
datetime_format = %Y-%m-%d %H:%M:%S
file = /var/log/cfn-init.log
log_stream_name = {instance_id}/var/log/cfn-init.log
log_group_name = ${MasterLogs}
[/var/log/cfn-wire.log]
datetime_format = %Y-%m-%d %H:%M:%S
file = /var/log/cfn-wire.log
log_stream_name = {instance_id}/var/log/cfn-wire.log
log_group_name = ${MasterLogs}
[/var/log/cloud-init-output.log]
file = /var/log/cloud-init-output.log
log_stream_name = {instance_id}/var/log/cloud-init-output.log
log_group_name = ${MasterLogs}
[/var/log/cloud-init.log]
datetime_format = %b %d %H:%M:%S
file = /var/log/cloud-init.log
log_stream_name = {instance_id}/var/log/cloud-init.log
log_group_name = ${MasterLogs}
[/var/log/cron]
datetime_format = %b %d %H:%M:%S
file = /var/log/cron
log_stream_name = {instance_id}/var/log/cron
log_group_name = ${MasterLogs}
[/var/log/dmesg]
file = /var/log/dmesg
log_stream_name = {instance_id}/var/log/dmesg
log_group_name = ${MasterLogs}
[/var/log/grubby_prune_debug]
file = /var/log/grubby_prune_debug
log_stream_name = {instance_id}/var/log/grubby_prune_debug
log_group_name = ${MasterLogs}
[/var/log/maillog]
datetime_format = %b %d %H:%M:%S
file = /var/log/maillog
log_stream_name = {instance_id}/var/log/maillog
log_group_name = ${MasterLogs}
[/var/log/messages]
datetime_format = %b %d %H:%M:%S
file = /var/log/messages
log_stream_name = {instance_id}/var/log/messages
log_group_name = ${MasterLogs}
[/var/log/secure]
datetime_format = %b %d %H:%M:%S
file = /var/log/secure
log_stream_name = {instance_id}/var/log/secure
log_group_name = ${MasterLogs}
[/var/log/yum.log]
datetime_format = %b %d %H:%M:%S
file = /var/log/yum.log
log_stream_name = {instance_id}/var/log/yum.log
log_group_name = ${MasterLogs}
mode: '000644'
owner: root
group: root
'/etc/awslogs/config/efs.conf':
content: !Sub |
[/var/log/amazon/efs/mount.log]
datetime_format = %Y-%m-%d %H:%M:%S
file = /var/log/amazon/efs/mount.log
log_stream_name = {instance_id}/var/log/amazon/efs/mount.log
log_group_name = ${MasterLogs}
mode: '000644'
owner: root
group: root
'/etc/awslogs/config/jenkins-master.conf':
content: !Sub |
[/var/log/jenkins/jenkins.log]
datetime_format = %d %b %Y %H:%M:%S
multi_line_start_pattern = {datetime_format}
file = /var/log/jenkins/jenkins.log
log_stream_name = {instance_id}/var/log/jenkins/jenkins.log
log_group_name = ${MasterLogs}
mode: '000644'
owner: root
group: root
services:
sysvinit:
awslogsd:
enabled: true
ensureRunning: true
packages:
yum:
- awslogs
files:
- '/etc/awslogs/awslogs.conf'
- '/etc/awslogs/awscli.conf'
- '/etc/awslogs/config/efs.conf'
- '/etc/awslogs/config/jenkins-master.conf'
ssh-access:
files:
'/opt/authorized_keys_command.sh':
content: |
#!/bin/bash -e
if [ -z "$1" ]; then
exit 1
fi
UnsaveUserName="$1"
UnsaveUserName=${UnsaveUserName//".plus."/"+"}
UnsaveUserName=${UnsaveUserName//".equal."/"="}
UnsaveUserName=${UnsaveUserName//".comma."/","}
UnsaveUserName=${UnsaveUserName//".at."/"@"}
aws iam list-ssh-public-keys --user-name "$UnsaveUserName" --query "SSHPublicKeys[?Status == 'Active'].[SSHPublicKeyId]" --output text | while read -r KeyId; do
aws iam get-ssh-public-key --user-name "$UnsaveUserName" --ssh-public-key-id "$KeyId" --encoding SSH --query "SSHPublicKey.SSHPublicKeyBody" --output text
done
mode: '000755'
owner: root
group: root
'/opt/import_users.sh':
content: |
#!/bin/bash -e
aws iam list-users --query "Users[].[UserName]" --output text | while read User; do
SaveUserName="$User"
SaveUserName=${SaveUserName//"+"/".plus."}
SaveUserName=${SaveUserName//"="/".equal."}
SaveUserName=${SaveUserName//","/".comma."}
SaveUserName=${SaveUserName//"@"/".at."}
if [ "${#SaveUserName}" -le "32" ]; then
if ! id -u "$SaveUserName" >/dev/null 2>&1; then
#sudo will read each file in /etc/sudoers.d, skipping file names that end in ‘~’ or contain a ‘.’ character to avoid causing problems with package manager or editor temporary/backup files.
SaveUserFileName=$(echo "$SaveUserName" | tr "." " ")
/usr/sbin/useradd "$SaveUserName"
echo "$SaveUserName ALL=(ALL) NOPASSWD:ALL" > "/etc/sudoers.d/$SaveUserFileName"
fi
else
echo "Can not import IAM user ${SaveUserName}. User name is longer than 32 characters."
fi
done
mode: '000755'
owner: root
group: root
'/etc/cron.d/import_users':
content: |
*/10 * * * * root /opt/import_users.sh
mode: '000644'
owner: root
group: root
commands:
'a_configure_sshd_command':
command: 'sed -e ''/AuthorizedKeysCommand / s/^#*/#/'' -i /etc/ssh/sshd_config; echo -e ''\nAuthorizedKeysCommand /opt/authorized_keys_command.sh'' >> /etc/ssh/sshd_config'
test: '! grep -q ''^AuthorizedKeysCommand /opt/authorized_keys_command.sh'' /etc/ssh/sshd_config'
'b_configure_sshd_commanduser':
command: 'sed -e ''/AuthorizedKeysCommandUser / s/^#*/#/'' -i /etc/ssh/sshd_config; echo -e ''\nAuthorizedKeysCommandUser nobody'' >> /etc/ssh/sshd_config'
test: '! grep -q ''^AuthorizedKeysCommandUser nobody'' /etc/ssh/sshd_config'
'c_import_users':
command: './import_users.sh'
cwd: '/opt'
services:
sysvinit:
sshd:
enabled: true
ensureRunning: true
commands:
- 'a_configure_sshd_command'
- 'b_configure_sshd_commanduser'
mount:
packages:
yum:
'amazon-efs-utils': []
commands:
'a_groupadd':
command: 'groupadd -g 497 jenkins'
test: 'if grep -q jenkins: /etc/group; then exit 1; else exit 0; fi'
'b_useradd':
command: 'adduser -u 498 -g 497 -s /bin/false -d /var/lib/jenkins -M -c ''Jenkins Continuous Integration Server'' jenkins'
test: 'if grep -q jenkins: /etc/passwd; then exit 1; else exit 0; fi'
'c_mount':
command: !Sub 'mkdir /var/lib/jenkins && chown -R jenkins:jenkins /var/lib/jenkins && echo "${MasterStorage}:/ /var/lib/jenkins efs tls,_netdev 0 0" >> /etc/fstab && while ! (echo > /dev/tcp/${MasterStorage}.efs.${AWS::Region}.amazonaws.com/2049) >/dev/null 2>&1; do sleep 5; done && mount -a -t efs'
test: '[ ! -d /var/lib/jenkins ]'
extras:
commands:
'a_enable_docker':
command: 'amazon-linux-extras enable docker=18.06.1 && yum -y clean metadata'
test: "! grep -Fxq '[amzn2extra-docker]' /etc/yum.repos.d/amzn2-extras.repo"
'b_enable_epel':
command: 'amazon-linux-extras enable epel=7.11 && yum -y clean metadata'
test: "! grep -Fxq '[amzn2extra-epel]' /etc/yum.repos.d/amzn2-extras.repo"
'c_disable_log4j_hotpatch': # Jenkins was never affected
command: 'systemctl mask log4j-cve-2021-44228-hotpatch'
epel:
packages:
yum:
'epel-release': []
dependencies:
packages:
yum:
'java-11-amazon-corretto-headless': []
'daemonize': []
ruby: []
rubygems:
daemons: ['1.3.1']
files:
'/etc/systemd/system/jenkins.service.d/timeout.conf':
content: |
[Service]
TimeoutStartSec=300
mode: '000644'
owner: root
group: root
commands:
a_gem_install_aws_eventstream: # workaround for https://github.com/aws/aws-sdk-ruby/pull/2573#issuecomment-913984611
command: 'gem install aws-eventstream -v 1.1.1'
test: '! gem list aws-eventstream -i -v 1.1.1'
b_gem_install_aws_partitions: # workaround for https://github.com/aws/aws-sdk-ruby/pull/2573#issuecomment-913984611