forked from Azure/AKS-Construction
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.bicep
1634 lines (1403 loc) · 54.3 KB
/
main.bicep
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
@minLength(2)
@description('The location to use for the deployment. defaults to Resource Groups location.')
param location string = resourceGroup().location
@minLength(3)
@maxLength(20)
@description('Used to name all resources')
param resourceName string
/*
Resource sections
1. Networking
2. DNS
3. Key Vault
4. Container Registry
5. Firewall
6. Application Gateway
7. AKS
8. Monitoring / Log Analytics
9. Deployment for telemetry
*/
/*.__ __. _______ .___________.____ __ ____ ______ .______ __ ___ __ .__ __. _______
| \ | | | ____|| |\ \ / \ / / / __ \ | _ \ | |/ / | | | \ | | / _____|
| \| | | |__ `---| |----` \ \/ \/ / | | | | | |_) | | ' / | | | \| | | | __
| . ` | | __| | | \ / | | | | | / | < | | | . ` | | | |_ |
| |\ | | |____ | | \ /\ / | `--' | | |\ \----.| . \ | | | |\ | | |__| |
|__| \__| |_______| |__| \__/ \__/ \______/ | _| `._____||__|\__\ |__| |__| \__| \______| */
//Networking can either be one of: custom / byo / default
@description('Are you providing your own vNet CIDR blocks')
param custom_vnet bool = false
@description('Full resource id path of an existing subnet to use for AKS')
param byoAKSSubnetId string = ''
@description('Full resource id path of an existing subnet to use for Application Gateway')
param byoAGWSubnetId string = ''
//--- Custom, BYO networking and PrivateApiZones requires BYO AKS User Identity
var createAksUai = custom_vnet || !empty(byoAKSSubnetId) || !empty(dnsApiPrivateZoneId) || keyVaultKmsCreateAndPrereqs || !empty(keyVaultKmsByoKeyId)
resource aksUai 'Microsoft.ManagedIdentity/userAssignedIdentities@2022-01-31-preview' = if (createAksUai) {
name: 'id-aks-${resourceName}'
location: location
}
//----------------------------------------------------- BYO Vnet
var existingAksVnetRG = !empty(byoAKSSubnetId) ? (length(split(byoAKSSubnetId, '/')) > 4 ? split(byoAKSSubnetId, '/')[4] : '') : ''
module aksnetcontrib './aksnetcontrib.bicep' = if (!empty(byoAKSSubnetId) && createAksUai) {
name: 'addAksNetContributor'
scope: resourceGroup(existingAksVnetRG)
params: {
byoAKSSubnetId: byoAKSSubnetId
user_identity_principalId: createAksUai ? aksUai.properties.principalId : ''
rbacAssignmentScope: uaiNetworkScopeRbac
}
}
//------------------------------------------------------ Create custom vnet
@minLength(9)
@maxLength(18)
@description('The address range for the custom vnet')
param vnetAddressPrefix string = '10.240.0.0/16'
@minLength(9)
@maxLength(18)
@description('The address range for AKS in your custom vnet')
param vnetAksSubnetAddressPrefix string = '10.240.0.0/22'
@minLength(9)
@maxLength(18)
@description('The address range for the App Gateway in your custom vnet')
param vnetAppGatewaySubnetAddressPrefix string = '10.240.5.0/24'
@minLength(9)
@maxLength(18)
@description('The address range for the ACR in your custom vnet')
param acrAgentPoolSubnetAddressPrefix string = '10.240.4.64/26'
@minLength(9)
@maxLength(18)
@description('The address range for Azure Bastion in your custom vnet')
param bastionSubnetAddressPrefix string = '10.240.4.128/26'
@minLength(9)
@maxLength(18)
@description('The address range for private link in your custom vnet')
param privateLinkSubnetAddressPrefix string = '10.240.4.192/26'
@minLength(9)
@maxLength(18)
@description('The address range for Azure Firewall in your custom vnet')
param vnetFirewallSubnetAddressPrefix string = '10.240.50.0/24'
@minLength(9)
@maxLength(18)
@description('The address range for Azure Firewall Management in your custom vnet')
param vnetFirewallManagementSubnetAddressPrefix string = '10.240.51.0/26'
@description('Enable support for private links (required custom_vnet)')
param privateLinks bool = false
@description('Enable support for ACR private pool')
param acrPrivatePool bool = false
@description('Deploy Azure Bastion to your vnet. (works with Custom Networking only, not BYO)')
param bastion bool = false
@description('Deploy NSGs to your vnet subnets. (works with Custom Networking only, not BYO)')
param CreateNetworkSecurityGroups bool = false
@description('Configure Flow Logs for Network Security Groups in the NetworkWatcherRG resource group. Requires Contributor RBAC on NetworkWatcherRG and Reader on Subscription.')
param CreateNetworkSecurityGroupFlowLogs bool = false
module network './network.bicep' = if (custom_vnet) {
name: 'network'
params: {
resourceName: resourceName
location: location
networkPluginIsKubenet: networkPlugin=='kubenet'
vnetAddressPrefix: vnetAddressPrefix
aksPrincipleId: createAksUai ? aksUai.properties.principalId : ''
vnetAksSubnetAddressPrefix: vnetAksSubnetAddressPrefix
ingressApplicationGateway: ingressApplicationGateway
vnetAppGatewaySubnetAddressPrefix: vnetAppGatewaySubnetAddressPrefix
azureFirewalls: azureFirewalls
vnetFirewallSubnetAddressPrefix: vnetFirewallSubnetAddressPrefix
vnetFirewallManagementSubnetAddressPrefix: vnetFirewallManagementSubnetAddressPrefix
privateLinks: privateLinks
privateLinkSubnetAddressPrefix: privateLinkSubnetAddressPrefix
privateLinkAcrId: privateLinks && !empty(registries_sku) ? acr.id : ''
privateLinkAkvId: privateLinks && keyVaultCreate ? kv.outputs.keyVaultId : ''
acrPrivatePool: acrPrivatePool
acrAgentPoolSubnetAddressPrefix: acrAgentPoolSubnetAddressPrefix
bastion: bastion
bastionSubnetAddressPrefix: bastionSubnetAddressPrefix
availabilityZones: availabilityZones
workspaceName: createLaw ? aks_law.name : ''
workspaceResourceGroupName: createLaw ? resourceGroup().name : ''
networkSecurityGroups: CreateNetworkSecurityGroups
CreateNsgFlowLogs: CreateNetworkSecurityGroups && CreateNetworkSecurityGroupFlowLogs
ingressApplicationGatewayPublic: empty(privateIpApplicationGateway)
natGateway: createNatGateway
natGatewayIdleTimeoutMins: natGwIdleTimeout
natGatewayPublicIps: natGwIpCount
}
}
output CustomVnetId string = custom_vnet ? network.outputs.vnetId : ''
output CustomVnetPrivateLinkSubnetId string = custom_vnet ? network.outputs.privateLinkSubnetId : ''
var aksSubnetId = custom_vnet ? network.outputs.aksSubnetId : byoAKSSubnetId
var appGwSubnetId = ingressApplicationGateway ? (custom_vnet ? network.outputs.appGwSubnetId : byoAGWSubnetId) : ''
/*______ .__ __. _______. ________ ______ .__ __. _______ _______.
| \ | \ | | / | | / / __ \ | \ | | | ____| / |
| .--. || \| | | (----` `---/ / | | | | | \| | | |__ | (----`
| | | || . ` | \ \ / / | | | | | . ` | | __| \ \
| '--' || |\ | .----) | / /----.| `--' | | |\ | | |____ .----) |
|_______/ |__| \__| |_______/ /________| \______/ |__| \__| |_______||_______/ */
@description('The full Azure resource ID of the DNS zone to use for the AKS cluster')
param dnsZoneId string = ''
var isDnsZonePrivate = !empty(dnsZoneId) ? split(dnsZoneId, '/')[7] == 'privateDnsZones' : false
module dnsZone './dnsZoneRbac.bicep' = if (!empty(dnsZoneId)) {
name: 'addDnsContributor'
params: {
dnsZoneId: dnsZoneId
vnetId: isDnsZonePrivate ? (!empty(byoAKSSubnetId) ? split(byoAKSSubnetId, '/subnets')[0] : (custom_vnet ? network.outputs.vnetId : '')) : ''
principalId: any(aks.properties.identityProfile.kubeletidentity).objectId
}
}
/*__ __ _______ ____ ____ ____ ____ ___ __ __ __ .___________.
| |/ / | ____|\ \ / / \ \ / / / \ | | | | | | | |
| ' / | |__ \ \/ / \ \/ / / ^ \ | | | | | | `---| |----`
| < | __| \_ _/ \ / / /_\ \ | | | | | | | |
| . \ | |____ | | \ / / _____ \ | `--' | | `----. | |
|__|\__\ |_______| |__| \__/ /__/ \__\ \______/ |_______| |__| */
@description('Creates a KeyVault')
param keyVaultCreate bool = false
@description('If soft delete protection is enabled')
param keyVaultSoftDelete bool = true
@description('If purge protection is enabled')
param keyVaultPurgeProtection bool = true
@description('Add IP to KV firewall allow-list')
param keyVaultIPAllowlist array = []
@description('Installs the AKS KV CSI provider')
param keyVaultAksCSI bool = false
@description('Rotation poll interval for the AKS KV CSI provider')
param keyVaultAksCSIPollInterval string = '2m'
@description('Creates a KeyVault for application secrets (eg. CSI)')
module kv 'keyvault.bicep' = if(keyVaultCreate) {
name: 'keyvaultApps'
params: {
resourceName: resourceName
keyVaultPurgeProtection: keyVaultPurgeProtection
keyVaultSoftDelete: keyVaultSoftDelete
keyVaultIPAllowlist: keyVaultIPAllowlist
location: location
privateLinks: privateLinks
}
}
@description('The principal ID of the user or service principal that requires access to the Key Vault. Set automatedDeployment to toggle between user and service prinicpal')
param keyVaultOfficerRolePrincipalId string = ''
var keyVaultOfficerRolePrincipalIds = [
keyVaultOfficerRolePrincipalId
]
@description('Parsing an array with union ensures that duplicates are removed, which is great when dealing with highly conditional elements')
var rbacSecretUserSps = union([deployAppGw && appgwKVIntegration ? appGwIdentity.properties.principalId : ''],[keyVaultAksCSI ? aks.properties.addonProfiles.azureKeyvaultSecretsProvider.identity.objectId : ''])
@description('A seperate module is used for RBAC to avoid delaying the KeyVault creation and causing a circular reference.')
module kvRbac 'keyvaultrbac.bicep' = if (keyVaultCreate) {
name: 'KeyVaultAppsRbac'
params: {
keyVaultName: keyVaultCreate ? kv.outputs.keyVaultName : ''
//service principals
rbacSecretUserSps: rbacSecretUserSps
rbacSecretOfficerSps: !empty(keyVaultOfficerRolePrincipalId) && automatedDeployment ? keyVaultOfficerRolePrincipalIds : []
rbacCertOfficerSps: !empty(keyVaultOfficerRolePrincipalId) && automatedDeployment ? keyVaultOfficerRolePrincipalIds : []
//users
rbacSecretOfficerUsers: !empty(keyVaultOfficerRolePrincipalId) && !automatedDeployment ? keyVaultOfficerRolePrincipalIds : []
rbacCertOfficerUsers: !empty(keyVaultOfficerRolePrincipalId) && !automatedDeployment ? keyVaultOfficerRolePrincipalIds : []
}
}
output keyVaultName string = keyVaultCreate ? kv.outputs.keyVaultName : ''
output keyVaultId string = keyVaultCreate ? kv.outputs.keyVaultId : ''
/* KeyVault for KMS Etcd*/
@description('Enable encryption at rest for Kubernetes etcd data')
param keyVaultKmsCreate bool = false
@description('Bring an existing Key from an existing Key Vault')
param keyVaultKmsByoKeyId string = ''
@description('The resource group for the existing KMS Key Vault')
param keyVaultKmsByoRG string = resourceGroup().name
@description('The PrincipalId of the deploying user, which is necessary when creating a Kms Key')
param keyVaultKmsOfficerRolePrincipalId string = ''
@description('The extracted name of the existing Key Vault')
var keyVaultKmsByoName = !empty(keyVaultKmsByoKeyId) ? split(split(keyVaultKmsByoKeyId,'/')[2],'.')[0] : ''
@description('The deployment delay to introduce when creating a new keyvault for kms key')
var kmsRbacWaitSeconds=30
@description('This indicates if the deploying user has provided their PrincipalId in order for the key to be created')
var keyVaultKmsCreateAndPrereqs = keyVaultKmsCreate && !empty(keyVaultKmsOfficerRolePrincipalId) && privateLinks == false
resource kvKmsByo 'Microsoft.KeyVault/vaults@2021-11-01-preview' existing = if(!empty(keyVaultKmsByoName)) {
name: keyVaultKmsByoName
scope: resourceGroup(keyVaultKmsByoRG)
}
@description('Creates a new Key vault for a new KMS Key')
module kvKms 'keyvault.bicep' = if(keyVaultKmsCreateAndPrereqs) {
name: 'keyvaultKms-${resourceName}'
params: {
resourceName: 'kms${resourceName}'
keyVaultPurgeProtection: keyVaultPurgeProtection
keyVaultSoftDelete: keyVaultSoftDelete
location: location
privateLinks: privateLinks
//aksUaiObjectId: aksUai.properties.principalId
}
}
module kvKmsCreatedRbac 'keyvaultrbac.bicep' = if(keyVaultKmsCreateAndPrereqs) {
name: 'keyvaultKmsRbacs-${resourceName}'
params: {
keyVaultName: keyVaultKmsCreate ? kvKms.outputs.keyVaultName : ''
//We can't create a kms kv and key and do privatelink. Private Link is a BYO scenario
// rbacKvContributorSps : [
// createAksUai && privateLinks ? aksUai.properties.principalId : ''
// ]
//This allows the Aks Cluster to access the key vault key
rbacCryptoUserSps: [
createAksUai ? aksUai.properties.principalId : ''
]
//This allows the Deploying user to create the key vault key
rbacCryptoOfficerUsers: [
!empty(keyVaultKmsOfficerRolePrincipalId) && !automatedDeployment ? keyVaultKmsOfficerRolePrincipalId : ''
]
//This allows the Deploying sp to create the key vault key
rbacCryptoOfficerSps: [
!empty(keyVaultKmsOfficerRolePrincipalId) && automatedDeployment ? keyVaultKmsOfficerRolePrincipalId : ''
]
}
}
module kvKmsByoRbac 'keyvaultrbac.bicep' = if(!empty(keyVaultKmsByoKeyId)) {
name: 'keyvaultKmsByoRbacs-${resourceName}'
scope: resourceGroup(keyVaultKmsByoRG)
params: {
keyVaultName: kvKmsByo.name
//Contribuor allows AKS to create the private link
rbacKvContributorSps : [
createAksUai && privateLinks ? aksUai.properties.principalId : ''
]
//This allows the Aks Cluster to access the key vault key
rbacCryptoUserSps: [
createAksUai ? aksUai.properties.principalId : ''
]
}
}
@description('It can take time for the RBAC to propagate, this delays the deployment to avoid this problem')
module waitForKmsRbac 'br/public:deployment-scripts/wait:1.0.1' = if(keyVaultKmsCreateAndPrereqs && kmsRbacWaitSeconds>0) {
name: 'keyvaultKmsRbac-waits-${resourceName}'
params: {
waitSeconds: kmsRbacWaitSeconds
location: location
}
dependsOn: [
kvKmsCreatedRbac
]
}
@description('Adding a key to the keyvault... We can only do this for public key vaults')
module kvKmsKey 'keyvaultkey.bicep' = if(keyVaultKmsCreateAndPrereqs) {
name: 'keyvaultKmsKeys-${resourceName}'
params: {
keyVaultName: keyVaultKmsCreateAndPrereqs ? kvKms.outputs.keyVaultName : ''
}
dependsOn: [waitForKmsRbac]
}
var azureKeyVaultKms = {
securityProfile : {
azureKeyVaultKms : {
enabled: keyVaultKmsCreateAndPrereqs || !empty(keyVaultKmsByoKeyId)
keyId: keyVaultKmsCreateAndPrereqs ? kvKmsKey.outputs.keyVaultKmsKeyUri : !empty(keyVaultKmsByoKeyId) ? keyVaultKmsByoKeyId : ''
keyVaultNetworkAccess: privateLinks ? 'private' : 'public'
keyVaultResourceId: privateLinks && !empty(keyVaultKmsByoKeyId) ? kvKmsByo.id : ''
}
}
}
@description('The name of the Kms Key Vault')
output keyVaultKmsName string = keyVaultKmsCreateAndPrereqs ? kvKms.outputs.keyVaultName : !empty(keyVaultKmsByoKeyId) ? keyVaultKmsByoName : ''
@description('Indicates if the user has supplied all the correct parameter to use a AKSC Created KMS')
output kmsCreatePrerequisitesMet bool = keyVaultKmsCreateAndPrereqs
/* ___ ______ .______
/ \ / | | _ \
/ ^ \ | ,----' | |_) |
/ /_\ \ | | | /
/ _____ \ __| `----. __ | |\ \----. __
/__/ \__\ (__)\______|(__)| _| `._____|(__)*/
@allowed([
''
'Basic'
'Standard'
'Premium'
])
@description('The SKU to use for the Container Registry')
param registries_sku string = ''
@description('Enable the ACR Content Trust Policy, SKU must be set to Premium')
param enableACRTrustPolicy bool = false
var acrContentTrustEnabled = enableACRTrustPolicy && registries_sku == 'Premium' ? 'enabled' : 'disabled'
//param enableACRZoneRedundancy bool = true
var acrZoneRedundancyEnabled = !empty(availabilityZones) && registries_sku == 'Premium' ? 'Enabled' : 'Disabled'
@description('Enable removing of untagged manifests from ACR')
param acrUntaggedRetentionPolicyEnabled bool = false
@description('The number of days to retain untagged manifests for')
param acrUntaggedRetentionPolicy int = 30
var acrName = 'cr${replace(resourceName, '-', '')}${uniqueString(resourceGroup().id, resourceName)}'
resource acr 'Microsoft.ContainerRegistry/registries@2021-06-01-preview' = if (!empty(registries_sku)) {
name: acrName
location: location
sku: {
#disable-next-line BCP036 //Disabling validation of this parameter to cope with empty string to indicate no ACR required.
name: registries_sku
}
properties: {
policies: {
trustPolicy: enableACRTrustPolicy ? {
status: acrContentTrustEnabled
type: 'Notary'
} : {}
retentionPolicy: acrUntaggedRetentionPolicyEnabled ? {
status: 'enabled'
days: acrUntaggedRetentionPolicy
} : json('null')
}
publicNetworkAccess: privateLinks /* && empty(acrIPWhitelist)*/ ? 'Disabled' : 'Enabled'
zoneRedundancy: acrZoneRedundancyEnabled
/*
networkRuleSet: {
defaultAction: 'Deny'
ipRules: empty(acrIPWhitelist) ? [] : [
{
action: 'Allow'
value: acrIPWhitelist
}
]
virtualNetworkRules: []
}
*/
}
}
output containerRegistryName string = !empty(registries_sku) ? acr.name : ''
output containerRegistryId string = !empty(registries_sku) ? acr.id : ''
resource acrDiags 'Microsoft.Insights/diagnosticSettings@2021-05-01-preview' = if (createLaw && !empty(registries_sku)) {
name: 'acrDiags'
scope: acr
properties: {
workspaceId:aks_law.id
logs: [
{
category: 'ContainerRegistryRepositoryEvents'
enabled: true
}
{
category: 'ContainerRegistryLoginEvents'
enabled: true
}
]
metrics: [
{
category: 'AllMetrics'
enabled: true
timeGrain: 'PT1M'
}
]
}
}
//resource acrPool 'Microsoft.ContainerRegistry/registries/agentPools@2019-06-01-preview' = if (custom_vnet && (!empty(registries_sku)) && privateLinks && acrPrivatePool) {
module acrPool 'acragentpool.bicep' = if (custom_vnet && (!empty(registries_sku)) && privateLinks && acrPrivatePool) {
name: 'acrprivatepool'
params: {
acrName: acr.name
acrPoolSubnetId: custom_vnet ? network.outputs.acrPoolSubnetId : ''
location: location
}
}
var AcrPullRole = subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '7f951dda-4ed3-4680-a7ca-43fe172d538d')
var KubeletObjectId = any(aks.properties.identityProfile.kubeletidentity).objectId
resource aks_acr_pull 'Microsoft.Authorization/roleAssignments@2022-04-01' = if (!empty(registries_sku)) {
scope: acr // Use when specifying a scope that is different than the deployment scope
name: guid(aks.id, 'Acr' , AcrPullRole)
properties: {
roleDefinitionId: AcrPullRole
principalType: 'ServicePrincipal'
principalId: KubeletObjectId
}
}
var AcrPushRole = subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '8311e382-0749-4cb8-b61a-304f252e45ec')
@description('The principal ID of the service principal to assign the push role to the ACR')
param acrPushRolePrincipalId string = ''
resource aks_acr_push 'Microsoft.Authorization/roleAssignments@2022-04-01' = if (!empty(registries_sku) && !empty(acrPushRolePrincipalId)) {
scope: acr // Use when specifying a scope that is different than the deployment scope
name: guid(aks.id, 'Acr' , AcrPushRole)
properties: {
roleDefinitionId: AcrPushRole
principalType: automatedDeployment ? 'ServicePrincipal' : 'User'
principalId: acrPushRolePrincipalId
}
}
param imageNames array = []
module acrImport 'br/public:deployment-scripts/import-acr:2.0.1' = if (!empty(registries_sku) && !empty(imageNames)) {
name: 'testAcrImportMulti'
params: {
acrName: acr.name
location: location
images: imageNames
}
}
/*______ __ .______ _______ ____ __ ____ ___ __ __
| ____|| | | _ \ | ____|\ \ / \ / / / \ | | | |
| |__ | | | |_) | | |__ \ \/ \/ / / ^ \ | | | |
| __| | | | / | __| \ / / /_\ \ | | | |
| | | | | |\ \----.| |____ \ /\ / / _____ \ | `----.| `----.
|__| |__| | _| `._____||_______| \__/ \__/ /__/ \__\ |_______||_______|*/
@description('Create an Azure Firewall, requires custom_vnet')
param azureFirewalls bool = false
@description('Add application rules to the firewall for certificate management.')
param certManagerFW bool = false
// @allowed([
// 'AllowAllIn'
// 'AllowAcrSubnetIn'
// ''
// ])
// @description('Allow Http traffic (80/443) into AKS from specific sources')
// param inboundHttpFW string = ''
@allowed([
'Basic'
'Premium'
'Standard'
])
param azureFirewallSku string = 'Standard'
module firewall './firewall.bicep' = if (azureFirewalls && custom_vnet) {
name: 'firewall'
params: {
resourceName: resourceName
location: location
workspaceDiagsId: createLaw ? aks_law.id : ''
fwSubnetId: azureFirewalls && custom_vnet ? network.outputs.fwSubnetId : ''
fwSku: azureFirewallSku
fwManagementSubnetId: azureFirewalls && custom_vnet && azureFirewallSku=='Basic' ? network.outputs.fwMgmtSubnetId : ''
vnetAksSubnetAddressPrefix: vnetAksSubnetAddressPrefix
certManagerFW: certManagerFW
appDnsZoneName: !empty(dnsZoneId) ? split(dnsZoneId, '/')[8] : ''
acrPrivatePool: acrPrivatePool
acrAgentPoolSubnetAddressPrefix: acrAgentPoolSubnetAddressPrefix
// inboundHttpFW: inboundHttpFW
availabilityZones: availabilityZones
}
}
/* ___ .______ .______ _______ ____ __ ____
/ \ | _ \ | _ \ / _____|\ \ / \ / /
/ ^ \ | |_) | | |_) | | | __ \ \/ \/ /
/ /_\ \ | ___/ | ___/ | | |_ | \ /
/ _____ \ | | | | __ | |__| | \ /\ / __
/__/ \__\ | _| | _| (__) \______| \__/ \__/ (__)*/
@description('Create an Application Gateway')
param ingressApplicationGateway bool = false
@description('The number of applciation gateway instances')
param appGWcount int = 2
@description('The maximum number of application gateway instances')
param appGWmaxCount int = 0
@maxLength(15)
@description('A known private ip in the Application Gateway subnet range to be allocated for internal traffic')
param privateIpApplicationGateway string = ''
@description('Enable key vault integration for application gateway')
param appgwKVIntegration bool = false
@allowed([
'Standard_v2'
'WAF_v2'
])
@description('The SKU for AppGw')
param appGWsku string = 'WAF_v2'
@description('Enable the WAF Firewall, valid for WAF_v2 SKUs')
param appGWenableFirewall bool = true
var deployAppGw = ingressApplicationGateway && (custom_vnet || !empty(byoAGWSubnetId))
var appGWenableWafFirewall = appGWsku=='Standard_v2' ? false : appGWenableFirewall
// If integrating App Gateway with KeyVault, create a Identity App Gateway will use to access keyvault
// 'identity' is always created (adding: "|| deployAppGw") until this is fixed:
// https://github.com/Azure/bicep/issues/387#issuecomment-885671296
resource appGwIdentity 'Microsoft.ManagedIdentity/userAssignedIdentities@2018-11-30' = if (deployAppGw) {
name: 'id-appgw-${resourceName}'
location: location
}
var appgwName = 'agw-${resourceName}'
var appgwResourceId = deployAppGw ? resourceId('Microsoft.Network/applicationGateways', '${appgwName}') : ''
resource appgwpip 'Microsoft.Network/publicIPAddresses@2021-02-01' = if (deployAppGw) {
name: 'pip-agw-${resourceName}'
location: location
sku: {
name: 'Standard'
}
zones: !empty(availabilityZones) ? availabilityZones : []
properties: {
publicIPAllocationMethod: 'Static'
}
}
var frontendPublicIpConfig = {
properties: {
publicIPAddress: {
id: appgwpip.id
}
}
name: 'appGatewayFrontendIP'
}
var frontendPrivateIpConfig = {
properties: {
privateIPAllocationMethod: 'Static'
privateIPAddress: privateIpApplicationGateway
subnet: {
id: appGwSubnetId
}
}
name: 'appGatewayPrivateIP'
}
@allowed([
'Prevention'
'Detection'
])
param appGwFirewallMode string = 'Prevention'
var appGwFirewallConfigOwasp = {
enabled: appGWenableWafFirewall
firewallMode: appGwFirewallMode
ruleSetType: 'OWASP'
ruleSetVersion: '3.2'
requestBodyCheck: true
maxRequestBodySizeInKb: 128
disabledRuleGroups: []
}
var appGWskuObj = union({
name: appGWsku
tier: appGWsku
}, appGWmaxCount == 0 ? {
capacity: appGWcount
} : {})
// ugh, need to create a variable with the app gateway properies, because of the conditional key 'autoscaleConfiguration'
var appgwProperties = union({
sku: appGWskuObj
sslPolicy: {
policyType: 'Predefined'
policyName: 'AppGwSslPolicy20170401S'
}
webApplicationFirewallConfiguration: appGWenableWafFirewall ? appGwFirewallConfigOwasp : json('null')
gatewayIPConfigurations: [
{
name: 'besubnet'
properties: {
subnet: {
id: appGwSubnetId
}
}
}
]
frontendIPConfigurations: empty(privateIpApplicationGateway) ? array(frontendPublicIpConfig) : concat(array(frontendPublicIpConfig), array(frontendPrivateIpConfig))
frontendPorts: [
{
name: 'appGatewayFrontendPort'
properties: {
port: 80
}
}
]
backendAddressPools: [
{
name: 'defaultaddresspool'
}
]
backendHttpSettingsCollection: [
{
name: 'defaulthttpsetting'
properties: {
port: 80
protocol: 'Http'
cookieBasedAffinity: 'Disabled'
requestTimeout: 30
pickHostNameFromBackendAddress: true
}
}
]
httpListeners: [
{
name: 'hlisten'
properties: {
frontendIPConfiguration: {
id: empty(privateIpApplicationGateway) ? '${appgwResourceId}/frontendIPConfigurations/appGatewayFrontendIP' : '${appgwResourceId}/frontendIPConfigurations/appGatewayPrivateIP'
}
frontendPort: {
id: '${appgwResourceId}/frontendPorts/appGatewayFrontendPort'
}
protocol: 'Http'
}
}
]
requestRoutingRules: [
{
name: 'appGwRoutingRuleName'
properties: {
ruleType: 'Basic'
httpListener: {
id: '${appgwResourceId}/httpListeners/hlisten'
}
backendAddressPool: {
id: '${appgwResourceId}/backendAddressPools/defaultaddresspool'
}
backendHttpSettings: {
id: '${appgwResourceId}/backendHttpSettingsCollection/defaulthttpsetting'
}
}
}
]
}, appGWmaxCount > 0 ? {
autoscaleConfiguration: {
minCapacity: appGWcount
maxCapacity: appGWmaxCount
}
} : {})
// 'identity' is always set until this is fixed: https://github.com/Azure/bicep/issues/387#issuecomment-885671296
resource appgw 'Microsoft.Network/applicationGateways@2021-02-01' = if (deployAppGw) {
name: appgwName
location: location
zones: !empty(availabilityZones) ? availabilityZones : []
identity: {
type: 'UserAssigned'
userAssignedIdentities: {
'${appGwIdentity.id}': {}
}
}
properties: appgwProperties
}
var contributor = subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'b24988ac-6180-42a0-ab88-20f7382dd24c')
// https://docs.microsoft.com/en-us/azure/role-based-access-control/role-assignments-template#new-service-principal
// AGIC's identity requires "Contributor" permission over Application Gateway.
resource appGwAGICContrib 'Microsoft.Authorization/roleAssignments@2022-04-01' = if (ingressApplicationGateway && deployAppGw) {
scope: appgw
name: guid(aks.id, 'Agic', contributor)
properties: {
roleDefinitionId: contributor
principalType: 'ServicePrincipal'
principalId: aks.properties.addonProfiles.ingressApplicationGateway.identity.objectId
}
}
// AGIC's identity requires "Reader" permission over Application Gateway's resource group.
var reader = subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'acdd72a7-3385-48ef-bd42-f606fba81ae7')
resource appGwAGICRGReader 'Microsoft.Authorization/roleAssignments@2022-04-01' = if (ingressApplicationGateway && deployAppGw) {
scope: resourceGroup()
name: guid(aks.id, 'Agic', reader)
properties: {
roleDefinitionId: reader
principalType: 'ServicePrincipal'
principalId: aks.properties.addonProfiles.ingressApplicationGateway.identity.objectId
}
}
// AGIC's identity requires "Managed Identity Operator" permission over the user assigned identity of Application Gateway.
var managedIdentityOperator = subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'f1a07417-d97a-45cb-824c-7a7467783830')
resource appGwAGICMIOp 'Microsoft.Authorization/roleAssignments@2022-04-01' = if (ingressApplicationGateway && deployAppGw) {
scope: appGwIdentity
name: guid(aks.id, 'Agic', managedIdentityOperator)
properties: {
roleDefinitionId: managedIdentityOperator
principalType: 'ServicePrincipal'
principalId: aks.properties.addonProfiles.ingressApplicationGateway.identity.objectId
}
}
// AppGW Diagnostics
resource appgw_Diag 'Microsoft.Insights/diagnosticSettings@2021-05-01-preview' = if (createLaw && deployAppGw) {
scope: appgw
name: 'appgwDiag'
properties: {
workspaceId: aks_law.id
logs: [
{
category: 'ApplicationGatewayAccessLog'
enabled: true
}
{
category: 'ApplicationGatewayPerformanceLog'
enabled: true
}
{
category: 'ApplicationGatewayFirewallLog'
enabled: true
}
]
}
}
// =================================================
// Prevent error: AGIC Identity needs atleast has 'Contributor' access to Application Gateway and 'Reader' access to Application Gateway's Resource Group
output ApplicationGatewayName string = deployAppGw ? appgw.name : ''
/*_ ___ __ __ .______ _______ .______ .__ __. _______ .___________. _______ _______.
| |/ / | | | | | _ \ | ____|| _ \ | \ | | | ____|| || ____| / |
| ' / | | | | | |_) | | |__ | |_) | | \| | | |__ `---| |----`| |__ | (----`
| < | | | | | _ < | __| | / | . ` | | __| | | | __| \ \
| . \ | `--' | | |_) | | |____ | |\ \----.| |\ | | |____ | | | |____ .----) |
|__|\__\ \______/ |______/ |_______|| _| `._____||__| \__| |_______| |__| |_______||_______/ */
@description('DNS prefix. Defaults to {resourceName}-dns')
param dnsPrefix string = '${resourceName}-dns'
@description('Kubernetes Version')
param kubernetesVersion string = '1.24.9'
@description('Enable Azure AD integration on AKS')
param enable_aad bool = false
@description('The ID of the Azure AD tenant')
param aad_tenant_id string = ''
@description('Create, and use a new Log Analytics workspace for AKS logs')
param omsagent bool = false
@description('Enables the ContainerLogsV2 table to be of type Basic')
param containerLogsV2BasicLogs bool = false
@description('Enable RBAC using AAD')
param enableAzureRBAC bool = false
@description('Enables Kubernetes Event-driven Autoscaling (KEDA)')
param kedaAddon bool = false
@description('Enables Open Service Mesh')
param openServiceMeshAddon bool = false
@description('Enables SGX Confidential Compute plugin')
param sgxPlugin bool = false
@description('Enables the Blob CSI driver')
param blobCSIDriver bool = false
@description('Enables the File CSI driver')
param fileCSIDriver bool = true
@description('Enables the Disk CSI driver')
param diskCSIDriver bool = true
@allowed([
'none'
'patch'
'stable'
'rapid'
'node-image'
])
@description('AKS upgrade channel')
param upgradeChannel string = 'none'
@allowed([
'Ephemeral'
'Managed'
])
@description('OS disk type')
param osDiskType string = 'Ephemeral'
@description('VM SKU')
param agentVMSize string = 'Standard_DS3_v2'
@description('Disk size in GB')
param osDiskSizeGB int = 0
@description('The number of agents for the user node pool')
param agentCount int = 3
@description('The maximum number of nodes for the user node pool')
param agentCountMax int = 0
var autoScale = agentCountMax > agentCount
@minLength(3)
@maxLength(12)
@description('Name for user node pool')
param nodePoolName string = 'npuser01'
@description('Allocate pod ips dynamically')
param cniDynamicIpAllocation bool = false
@minValue(10)
@maxValue(250)
@description('The maximum number of pods per node.')
param maxPods int = 30
@allowed([
'azure'
'kubenet'
])
@description('The network plugin type')
param networkPlugin string = 'azure'
@allowed([
''
'Overlay'
])
@description('The network plugin type')
param networkPluginMode string = ''
@allowed([
''
'cilium'
])
@description('Use Cilium dataplane (requires azure networkPlugin)')
param ebpfDataplane string = ''
@allowed([
''
'azure'
'calico'
])
@description('The network policy to use.')
param networkPolicy string = ''
@allowed([
''
'audit'
'deny'
])
@description('Enable the Azure Policy addon')
param azurepolicy string = ''
@allowed([
'Baseline'
'Restricted'
])
param azurePolicyInitiative string = 'Baseline'
@description('The IP addresses that are allowed to access the API server')
param authorizedIPRanges array = []
@description('Enable private cluster')
param enablePrivateCluster bool = false
@allowed([
'system'
'none'
'privateDnsZone'
])
@description('Private cluster dns advertisment method, leverages the dnsApiPrivateZoneId parameter')
param privateClusterDnsMethod string = 'system'
@description('The full Azure resource ID of the privatelink DNS zone to use for the AKS cluster API Server')
param dnsApiPrivateZoneId string = ''
@description('The zones to use for a node pool')
param availabilityZones array = []
@description('Disable local K8S accounts for AAD enabled clusters')
param AksDisableLocalAccounts bool = false
@description('Use the paid sku for SLA rather than SLO')
param AksPaidSkuForSLA bool = false
@minLength(9)
@maxLength(18)
@description('The address range to use for pods')
param podCidr string = '10.240.100.0/22'
@minLength(9)
@maxLength(18)
@description('The address range to use for services')
param serviceCidr string = '172.10.0.0/16'
@minLength(7)
@maxLength(15)
@description('The IP address to reserve for DNS')
param dnsServiceIP string = '172.10.0.10'
@minLength(9)
@maxLength(18)
@description('The address range to use for the docker bridge')
param dockerBridgeCidr string = '172.17.0.1/16'