This repository was archived by the owner on Jul 28, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathDeployer.cs
More file actions
3141 lines (2677 loc) · 178 KB
/
Deployer.cs
File metadata and controls
3141 lines (2677 loc) · 178 KB
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 (c) Microsoft Corporation.
// Licensed under the MIT License.
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IdentityModel.Tokens.Jwt;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.WebSockets;
using System.Security.Cryptography;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Identity;
using Azure.ResourceManager;
using Azure.ResourceManager.ApplicationInsights;
using Azure.ResourceManager.ApplicationInsights.Models;
using Azure.ResourceManager.Authorization;
using Azure.ResourceManager.Batch;
using Azure.ResourceManager.Compute;
using Azure.ResourceManager.ContainerRegistry;
using Azure.ResourceManager.ContainerService;
using Azure.ResourceManager.ContainerService.Models;
using Azure.ResourceManager.KeyVault;
using Azure.ResourceManager.KeyVault.Models;
using Azure.ResourceManager.ManagedServiceIdentities;
using Azure.ResourceManager.Network;
using Azure.ResourceManager.Network.Models;
using Azure.ResourceManager.OperationalInsights;
using Azure.ResourceManager.PostgreSql.FlexibleServers;
using Azure.ResourceManager.PostgreSql.FlexibleServers.Models;
using Azure.ResourceManager.PrivateDns;
using Azure.ResourceManager.ResourceGraph;
using Azure.ResourceManager.Resources;
using Azure.ResourceManager.Resources.Models;
using Azure.ResourceManager.Storage;
using Azure.Security.KeyVault.Secrets;
using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Specialized;
using BuildPushAcr;
using Common;
using CommonUtilities;
using CommonUtilities.AzureCloud;
using k8s;
using Microsoft.Graph;
using Newtonsoft.Json;
using Polly;
using Polly.Retry;
using Polly.Utilities;
using Batch = Azure.ResourceManager.Batch.Models;
using Storage = Azure.ResourceManager.Storage.Models;
namespace CromwellOnAzureDeployer
{
public class Deployer(Configuration configuration)
{
private static readonly AsyncRetryPolicy roleAssignmentHashConflictRetryPolicy = Policy
.Handle<RequestFailedException>(requestFailedException =>
"HashConflictOnDifferentRoleAssignmentIds".Equals(requestFailedException.ErrorCode, StringComparison.OrdinalIgnoreCase))
.RetryAsync();
private static bool StringComparisonOrdinalIgnoreCase(string v1, string v2)
=> v2.Equals(v1, StringComparison.OrdinalIgnoreCase);
private static readonly AsyncRetryPolicy updateConflictRetryPolicy = Policy
.Handle<RequestFailedException>(azureException =>
(int)HttpStatusCode.Conflict == azureException.Status && azureException.ErrorCode switch
{
var x when StringComparisonOrdinalIgnoreCase(x, "EtagMismatch") => true,
var x when StringComparisonOrdinalIgnoreCase(x, "OperationNotAllowed") => true,
_ => false,
})
.WaitAndRetryAsync(30, retryAttempt => TimeSpan.FromSeconds(10));
private static readonly AsyncRetryPolicy buildPushAcrRetryPolicy = Policy
.Handle<Exception>(AsyncRetryExceptionPolicy)
.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(1));
private static bool AsyncRetryExceptionPolicy(Exception ex)
{
var dontRetry = ex is InvalidOperationException
|| (ex is Microsoft.Kiota.Abstractions.ApiException ae && (int)HttpStatusCode.Unauthorized == ae.ResponseStatusCode)
|| (ex is GitHub.Models.ValidationError ve && (int)HttpStatusCode.UnprocessableContent == ve.ResponseStatusCode)
|| (ex is GitHub.Models.BasicError be &&
((int)HttpStatusCode.Forbidden == be.ResponseStatusCode
|| (int)HttpStatusCode.NotFound == be.ResponseStatusCode
|| (int)HttpStatusCode.Conflict == be.ResponseStatusCode));
if (!dontRetry)
{
Console.WriteLine($"Retrying ACR image build because ({ex.GetType().FullName}): {ex.Message}");
}
return !dontRetry;
}
private static readonly AsyncRetryPolicy acrGetDigestRetryPolicy = Policy
.Handle<RequestFailedException>(azureException => (int)HttpStatusCode.NotFound == azureException.Status)
.WaitAndRetryAsync(30, retryAttempt => TimeSpan.FromSeconds(10));
private static readonly AsyncRetryPolicy generalRetryPolicy = Policy
.Handle<Exception>()
.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(1));
private static readonly AsyncRetryPolicy internalServerErrorRetryPolicy = Policy
.Handle<RequestFailedException>(azureException =>
(int)HttpStatusCode.OK == azureException.Status &&
"InternalServerError".Equals(azureException.ErrorCode, StringComparison.OrdinalIgnoreCase))
.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(15));
internal static Azure.Core.Pipeline.RetryPolicy GetRetryPolicy(CommonUtilities.Options.RetryPolicyOptions retryPolicy)
=> new(retryPolicy.MaxRetryCount, DelayStrategy.CreateExponentialDelayStrategy(TimeSpan.FromSeconds(retryPolicy.ExponentialBackOffExponent)));
public const string WorkflowsContainerName = "workflows";
public const string ConfigurationContainerName = "configuration";
public const string TesInternalContainerName = "tes-internal";
public const string CromwellConfigurationFileName = "cromwell-application.conf";
public const string AllowedVmSizesFileName = "allowed-vm-sizes";
public const string InputsContainerName = "inputs";
public const string OutputsContainerName = "outputs";
public const string LogsContainerName = "cromwell-workflow-logs";
public const string ExecutionsContainerName = "cromwell-executions";
public const string StorageAccountKeySecretName = "CoAStorageKey";
public const string PostgresqlSslMode = "VerifyFull";
private readonly CancellationTokenSource cts = new();
private readonly List<string> requiredResourceProviders =
[
"Microsoft.Authorization",
"Microsoft.Batch",
"Microsoft.Compute",
"Microsoft.ContainerService",
"Microsoft.DocumentDB",
"Microsoft.OperationalInsights",
"Microsoft.OperationsManagement",
"Microsoft.insights",
"Microsoft.Network",
"Microsoft.Storage",
"Microsoft.DBforPostgreSQL",
];
private readonly Dictionary<string, List<string>> requiredResourceProviderFeatures = new()
{
{ "Microsoft.Compute", new() { "EncryptionAtHost" } },
};
private Configuration configuration { get; } = configuration;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Performance", "CA1859:Use concrete types when possible for improved performance", Justification = "We are using the base type everywhere.")]
[System.Diagnostics.CodeAnalysis.SuppressMessage("CodeQuality", "IDE0079:Remove unnecessary suppression", Justification = "CA1859 suppression seems appropriate in this use case.")]
private TokenCredential tokenCredential { get; set; }
private SubscriptionResource armSubscription { get; set; }
private ArmClient armClient { get; set; }
private ResourceGroupResource resourceGroup { get; set; }
private CloudEnvironment cloudEnvironment { get; set; }
private IEnumerable<SubscriptionResource> subscriptionIds { get; set; }
private bool isResourceGroupCreated { get; set; }
private KubernetesManager kubernetesManager { get; set; }
internal static AzureCloudConfig azureCloudConfig { get; private set; }
internal static bool IsStorageInPublicCloud { get; private set; }
private static async Task<T> EnsureResourceDataAsync<T>(T resource, Predicate<T> HasData, Func<T, Func<CancellationToken, Task<Response<T>>>> GetAsync, CancellationToken cancellationToken, Action<T> OnAcquisition = null) where T : ArmResource
{
return HasData(resource)
? resource
: await FetchResourceDataAsync(GetAsync(resource), cancellationToken, OnAcquisition);
}
private static async Task<T> FetchResourceDataAsync<T>(Func<CancellationToken, Task<Response<T>>> GetAsync, CancellationToken cancellationToken, Action<T> OnAcquisition = null) where T : ArmResource
{
ArgumentNullException.ThrowIfNull(GetAsync);
var result = await GetAsync(cancellationToken);
OnAcquisition?.Invoke(result);
return result;
}
private async ValueTask EnsureResourceGroup()
{
if (resourceGroup is null && !string.IsNullOrWhiteSpace(configuration.ResourceGroupName))
{
resourceGroup = (await armSubscription.GetResourceGroupAsync(configuration.ResourceGroupName, cts.Token)).Value;
}
}
private BlobClient GetBlobClient(StorageAccountData storageAccount, string containerName, string blobName)
{
return new(new BlobUriBuilder(storageAccount.PrimaryEndpoints.BlobUri) { BlobContainerName = containerName, BlobName = blobName }.ToUri(),
tokenCredential,
new()
{
Audience = Azure.Storage.Blobs.Models.BlobAudience.DefaultAudience, // https://github.com/Azure/azure-cli/issues/28708#issuecomment-2047256166
RetryPolicy = GetRetryPolicy(new())
});
}
private BlobContainerClient GetBlobContainerClient(StorageAccountData storageAccount, string containerName)
{
return new(new BlobUriBuilder(storageAccount.PrimaryEndpoints.BlobUri) { BlobContainerName = containerName }.ToUri(),
tokenCredential,
new()
{
Audience = Azure.Storage.Blobs.Models.BlobAudience.DefaultAudience, // https://github.com/Azure/azure-cli/issues/28708#issuecomment-2047256166
RetryPolicy = GetRetryPolicy(new())
});
}
public async Task<int> DeployAsync()
{
var mainTimer = Stopwatch.StartNew();
try
{
ConsoleEx.WriteLine("Running...");
await Execute($"Getting cloud configuration for {configuration.AzureCloudName}...", async () =>
{
azureCloudConfig = await AzureCloudConfig.FromKnownCloudNameAsync(cloudName: configuration.AzureCloudName, retryPolicyOptions: Microsoft.Extensions.Options.Options.Create<CommonUtilities.Options.RetryPolicyOptions>(new()));
cloudEnvironment = new(azureCloudConfig.ArmEnvironment.Value, azureCloudConfig.AuthorityHost);
});
IsStorageInPublicCloud = "core.windows.net".Equals(azureCloudConfig.Suffixes.StorageSuffix, StringComparison.OrdinalIgnoreCase);
await Execute("Validating command line arguments...", () =>
{
ValidateInitialCommandLineArgs();
return Task.CompletedTask;
});
await ValidateTokenProviderAsync();
await Execute("Connecting to Azure Services...", async () =>
{
tokenCredential = new AzureCliCredential(new() { AuthorityHost = cloudEnvironment.AzureAuthorityHost, RetryPolicy = GetRetryPolicy(new()) });
armClient = new ArmClient(tokenCredential, configuration.SubscriptionId, new() { Environment = cloudEnvironment.ArmEnvironment, RetryPolicy = GetRetryPolicy(new()) });
armSubscription = armClient.GetSubscriptionResource(SubscriptionResource.CreateResourceIdentifier(configuration.SubscriptionId));
subscriptionIds = await armClient.GetSubscriptions().GetAllAsync(cts.Token).ToListAsync(cts.Token);
});
await ValidateSubscriptionAndResourceGroupAsync(configuration);
kubernetesManager = new KubernetesManager(configuration, azureCloudConfig, GetBlobClient, cts.Token);
ContainerServiceManagedClusterResource aksCluster = null;
BatchAccountResource batchAccount = null;
OperationalInsightsWorkspaceResource logAnalyticsWorkspace = null;
ApplicationInsightsComponentResource appInsights = null;
PostgreSqlFlexibleServerResource postgreSqlFlexServer = null;
StorageAccountResource storageAccount = null;
StorageAccountData storageAccountData = null;
Uri keyVaultUri = null;
UserAssignedIdentityResource managedIdentity = null;
PrivateDnsZoneResource postgreSqlDnsZone = null;
IKubernetes kubernetesClient = null;
var containersToMount = await GetContainersToMount(configuration.ContainersToMountPath);
try
{
var targetVersion = Utility.DelimitedTextToDictionary(Utility.GetFileContent("scripts", "env-00-coa-version.txt")).GetValueOrDefault("CromwellOnAzureVersion");
if (configuration.Update)
{
await EnsureResourceGroup();
configuration.RegionName = resourceGroup.Id.Location ?? (resourceGroup.HasData
? resourceGroup.Data.Location.Name
: (await FetchResourceDataAsync(resourceGroup.GetAsync, cts.Token, resource => resourceGroup = resource)).Data.Location.Name);
ConsoleEx.WriteLine($"Upgrading Cromwell on Azure instance in resource group '{resourceGroup.Id.Name}' to version {targetVersion}...");
if (string.IsNullOrEmpty(configuration.StorageAccountName))
{
var storageAccounts = await resourceGroup.GetStorageAccounts().ToListAsync(cts.Token);
storageAccount = storageAccounts.Count switch
{
0 => throw new ValidationException($"Update was requested but resource group {configuration.ResourceGroupName} does not contain any storage accounts.", displayExample: false),
1 => storageAccounts.Single(),
_ => throw new ValidationException($"Resource group {configuration.ResourceGroupName} contains multiple storage accounts. {nameof(configuration.StorageAccountName)} must be provided.", displayExample: false),
};
}
else
{
storageAccount = await GetExistingStorageAccountAsync(configuration.StorageAccountName)
?? throw new ValidationException($"Storage account {configuration.StorageAccountName}, does not exist in region {configuration.RegionName} or is not accessible to the current user.", displayExample: false);
}
storageAccountData = (await FetchResourceDataAsync(ct => storageAccount.GetAsync(cancellationToken: ct), cts.Token, account => storageAccount = account)).Data;
switch (await AssignRoleForDeployerToStorageAccountAsync(storageAccount))
{
case true:
// 10 minutes for propagation https://learn.microsoft.com/azure/role-based-access-control/troubleshooting
await Execute("Waiting 5 minutes for role assignment propagation...",
() => Task.Delay(TimeSpan.FromMinutes(5), cts.Token));
break;
case null:
ConsoleEx.WriteLine("Unable to assign 'Storage Blob Data Contributor' for deployment identity to the storage account. If the deployment fails as a result, assign the deploying user the 'Storage Blob Data Contributor' role for the storage account.", ConsoleColor.Yellow);
break;
}
var aksValues = await kubernetesManager.GetAKSSettingsAsync(storageAccountData);
if (0 == aksValues.Count)
{
throw new ValidationException("Upgrading pre-4.0 versions of CromwellOnAzure is not supported. Please see https://github.com/microsoft/CromwellOnAzure/wiki/4.0-Migration-Guide.", displayExample: false);
}
if (aksValues.TryGetValue("AksCoANamespace", out var aksCoANamespace))
{
configuration.AksCoANamespace = aksCoANamespace;
}
if (!aksValues.TryGetValue("BatchAccountName", out var batchAccountName))
{
throw new ValidationException($"Could not retrieve the Batch account name", displayExample: false);
}
batchAccount = await GetExistingBatchAccountAsync(batchAccountName)
?? throw new ValidationException($"Batch account {batchAccountName}, referenced by the stored configuration, does not exist in region {configuration.RegionName} or is not accessible to the current user.", displayExample: false);
configuration.BatchAccountName = batchAccountName;
if (!aksValues.TryGetValue("PostgreSqlServerName", out var postgreSqlServerName))
{
throw new ValidationException($"Could not retrieve the PostgreSqlServer account name from stored configuration in {storageAccount.Id.Name}.", displayExample: false);
}
configuration.PostgreSqlServerName = postgreSqlServerName;
if (string.IsNullOrEmpty(configuration.AksClusterName))
{
var aksClusters = await resourceGroup.GetContainerServiceManagedClusters().GetAllAsync(cts.Token).ToListAsync(cts.Token);
aksCluster = aksClusters.Count switch
{
0 => throw new ValidationException($"Update was requested but resource group {configuration.ResourceGroupName} does not contain any AKS clusters.", displayExample: false),
1 => (await aksClusters.Single().GetAsync()).Value,
_ => throw new ValidationException($"Resource group {configuration.ResourceGroupName} contains multiple AKS clusters. {nameof(configuration.AksClusterName)} must be provided.", displayExample: false),
};
configuration.AksClusterName = aksCluster.Data.Name;
}
else
{
aksCluster = await GetExistingAKSClusterAsync(configuration.AksClusterName)
?? throw new ValidationException($"AKS cluster {configuration.AksClusterName} does not exist in region {configuration.RegionName} or is not accessible to the current user.", displayExample: false);
}
if (aksValues.TryGetValue("CrossSubscriptionAKSDeployment", out var crossSubscriptionAKSDeployment))
{
configuration.CrossSubscriptionAKSDeployment = bool.TryParse(crossSubscriptionAKSDeployment, out var parsed) ? parsed : null;
}
if (aksValues.TryGetValue("KeyVaultName", out var keyVaultName))
{
var keyVault = await GetKeyVaultAsync(keyVaultName);
keyVaultUri = (keyVault.HasData ? keyVault : await FetchResourceDataAsync(keyVault.GetAsync, cts.Token)).Data.Properties.VaultUri;
}
if (!aksValues.TryGetValue("ManagedIdentityClientId", out var managedIdentityClientId))
{
throw new ValidationException($"Could not retrieve ManagedIdentityClientId.", displayExample: false);
}
var clientId = Guid.Parse(managedIdentityClientId);
managedIdentity = await resourceGroup.GetUserAssignedIdentities()
.SelectAwaitWithCancellation(async (id, ct) => await FetchResourceDataAsync(id.GetAsync, ct))
.FirstOrDefaultAsync(id => id.Data.ClientId == clientId, cts.Token)
?? throw new ValidationException($"Managed Identity {managedIdentityClientId} does not exist in region {configuration.RegionName} or is not accessible to the current user.", displayExample: false);
// Override any configuration that is used by the update.
var versionString = aksValues["CromwellOnAzureVersion"];
var installedVersion = !string.IsNullOrEmpty(versionString) && Version.TryParse(versionString, out var version) ? version : null;
if (installedVersion is null || installedVersion < new Version(4, 0))
{
throw new ValidationException("Upgrading pre-4.0 versions of CromwellOnAzure is not supported. Please see https://github.com/microsoft/CromwellOnAzure/wiki/4.0-Migration-Guide.");
}
var settings = ConfigureSettings(managedIdentity.Data.ClientId?.ToString("D"), aksValues, installedVersion);
var waitForRoleAssignmentPropagation = false;
IEnumerable<string> manualPrecommands = null;
Func<IKubernetes, Task> asyncTask = null;
if (!string.IsNullOrWhiteSpace(configuration.AcrId) && settings.TryGetValue("AcrId", out var acrId) && !string.IsNullOrEmpty(acrId))
{
throw new ValidationException("AcrId must not be set if previously configured.", displayExample: false);
}
if (installedVersion is null || installedVersion < new Version(4, 4))
{
// Ensure all storage containers are created.
await CreateDefaultStorageContainersAsync(storageAccount);
if (string.IsNullOrWhiteSpace(settings["BatchNodesSubnetId"]))
{
settings["BatchNodesSubnetId"] = await UpdateVnetWithBatchSubnet();
}
}
if (installedVersion is null || installedVersion < new Version(4, 7))
{
await AssignMIAsNetworkContributorToResourceAsync(managedIdentity, resourceGroup);
await AssignMIAsDataOwnerToStorageAccountAsync(managedIdentity, storageAccount);
await Execute($"Moving {AllowedVmSizesFileName} file to new location: {TesInternalContainerName}/{ConfigurationContainerName}/{AllowedVmSizesFileName}",
() => MoveAllowedVmSizesFileAsync(storageAccountData));
waitForRoleAssignmentPropagation = true;
}
if (installedVersion is null || installedVersion < new Version(5, 4, 7)) // Previous attempt < 5.0.1
{
if (string.IsNullOrWhiteSpace(settings["ExecutionsContainerName"]))
{
settings["ExecutionsContainerName"] = ExecutionsContainerName;
}
}
if (installedVersion is null || installedVersion < new Version(5, 4, 7)) // Previous attempt < 5.2.2
{
var connectionString = settings["AzureServicesAuthConnectionString"];
if (connectionString.Contains("RunAs=App"))
{
settings["AzureServicesAuthConnectionString"] = connectionString.Replace("RunAs=App", "RunAs=Workload");
}
var pool = aksCluster.Data.AgentPoolProfiles.FirstOrDefault(pool => "nodepool1".Equals(pool.Name, StringComparison.OrdinalIgnoreCase));
if (!(aksCluster.Data.SecurityProfile.IsWorkloadIdentityEnabled ?? false) ||
!(aksCluster.Data.OidcIssuerProfile.IsEnabled ?? false) ||
pool?.OSSku == ContainerServiceOSSku.Ubuntu ||
!(pool?.EnableEncryptionAtHost ?? false) ||
!(aksCluster.Data.AadProfile?.IsAzureRbacEnabled ?? false) ||
(await managedIdentity.GetFederatedIdentityCredentials()
.SingleOrDefaultAsync(r => "coaFederatedIdentity".Equals(r.Id.Name, StringComparison.OrdinalIgnoreCase), cts.Token)) is null)
{
await AssignMeAsRbacClusterAdminToManagedClusterAsync(aksCluster);
waitForRoleAssignmentPropagation = true;
ManagedClusterEnableManagedAad(aksCluster.Data);
if (pool?.OSSku == ContainerServiceOSSku.Ubuntu || !(pool?.EnableEncryptionAtHost ?? false))
{
pool.EnableEncryptionAtHost = true;
pool.OSSku = ContainerServiceOSSku.AzureLinux;
}
aksCluster = await EnableWorkloadIdentity(aksCluster, managedIdentity, resourceGroup);
await Task.Delay(TimeSpan.FromMinutes(2), cts.Token);
if (installedVersion is null || installedVersion < new Version(5, 2, 3))
{
manualPrecommands = (manualPrecommands ?? []).Append("Include the following HELM command: uninstall aad-pod-identity --namespace kube-system");
asyncTask = _ => kubernetesManager.RemovePodAadChart();
}
}
}
if (installedVersion is null || installedVersion < new Version(5, 3, 0))
{
settings["AzureCloudName"] = configuration.AzureCloudName;
}
if (installedVersion is null || installedVersion < new Version(5, 3, 1))
{
if (string.IsNullOrWhiteSpace(settings["DeploymentCreated"]))
{
settings["DeploymentCreated"] = settings["DeploymentUpdated"];
}
}
if (IsStorageInPublicCloud && (installedVersion is null || installedVersion < new Version(5, 5, 1)))
{
var cromwellConfig = GetBlobClient(storageAccountData, ConfigurationContainerName, CromwellConfigurationFileName);
var configContent = await DownloadTextFromStorageAccountAsync(cromwellConfig, cts.Token);
if (!configContent.Contains(".blob.", StringComparison.Ordinal))
{
using HoconUtil hocon = new(configContent);
var conf = hocon.Parse();
var changes = Hocon.HoconParser.Parse($@"
filesystems.blob {{
class = ""cromwell.filesystems.blob.BlobPathBuilderFactory""
global {{
class = ""cromwell.filesystems.blob.BlobFileSystemManager""
config.subscription = ""{configuration.SubscriptionId}""
}}
}}
engine.filesystems.blob.enabled: true
backend.providers.TES.config {{
filesystems {{
http.enabled: true
local.enabled: true
blob.enabled: true
}}
root = ""https://{storageAccountData.Name}.blob.{azureCloudConfig.Suffixes.StorageSuffix}/{ExecutionsContainerName}/""
}}").Value.GetObject();
conf.Value.GetObject().Merge(changes);
await UploadTextToStorageAccountAsync(cromwellConfig, hocon.ToString(conf).ReplaceLineEndings("\r\n"), cts.Token);
}
}
if (!IsStorageInPublicCloud && (installedVersion.Major == 5 && installedVersion.Minor == 5 && installedVersion.Build == 1)) // special case: revert 5.5.1 changes
{
var cromwellConfig = GetBlobClient(storageAccountData, ConfigurationContainerName, CromwellConfigurationFileName);
var configContent = await DownloadTextFromStorageAccountAsync(cromwellConfig, cts.Token);
if (configContent.Contains(".blob.", StringComparison.Ordinal))
{
using HoconUtil hocon = new(configContent);
var conf = hocon.Parse();
var changes = Hocon.HoconParser.Parse($@"backend.providers.TES.config.root = ""/{ExecutionsContainerName}""").Value.GetObject();
conf.Value.GetObject().Merge(changes);
_ = hocon.Remove(conf, "filesystems.blob");
_ = hocon.Remove(conf, "engine.filesystems.blob");
_ = hocon.Remove(conf, "backend.providers.TES.config.filesystems.blob");
await UploadTextToStorageAccountAsync(cromwellConfig, hocon.ToString(conf).ReplaceLineEndings("\r\n"), cts.Token);
}
}
//if (installedVersion is null || installedVersion < new Version(x, y, z))
//{
//}
await Task.WhenAll(
[
BuildPushAcrAsync(settings, targetVersion, managedIdentity),
Task.Run(async () =>
{
if (waitForRoleAssignmentPropagation)
{
// 10 minutes for propagation https://learn.microsoft.com/azure/role-based-access-control/troubleshooting
await Execute("Waiting 10 minutes for role assignment propagation...",
() => Task.Delay(TimeSpan.FromMinutes(10), cts.Token));
}
})
]);
await kubernetesManager.UpgradeValuesYamlAsync(storageAccountData, settings, containersToMount, installedVersion);
kubernetesClient = await PerformHelmDeploymentAsync(aksCluster, manualPrecommands, asyncTask);
await kubernetesManager.ProcessClusterUpdatesAsync(kubernetesClient, aksCluster, installedVersion, Execute);
await WriteNonPersonalizedFilesToStorageAccountAsync(storageAccountData);
}
if (!configuration.Update)
{
if (string.IsNullOrWhiteSpace(configuration.BatchPrefix))
{
var blob = new byte[5];
RandomNumberGenerator.Fill(blob);
configuration.BatchPrefix = blob.ConvertToBase32().TrimEnd('=');
}
KeyVaultResource keyVault = default;
await Execute("Validating existing Azure resources...", async () =>
{
await ValidateRegionNameAsync(configuration.RegionName);
ValidateMainIdentifierPrefix(configuration.MainIdentifierPrefix);
storageAccount = await ValidateAndGetExistingStorageAccountAsync();
batchAccount = await ValidateAndGetExistingBatchAccountAsync();
postgreSqlFlexServer = await ValidateAndGetExistingPostgresqlServer();
aksCluster = await ValidateAndGetExistingAKSClusterAsync();
keyVault = await ValidateAndGetExistingKeyVault();
if (aksCluster is null && !configuration.ManualHelmDeployment)
{
//await ValidateVmAsync();
}
if (string.IsNullOrWhiteSpace(configuration.PostgreSqlServerNameSuffix))
{
configuration.PostgreSqlServerNameSuffix = $".{azureCloudConfig.Suffixes.PostgresqlServerEndpointSuffix}";
}
if (string.IsNullOrWhiteSpace(configuration.PostgreSqlServerName))
{
configuration.PostgreSqlServerName = Utility.RandomResourceName($"{configuration.MainIdentifierPrefix}-", 15);
}
configuration.PostgreSqlAdministratorPassword = PasswordGenerator.GeneratePassword();
configuration.PostgreSqlCromwellUserPassword = PasswordGenerator.GeneratePassword();
configuration.PostgreSqlTesUserPassword = PasswordGenerator.GeneratePassword();
if (string.IsNullOrWhiteSpace(configuration.BatchAccountName))
{
configuration.BatchAccountName = Utility.RandomResourceName($"{configuration.MainIdentifierPrefix}", 15);
}
if (string.IsNullOrWhiteSpace(configuration.StorageAccountName))
{
configuration.StorageAccountName = Utility.RandomResourceName($"{configuration.MainIdentifierPrefix}", 24);
}
if (string.IsNullOrWhiteSpace(configuration.ApplicationInsightsAccountName))
{
configuration.ApplicationInsightsAccountName = Utility.RandomResourceName($"{configuration.MainIdentifierPrefix}-", 15);
}
if (string.IsNullOrWhiteSpace(configuration.AksClusterName))
{
configuration.AksClusterName = Utility.RandomResourceName($"{configuration.MainIdentifierPrefix}-", 25);
}
if (string.IsNullOrWhiteSpace(configuration.KeyVaultName))
{
configuration.KeyVaultName = Utility.RandomResourceName($"{configuration.MainIdentifierPrefix}-", 15);
}
await RegisterResourceProvidersAsync();
await RegisterResourceProviderFeaturesAsync();
if (batchAccount is null)
{
await ValidateBatchAccountQuotaAsync();
}
});
ConsoleEx.WriteLine($"Deploying Cromwell on Azure version {targetVersion}...");
if (!string.IsNullOrEmpty(configuration.BatchNodesSubnetId))
{
configuration.BatchSubnetName = new ResourceIdentifier(configuration.BatchNodesSubnetId).Name;
}
var vnetAndSubnet = await ValidateAndGetExistingVirtualNetworkAsync();
if (resourceGroup is null)
{
configuration.ResourceGroupName = Utility.RandomResourceName($"{configuration.MainIdentifierPrefix}-", 15);
resourceGroup = await CreateResourceGroupAsync();
isResourceGroupCreated = true;
}
else
{
await EnsureResourceGroup();
}
if (!string.IsNullOrWhiteSpace(configuration.IdentityResourceId))
{
var identityResourceId = ResourceIdentifier.Parse(configuration.IdentityResourceId);
if (!UserAssignedIdentityResource.CreateResourceIdentifier(identityResourceId.SubscriptionId, identityResourceId.ResourceGroupName, identityResourceId.Name).Equals(identityResourceId)
// https://learn.microsoft.com/azure/azure-resource-manager/management/resource-name-rules#microsoftmanagedidentity
// https://learn.microsoft.com/entra/identity/managed-identities-azure-resources/how-manage-user-assigned-managed-identities?pivots=identity-mi-methods-azp#create-a-user-assigned-managed-identity
|| identityResourceId.Name.Length < 3 || identityResourceId.Name.Length > 24
|| !char.IsAsciiLetterOrDigit(identityResourceId.Name[0])
|| !identityResourceId.Name.Skip(1).All(@char => char.IsAsciiLetterOrDigit(@char) || '-' == @char || '_' == @char))
{
throw new ValidationException($"{nameof(configuration.IdentityResourceId)} is invalid. It must be a user assigned managed identity with a valid name that isn't longer than 24 characters.", false);
}
ConsoleEx.WriteLine($"Using existing user-assigned managed identity: {identityResourceId}");
managedIdentity = await GetUserManagedIdentityAsync(identityResourceId);
}
else
{
managedIdentity = await CreateUserManagedIdentityAsync();
}
managedIdentity = await EnsureResourceDataAsync(managedIdentity, id => id.HasData, id => id.GetAsync, cts.Token);
if (vnetAndSubnet is not null)
{
ConsoleEx.WriteLine($"Creating VM in existing virtual network {vnetAndSubnet.Value.virtualNetwork.Id.Name} and subnet {vnetAndSubnet.Value.vmSubnet.Id.Name}");
}
if (storageAccount is not null)
{
ConsoleEx.WriteLine($"Using existing Storage Account {storageAccount.Id.Name}");
}
if (batchAccount is not null)
{
ConsoleEx.WriteLine($"Using existing Batch Account {batchAccount.Id.Name}");
}
await Task.WhenAll(
[
Task.Run(async () =>
{
if (vnetAndSubnet is null)
{
configuration.VnetName = Utility.RandomResourceName($"{configuration.MainIdentifierPrefix}-", 15);
configuration.PostgreSqlSubnetName = string.IsNullOrEmpty(configuration.PostgreSqlSubnetName) ? configuration.DefaultPostgreSqlSubnetName : configuration.PostgreSqlSubnetName;
configuration.BatchSubnetName = string.IsNullOrEmpty(configuration.BatchSubnetName) ? configuration.DefaultBatchSubnetName : configuration.BatchSubnetName;
configuration.VmSubnetName = string.IsNullOrEmpty(configuration.VmSubnetName) ? configuration.DefaultVmSubnetName : configuration.VmSubnetName;
vnetAndSubnet = await CreateVnetAndSubnetsAsync();
}
}),
Task.Run(async () =>
{
logAnalyticsWorkspace = await GetLogAnalyticsWorkspaceAsync(configuration.LogAnalyticsArmId);
if (logAnalyticsWorkspace == null)
{
var workspaceName = Utility.RandomResourceName(configuration.MainIdentifierPrefix, 15);
logAnalyticsWorkspace = await CreateLogAnalyticsWorkspaceAsync(workspaceName);
configuration.LogAnalyticsArmId = logAnalyticsWorkspace.Id;
}
}),
Task.Run(async () =>
{
storageAccount = await EnsureResourceDataAsync(storageAccount ?? await CreateStorageAccountAsync(), r => r.HasData, r => ct => r.GetAsync(cancellationToken: ct), cts.Token);
await CreateDefaultStorageContainersAsync(storageAccount);
storageAccountData = storageAccount.Data;
if (await AssignRoleForDeployerToStorageAccountAsync(storageAccount) is null)
{
ConsoleEx.WriteLine("Unable to assign 'Storage Blob Data Contributor' for deployment identity to the storage account. If the deployment fails as a result, the storage account must be precreated and the deploying user must have the 'Storage Blob Data Contributor' role for the storage account.", ConsoleColor.Yellow);
}
else
{
await Task.Delay(TimeSpan.FromMinutes(5), cts.Token);
}
await AssignVmAsContributorToStorageAccountAsync(managedIdentity, storageAccount);
await AssignMIAsDataOwnerToStorageAccountAsync(managedIdentity, storageAccount);
await AssignManagedIdOperatorToResourceAsync(managedIdentity, resourceGroup);
await AssignMIAsNetworkContributorToResourceAsync(managedIdentity, resourceGroup);
await WriteNonPersonalizedFilesToStorageAccountAsync(storageAccountData);
await WritePersonalizedFilesToStorageAccountAsync(storageAccountData);
}),
]);
if (configuration.CrossSubscriptionAKSDeployment.GetValueOrDefault())
{
await Task.Run(async () =>
{
keyVault ??= await CreateKeyVaultAsync(configuration.KeyVaultName, managedIdentity, vnetAndSubnet.Value.virtualNetwork, vnetAndSubnet.Value.vmSubnet);
keyVaultUri = (await EnsureResourceDataAsync(keyVault, r => r.HasData, r => r.GetAsync, cts.Token)).Data.Properties.VaultUri;
var key = await storageAccount.GetKeysAsync(cancellationToken: cts.Token).FirstAsync(cts.Token);
await SetStorageKeySecret(keyVaultUri, StorageAccountKeySecretName, key.Value);
});
}
if (postgreSqlFlexServer is null)
{
postgreSqlDnsZone = await GetExistingPrivateDnsZoneAsync($"privatelink.{azureCloudConfig.Suffixes.PostgresqlServerEndpointSuffix}");
postgreSqlDnsZone ??= await CreatePrivateDnsZoneAsync(vnetAndSubnet.Value.virtualNetwork, $"privatelink.{azureCloudConfig.Suffixes.PostgresqlServerEndpointSuffix}", "PostgreSQL Server");
}
await Task.WhenAll(
[
Task.Run(async () =>
{
if (aksCluster is null && !configuration.ManualHelmDeployment)
{
aksCluster = await ProvisionManagedClusterAsync(managedIdentity, logAnalyticsWorkspace, vnetAndSubnet?.vmSubnet.Id, configuration.PrivateNetworking.GetValueOrDefault(), configuration.AksNodeResourceGroupName);
await AssignMeAsRbacClusterAdminToManagedClusterAsync(aksCluster);
aksCluster = await EnableWorkloadIdentity(aksCluster, managedIdentity, resourceGroup);
}
}),
Task.Run(async () =>
{
batchAccount ??= await CreateBatchAccountAsync(storageAccount.Id);
await AssignVmAsContributorToBatchAccountAsync(managedIdentity, batchAccount);
}),
Task.Run(async () =>
{
appInsights = await CreateAppInsightsResourceAsync(new(configuration.LogAnalyticsArmId));
await AssignVmAsContributorToAppInsightsAsync(managedIdentity, appInsights);
}),
Task.Run(async () =>
{
postgreSqlFlexServer ??= await CreatePostgreSqlServerAndDatabaseAsync(vnetAndSubnet.Value.postgreSqlSubnet, postgreSqlDnsZone);
})
]);
if (string.IsNullOrEmpty(this.configuration.BatchNodesSubnetId))
{
configuration.BatchNodesSubnetId = vnetAndSubnet.Value.batchSubnet.Id;
}
var clientId = managedIdentity.Data.ClientId;
var settings = ConfigureSettings(clientId?.ToString("D"));
await BuildPushAcrAsync(settings, targetVersion, managedIdentity);
await kubernetesManager.UpdateHelmValuesAsync(storageAccountData, keyVaultUri, resourceGroup.Id.Name, settings, managedIdentity.Data, containersToMount);
kubernetesClient = await PerformHelmDeploymentAsync(aksCluster,
[
"Run the following postgresql command to setup the database.",
"\tPostgreSQL command: " + GetPostgreSQLCreateCromwellUserCommand(configuration.PostgreSqlCromwellDatabaseName, GetCreateCromwellUserString()),
"\tPostgreSQL command: " + GetPostgreSQLCreateCromwellUserCommand(configuration.PostgreSqlTesDatabaseName, GetCreateTesUserString()),
],
async kubernetesClient =>
{
await kubernetesManager.DeployCoADependenciesAsync();
// Deploy an ubuntu pod to run PSQL commands, then delete it
const string deploymentNamespace = "default";
var (deploymentName, ubuntuDeployment) = KubernetesManager.GetUbuntuDeploymentTemplate(configuration.PrivatePSQLUbuntuImage);
await kubernetesClient.AppsV1.CreateNamespacedDeploymentAsync(ubuntuDeployment, deploymentNamespace, cancellationToken: cts.Token);
await ExecuteQueriesOnAzurePostgreSQLDbFromK8(kubernetesClient, deploymentName, deploymentNamespace);
await kubernetesClient.AppsV1.DeleteNamespacedDeploymentAsync(deploymentName, deploymentNamespace, cancellationToken: cts.Token);
});
}
if (kubernetesClient is not null)
{
await kubernetesManager.WaitForCromwellAsync(kubernetesClient);
}
}
finally
{
if (!configuration.ManualHelmDeployment)
{
kubernetesManager?.DeleteTempFiles();
}
}
var batchAccountData = (await EnsureResourceDataAsync(await GetExistingBatchAccountAsync(configuration.BatchAccountName), r => r.HasData, r => r.GetAsync, cts.Token)).Data;
var maxPerFamilyQuota = batchAccountData.IsDedicatedCoreQuotaPerVmFamilyEnforced ?? false ? batchAccountData.DedicatedCoreQuotaPerVmFamily.Select(q => q.CoreQuota ?? 0).Where(q => 0 != q) : Enumerable.Repeat(batchAccountData.DedicatedCoreQuota ?? 0, 1);
var isBatchQuotaAvailable = batchAccountData.LowPriorityCoreQuota > 0 || (batchAccountData.DedicatedCoreQuota > 0 && maxPerFamilyQuota.Append(0).Max() > 0);
var isBatchPoolQuotaAvailable = batchAccountData.PoolQuota > 0;
var isBatchJobQuotaAvailable = batchAccountData.ActiveJobAndJobScheduleQuota > 0;
var insufficientQuotas = new List<string>();
int exitCode;
if (!isBatchQuotaAvailable) insufficientQuotas.Add("core");
if (!isBatchPoolQuotaAvailable) insufficientQuotas.Add("pool");
if (!isBatchJobQuotaAvailable) insufficientQuotas.Add("job");
if (0 != insufficientQuotas.Count)
{
if (!configuration.SkipTestWorkflow)
{
ConsoleEx.WriteLine("Could not run the test workflow.", ConsoleColor.Yellow);
}
var quotaMessage = string.Join(" and ", insufficientQuotas);
ConsoleEx.WriteLine($"Deployment was successful, but Batch account {configuration.BatchAccountName} does not have sufficient {quotaMessage} quota to run workflows.", ConsoleColor.Yellow);
ConsoleEx.WriteLine($"Request Batch {quotaMessage} quota: https://docs.microsoft.com/en-us/azure/batch/batch-quota-limit", ConsoleColor.Yellow);
ConsoleEx.WriteLine("After receiving the quota, read the docs to run a test workflow and confirm successful deployment.", ConsoleColor.Yellow);
exitCode = 2;
}
else
{
if (configuration.SkipTestWorkflow)
{
exitCode = 0;
}
else
{
var isTestWorkflowSuccessful = await RunTestWorkflow(storageAccountData, usePreemptibleVm: batchAccountData.LowPriorityCoreQuota > 0);
if (!isTestWorkflowSuccessful)
{
await DeleteResourceGroupIfUserConsentsAsync();
}
exitCode = isTestWorkflowSuccessful ? 0 : 1;
}
}
ConsoleEx.WriteLine($"Completed in {mainTimer.Elapsed.TotalMinutes:n1} minutes.");
return exitCode;
}
catch (ValidationException validationException)
{
DisplayValidationExceptionAndExit(validationException);
return 1;
}
catch (Exception exc)
{
if (!(exc is OperationCanceledException && cts.Token.IsCancellationRequested))
{
ConsoleEx.WriteLine();
ConsoleEx.WriteLine($"{exc.GetType().FullName}: {exc.Message}", ConsoleColor.Red);
if (configuration.DebugLogging)
{
ConsoleEx.WriteLine(exc.StackTrace, ConsoleColor.Red);
if (exc is KubernetesException kExc)
{
ConsoleEx.WriteLine($"Kubenetes Status: {kExc.Status}");
}
if (exc is WebSocketException wExc)
{
ConsoleEx.WriteLine($"WebSocket ErrorCode: {wExc.WebSocketErrorCode}");
}
if (exc is RequestFailedException fExc)
{
ConsoleEx.WriteLine($"HTTP Response: {fExc.GetRawResponse().Content}");
}
}
}
ConsoleEx.WriteLine();
Debugger.Break();
WriteGeneralRetryMessageToConsole();
await DeleteResourceGroupIfUserConsentsAsync();
return 1;
}
}
private async Task MoveAllowedVmSizesFileAsync(StorageAccountData storageAccount)
{
var allowedVmSizesFileContent = Utility.GetFileContent("scripts", AllowedVmSizesFileName);
var existingAllowedVmSizesBlobClient = GetBlobClient(storageAccount, ConfigurationContainerName, AllowedVmSizesFileName);
var isExistingFile = false;
// Get existing content if it exists
if (await existingAllowedVmSizesBlobClient.ExistsAsync(cts.Token))
{
isExistingFile = true;
var existingAllowedVmSizesContent = (await existingAllowedVmSizesBlobClient.DownloadContentAsync(cts.Token)).Value.Content.ToString();
if (!string.IsNullOrWhiteSpace(existingAllowedVmSizesContent))
{
// Use existing content
allowedVmSizesFileContent = existingAllowedVmSizesContent;
}
}
// Upload to new location
await UploadTextToStorageAccountAsync(GetBlobClient(storageAccount, TesInternalContainerName, $"{ConfigurationContainerName}/{AllowedVmSizesFileName}"), allowedVmSizesFileContent, cts.Token);
if (isExistingFile)
{
// Delete old file to prevent user confusion about source of truth
await existingAllowedVmSizesBlobClient.DeleteAsync(cancellationToken: cts.Token);
}
}
private async Task<IKubernetes> PerformHelmDeploymentAsync(ContainerServiceManagedClusterResource aksCluster, IEnumerable<string> manualPrecommands = default, Func<IKubernetes, Task> asyncTask = default)
{
if (configuration.ManualHelmDeployment)
{
ConsoleEx.WriteLine($"Helm chart written to disk at: {kubernetesManager.helmScriptsRootDirectory}");
ConsoleEx.WriteLine($"Please update values file if needed here: {kubernetesManager.TempHelmValuesYamlPath}");
foreach (var line in manualPrecommands ?? [])
{
ConsoleEx.WriteLine(line);
}
ConsoleEx.WriteLine($"Then, deploy the helm chart, and press Enter to continue.");
ConsoleEx.ReadLine();
return default;
}
else
{
var kubernetesClient = await kubernetesManager.GetKubernetesClientAsync(aksCluster);
await (asyncTask?.Invoke(kubernetesClient) ?? Task.CompletedTask);
await kubernetesManager.DeployHelmChartToClusterAsync();
return kubernetesClient;
}
}
private async Task<KeyVaultResource> ValidateAndGetExistingKeyVault()
{
if (string.IsNullOrWhiteSpace(configuration.KeyVaultName))
{
return null;
}
return (await GetKeyVaultAsync(configuration.KeyVaultName))
?? throw new ValidationException($"If key vault name is provided, it must already exist in region {configuration.RegionName}, and be accessible to the current user.", displayExample: false);
}
private async Task<PostgreSqlFlexibleServerResource> ValidateAndGetExistingPostgresqlServer()
{
if (string.IsNullOrWhiteSpace(configuration.PostgreSqlServerName))
{
return null;
}
return (await GetExistingPostgresqlService(configuration.PostgreSqlServerName))
?? throw new ValidationException($"If Postgresql server name is provided, the server must already exist in region {configuration.RegionName}, and be accessible to the current user.", displayExample: false);
}
private async Task<ContainerServiceManagedClusterResource> ValidateAndGetExistingAKSClusterAsync()
{
if (string.IsNullOrWhiteSpace(configuration.AksClusterName))
{
return null;
}
return (await GetExistingAKSClusterAsync(configuration.AksClusterName))