-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathdeploy.ps1
More file actions
1135 lines (999 loc) · 48.6 KB
/
deploy.ps1
File metadata and controls
1135 lines (999 loc) · 48.6 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
# ADME-Fabric Control Plane Deployment Script (PowerShell)
# Idempotent deployment - safe to run multiple times
param(
[string]$ResourceGroup = "rg-adme-control-plane",
[string]$Location = "eastus",
[string]$ContainerAppEnv = "env-adme-control-plane",
[string]$ContainerAppName = "adme-control-plane",
[string]$KeyVaultName = "", # Auto-generated if not provided
[string]$SqlServerName = "", # Auto-generated if not provided
[string]$SqlDatabaseName = "controlplane",
[string]$EncryptionKey = $env:ENCRYPTION_KEY,
[string]$LogLevel = "INFO",
[string]$VNetName = "vnet-adme-control-plane", # Virtual Network name
[string]$VNetAddressPrefix = "10.0.0.0/16", # VNet address space
[string]$SubnetContainerApps = "snet-container-apps", # Subnet for Container Apps
[string]$SubnetPrivateEndpoints = "snet-private-endpoints", # Subnet for Private Endpoints
[switch]$SkipKeyVault, # Use local encryption instead of Key Vault
[switch]$SkipAzureSql, # Use SQLite instead of Azure SQL
[switch]$UseSqlite, # Alias for SkipAzureSql (more intuitive)
[switch]$SkipPrivateLink # Skip Private Link setup (use public network)
)
$ErrorActionPreference = "Stop"
# Normalize parameters
if ($UseSqlite) { $SkipAzureSql = $true }
Write-Host "=========================================" -ForegroundColor Cyan
Write-Host "ADME-Fabric Control Plane Deployment" -ForegroundColor Cyan
Write-Host "=========================================" -ForegroundColor Cyan
Write-Host "Resource Group: $ResourceGroup"
Write-Host "Location: $Location"
Write-Host "Container App: $ContainerAppName"
Write-Host "Database: $(if ($SkipAzureSql) { 'SQLite (local)' } else { 'Azure SQL (Managed Identity)' })"
Write-Host "Key Vault: $(if ($SkipKeyVault) { 'Disabled' } else { 'Enabled (Managed Identity)' })"
Write-Host "Network: $(if ($SkipPrivateLink) { 'Public' } else { 'Private Link (VNet integrated)' })"
Write-Host "=========================================" -ForegroundColor Cyan
# Sanitize input parameters
if ($KeyVaultName -and ($KeyVaultName -match "\s")) {
Write-Host "⚠ Warning: KeyVaultName parameter contained spaces or invalid characters. Resetting to auto-detect." -ForegroundColor Yellow
$KeyVaultName = ""
}
# Generate encryption key if not provided (only used if Key Vault is skipped)
if ($EncryptionKey) {
# Clean up key if it contains comments or whitespace
$EncryptionKey = $EncryptionKey -replace '\s*#.*$', '' -replace '\s+', ''
}
if (-not $EncryptionKey) {
Write-Host "⚠ Generating encryption key..." -ForegroundColor Yellow
$EncryptionKey = python -c "from cryptography.fernet import Fernet; print(Fernet.generate_key().decode())"
Write-Host " → Key generated (for fallback encryption)" -ForegroundColor Green
}
# Variables for Key Vault
$KeyVaultUrl = $null
$UserAssignedIdentityId = $null
$UserAssignedIdentityClientId = $null
$UserAssignedIdentityPrincipalId = $null
# Get subscription ID early (needed for various resource IDs)
$subscriptionId = az account show --query id -o tsv
# 1. Create Resource Group (idempotent)
Write-Host "`n✓ Checking resource group..." -ForegroundColor Green
$rgExists = az group exists --name $ResourceGroup
if ($rgExists -eq "true") {
Write-Host " → Resource group already exists"
}
else {
Write-Host " → Creating resource group..."
az group create --name $ResourceGroup --location $Location --output table
Start-Sleep -Seconds 2 # Wait for resource group to propagate
Write-Host " ✓ Resource group created" -ForegroundColor Green
}
# 1.5 Create User-Assigned Managed Identity (required for ACR pulls and Key Vault)
Write-Host "`n✓ Checking User-Assigned Managed Identity..." -ForegroundColor Green
$IdentityName = "id-$ContainerAppName"
$identityExists = $false
try {
$identityCheck = az identity show --name $IdentityName --resource-group $ResourceGroup 2>$null
if ($identityCheck) {
$identityExists = $true
}
}
catch {
# Identity doesn't exist
}
if ($identityExists) {
Write-Host " → Managed Identity already exists: $IdentityName"
}
else {
Write-Host " → Creating User-Assigned Managed Identity..."
az identity create `
--name $IdentityName `
--resource-group $ResourceGroup `
--location $Location `
--output table
if ($LASTEXITCODE -ne 0) {
Write-Host " ✗ Failed to create Managed Identity (required for image pulls)." -ForegroundColor Red
exit 1
}
Write-Host " → Waiting for identity to propagate..."
Start-Sleep -Seconds 10
Write-Host " ✓ Managed Identity created" -ForegroundColor Green
}
# Get identity details (always used for registry auth; also for Key Vault if enabled)
$UserAssignedIdentityId = az identity show --name $IdentityName --resource-group $ResourceGroup --query id -o tsv
$UserAssignedIdentityClientId = az identity show --name $IdentityName --resource-group $ResourceGroup --query clientId -o tsv
$UserAssignedIdentityPrincipalId = az identity show --name $IdentityName --resource-group $ResourceGroup --query principalId -o tsv
Write-Host " → Identity Principal ID: $UserAssignedIdentityPrincipalId"
# 1.55 Create Virtual Network and Subnets for Private Link (if not skipping)
$VNetId = $null
$SubnetContainerAppsId = $null
$SubnetPrivateEndpointsId = $null
if (-not $SkipPrivateLink -and -not $SkipAzureSql) {
Write-Host "`n✓ Checking Virtual Network for Private Link..." -ForegroundColor Green
$vnetExists = $false
try {
$vnetCheck = az network vnet show --name $VNetName --resource-group $ResourceGroup 2>$null
if ($vnetCheck) {
$vnetExists = $true
}
}
catch {
# VNet doesn't exist
}
if ($vnetExists) {
Write-Host " → Virtual Network already exists: $VNetName"
$VNetId = az network vnet show --name $VNetName --resource-group $ResourceGroup --query id -o tsv
}
else {
Write-Host " → Creating Virtual Network: $VNetName..."
az network vnet create `
--name $VNetName `
--resource-group $ResourceGroup `
--location $Location `
--address-prefix $VNetAddressPrefix `
--output table
if ($LASTEXITCODE -ne 0) {
Write-Host " ⚠ Failed to create Virtual Network - falling back to public network" -ForegroundColor Yellow
$SkipPrivateLink = $true
}
else {
$VNetId = az network vnet show --name $VNetName --resource-group $ResourceGroup --query id -o tsv
Write-Host " ✓ Virtual Network created" -ForegroundColor Green
}
}
if (-not $SkipPrivateLink) {
# Create/check subnet for Container Apps Environment
Write-Host " → Checking subnet for Container Apps: $SubnetContainerApps..."
$subnetCAExists = $false
try {
$subnetCheck = az network vnet subnet show --vnet-name $VNetName --name $SubnetContainerApps --resource-group $ResourceGroup 2>$null
if ($subnetCheck) {
$subnetCAExists = $true
}
}
catch { }
if ($subnetCAExists) {
Write-Host " → Container Apps subnet already exists"
$SubnetContainerAppsId = az network vnet subnet show --vnet-name $VNetName --name $SubnetContainerApps --resource-group $ResourceGroup --query id -o tsv
}
else {
Write-Host " → Creating subnet for Container Apps..."
# Container Apps requires a /23 or larger subnet with delegation
az network vnet subnet create `
--name $SubnetContainerApps `
--resource-group $ResourceGroup `
--vnet-name $VNetName `
--address-prefix "10.0.0.0/23" `
--delegations "Microsoft.App/environments" `
--output table
if ($LASTEXITCODE -eq 0) {
$SubnetContainerAppsId = az network vnet subnet show --vnet-name $VNetName --name $SubnetContainerApps --resource-group $ResourceGroup --query id -o tsv
Write-Host " ✓ Container Apps subnet created" -ForegroundColor Green
}
else {
Write-Host " ⚠ Failed to create Container Apps subnet" -ForegroundColor Yellow
}
}
# Create/check subnet for Private Endpoints
Write-Host " → Checking subnet for Private Endpoints: $SubnetPrivateEndpoints..."
$subnetPEExists = $false
try {
$subnetPECheck = az network vnet subnet show --vnet-name $VNetName --name $SubnetPrivateEndpoints --resource-group $ResourceGroup 2>$null
if ($subnetPECheck) {
$subnetPEExists = $true
}
}
catch { }
if ($subnetPEExists) {
Write-Host " → Private Endpoints subnet already exists"
$SubnetPrivateEndpointsId = az network vnet subnet show --vnet-name $VNetName --name $SubnetPrivateEndpoints --resource-group $ResourceGroup --query id -o tsv
}
else {
Write-Host " → Creating subnet for Private Endpoints..."
az network vnet subnet create `
--name $SubnetPrivateEndpoints `
--resource-group $ResourceGroup `
--vnet-name $VNetName `
--address-prefix "10.0.2.0/24" `
--output table
if ($LASTEXITCODE -eq 0) {
$SubnetPrivateEndpointsId = az network vnet subnet show --vnet-name $VNetName --name $SubnetPrivateEndpoints --resource-group $ResourceGroup --query id -o tsv
Write-Host " ✓ Private Endpoints subnet created" -ForegroundColor Green
}
else {
Write-Host " ⚠ Failed to create Private Endpoints subnet" -ForegroundColor Yellow
}
}
}
}
# 1.6 Create Azure Key Vault (for secure secret storage)
if (-not $SkipKeyVault) {
Write-Host "`n✓ Checking Azure Key Vault..." -ForegroundColor Green
# Try to find existing Key Vault or generate name
if (-not $KeyVaultName) {
try {
$KeyVaultName = az keyvault list --resource-group $ResourceGroup --query "[0].name" -o tsv 2>$null
}
catch {
# No Key Vault exists
}
}
if ($KeyVaultName) {
Write-Host " → Using existing Key Vault: $KeyVaultName"
}
else {
Write-Host " → Creating Azure Key Vault..."
# Generate unique Key Vault name (3-24 chars, alphanumeric and hyphens)
$KeyVaultName = "kv-admecp-$(Get-Random -Maximum 99999)"
az keyvault create `
--name $KeyVaultName `
--resource-group $ResourceGroup `
--location $Location `
--enable-rbac-authorization true `
--output table
if ($LASTEXITCODE -ne 0) {
Write-Host " ⚠ Failed to create Key Vault - falling back to local encryption" -ForegroundColor Yellow
$SkipKeyVault = $true
$KeyVaultName = $null
}
else {
Write-Host " → Waiting for Key Vault to be ready..."
Start-Sleep -Seconds 5
Write-Host " ✓ Key Vault created: $KeyVaultName" -ForegroundColor Green
}
}
if ($KeyVaultName -and -not $SkipKeyVault) {
$KeyVaultUrl = az keyvault show --name $KeyVaultName --query properties.vaultUri -o tsv
Write-Host " → Key Vault URL: $KeyVaultUrl"
# Assign Key Vault Secrets Officer role to Managed Identity
Write-Host "`n✓ Configuring Key Vault access for Managed Identity..." -ForegroundColor Green
$subscriptionId = az account show --query id -o tsv
$kvScope = "/subscriptions/$subscriptionId/resourceGroups/$ResourceGroup/providers/Microsoft.KeyVault/vaults/$KeyVaultName"
# Check if role assignment already exists
$roleAssigned = $false
try {
$existingRole = az role assignment list --assignee $UserAssignedIdentityPrincipalId --scope $kvScope --query "[?roleDefinitionName=='Key Vault Secrets Officer']" -o tsv 2>$null
if ($existingRole) {
$roleAssigned = $true
}
}
catch {
# Role not assigned
}
if ($roleAssigned) {
Write-Host " → Role assignment already exists"
}
else {
Write-Host " → Attempting to assign 'Key Vault Secrets Officer' role..."
try {
$assignmentOutput = az role assignment create `
--role "Key Vault Secrets Officer" `
--assignee-object-id $UserAssignedIdentityPrincipalId `
--assignee-principal-type ServicePrincipal `
--scope $kvScope `
--output json 2>&1
if ($LASTEXITCODE -eq 0) {
Write-Host " ✓ Key Vault access configured" -ForegroundColor Green
}
else {
Write-Host " ⚠ Could not assign Key Vault role automatically" -ForegroundColor Yellow
Write-Host " This requires Owner or User Access Administrator role" -ForegroundColor Gray
Write-Host " The role can be assigned manually after deployment" -ForegroundColor Gray
# Save role assignment command for manual execution
$manualRoleCmd = "az role assignment create --role `"Key Vault Secrets Officer`" --assignee-object-id $UserAssignedIdentityPrincipalId --assignee-principal-type ServicePrincipal --scope `"$kvScope`""
}
}
catch {
Write-Host " ⚠ Could not assign Key Vault role: $_" -ForegroundColor Yellow
}
}
}
}
# 1.7 Create Azure SQL Database (for production persistence)
$SqlServerFqdn = $null
$DatabaseUrl = $null
if (-not $SkipAzureSql) {
Write-Host "`n✓ Checking Azure SQL Database..." -ForegroundColor Green
# Try to find existing SQL Server or generate name
if (-not $SqlServerName) {
try {
$SqlServerName = az sql server list --resource-group $ResourceGroup --query "[0].name" -o tsv 2>$null
}
catch {
# No SQL Server exists
}
}
if ($SqlServerName) {
Write-Host " → Using existing SQL Server: $SqlServerName"
$SqlServerFqdn = az sql server show --name $SqlServerName --resource-group $ResourceGroup --query fullyQualifiedDomainName -o tsv
}
else {
Write-Host " → Creating Azure SQL Server..."
# Generate unique SQL server name (3-63 chars, lowercase alphanumeric and hyphens)
$SqlServerName = "sql-admecp-$(Get-Random -Maximum 99999)"
# Create SQL Server with Azure AD-only authentication (no SQL admin password needed)
$currentUserObjectId = az ad signed-in-user show --query id -o tsv
$currentUserUpn = az ad signed-in-user show --query userPrincipalName -o tsv
az sql server create `
--name $SqlServerName `
--resource-group $ResourceGroup `
--location $Location `
--enable-ad-only-auth `
--external-admin-principal-type User `
--external-admin-name $currentUserUpn `
--external-admin-sid $currentUserObjectId `
--output table
if ($LASTEXITCODE -ne 0) {
Write-Host " ⚠ Failed to create SQL Server - falling back to SQLite" -ForegroundColor Yellow
$SkipAzureSql = $true
$SqlServerName = $null
}
else {
Write-Host " → Waiting for SQL Server to be ready..."
Start-Sleep -Seconds 5
$SqlServerFqdn = az sql server show --name $SqlServerName --resource-group $ResourceGroup --query fullyQualifiedDomainName -o tsv
Write-Host " ✓ SQL Server created: $SqlServerFqdn" -ForegroundColor Green
}
}
if ($SqlServerName -and -not $SkipAzureSql) {
# Configure network access based on Private Link setting
if (-not $SkipPrivateLink -and $SubnetPrivateEndpointsId) {
Write-Host " → Configuring SQL Server for Private Link only (no public access)..."
# Disable public network access
az sql server update `
--name $SqlServerName `
--resource-group $ResourceGroup `
--enable-public-network false `
--output none 2>$null
if ($LASTEXITCODE -eq 0) {
Write-Host " ✓ Public network access disabled on SQL Server" -ForegroundColor Green
}
else {
Write-Host " ⚠ Could not disable public network access" -ForegroundColor Yellow
}
# Create Private DNS Zone for SQL Server
Write-Host " → Checking Private DNS Zone for SQL Server..."
$SqlDnsZoneName = "privatelink.database.windows.net"
$dnsZoneExists = $false
try {
$dnsCheck = az network private-dns zone show --name $SqlDnsZoneName --resource-group $ResourceGroup 2>$null
if ($dnsCheck) { $dnsZoneExists = $true }
}
catch { }
if ($dnsZoneExists) {
Write-Host " → Private DNS Zone already exists: $SqlDnsZoneName"
}
else {
Write-Host " → Creating Private DNS Zone: $SqlDnsZoneName..."
az network private-dns zone create `
--name $SqlDnsZoneName `
--resource-group $ResourceGroup `
--output table
if ($LASTEXITCODE -eq 0) {
Write-Host " ✓ Private DNS Zone created" -ForegroundColor Green
}
}
# Link DNS Zone to VNet
Write-Host " → Checking VNet link for DNS Zone..."
$dnsLinkName = "link-$VNetName"
$dnsLinkExists = $false
try {
$linkCheck = az network private-dns link vnet show --zone-name $SqlDnsZoneName --name $dnsLinkName --resource-group $ResourceGroup 2>$null
if ($linkCheck) { $dnsLinkExists = $true }
}
catch { }
if ($dnsLinkExists) {
Write-Host " → VNet DNS link already exists"
}
else {
Write-Host " → Creating VNet link for DNS Zone..."
az network private-dns link vnet create `
--zone-name $SqlDnsZoneName `
--name $dnsLinkName `
--resource-group $ResourceGroup `
--virtual-network $VNetName `
--registration-enabled false `
--output table
if ($LASTEXITCODE -eq 0) {
Write-Host " ✓ VNet DNS link created" -ForegroundColor Green
}
}
# Create Private Endpoint for SQL Server
Write-Host " → Checking Private Endpoint for SQL Server..."
$SqlPrivateEndpointName = "pe-sql-$SqlServerName"
$peExists = $false
try {
$peCheck = az network private-endpoint show --name $SqlPrivateEndpointName --resource-group $ResourceGroup 2>$null
if ($peCheck) { $peExists = $true }
}
catch { }
if ($peExists) {
Write-Host " → Private Endpoint already exists: $SqlPrivateEndpointName"
}
else {
Write-Host " → Creating Private Endpoint for SQL Server..."
$SqlServerResourceId = "/subscriptions/$subscriptionId/resourceGroups/$ResourceGroup/providers/Microsoft.Sql/servers/$SqlServerName"
az network private-endpoint create `
--name $SqlPrivateEndpointName `
--resource-group $ResourceGroup `
--location $Location `
--vnet-name $VNetName `
--subnet $SubnetPrivateEndpoints `
--private-connection-resource-id $SqlServerResourceId `
--group-id sqlServer `
--connection-name "conn-$SqlServerName" `
--output table
if ($LASTEXITCODE -eq 0) {
Write-Host " ✓ Private Endpoint created" -ForegroundColor Green
# Configure DNS record for the private endpoint
Write-Host " → Creating DNS record for Private Endpoint..."
$peNicId = az network private-endpoint show --name $SqlPrivateEndpointName --resource-group $ResourceGroup --query "networkInterfaces[0].id" -o tsv
$peIpAddress = az network nic show --ids $peNicId --query "ipConfigurations[0].privateIPAddress" -o tsv
# Create A record in Private DNS Zone
$dnsRecordExists = $false
try {
$recordCheck = az network private-dns record-set a show --zone-name $SqlDnsZoneName --name $SqlServerName --resource-group $ResourceGroup 2>$null
if ($recordCheck) { $dnsRecordExists = $true }
}
catch { }
if (-not $dnsRecordExists) {
az network private-dns record-set a add-record `
--zone-name $SqlDnsZoneName `
--record-set-name $SqlServerName `
--resource-group $ResourceGroup `
--ipv4-address $peIpAddress `
--output none
if ($LASTEXITCODE -eq 0) {
Write-Host " ✓ DNS record created: $SqlServerName -> $peIpAddress" -ForegroundColor Green
}
}
else {
Write-Host " → DNS record already exists"
}
}
else {
Write-Host " ⚠ Failed to create Private Endpoint - ensure public access is available" -ForegroundColor Yellow
# Re-enable public access as fallback
az sql server update --name $SqlServerName --resource-group $ResourceGroup --enable-public-network true --output none 2>$null
$SkipPrivateLink = $true
}
}
}
else {
# Allow Azure services to access SQL Server (public network)
Write-Host " → Configuring firewall to allow Azure services..."
az sql server firewall-rule create `
--server $SqlServerName `
--resource-group $ResourceGroup `
--name AllowAzureServices `
--start-ip-address 0.0.0.0 `
--end-ip-address 0.0.0.0 `
--output none 2>$null
}
# Check/Create Database
Write-Host " → Checking database: $SqlDatabaseName..."
$dbExists = $false
try {
$dbCheck = az sql db show --server $SqlServerName --resource-group $ResourceGroup --name $SqlDatabaseName 2>$null
if ($dbCheck) { $dbExists = $true }
}
catch { }
if ($dbExists) {
Write-Host " → Database already exists"
}
else {
Write-Host " → Creating database (Serverless tier)..."
az sql db create `
--server $SqlServerName `
--resource-group $ResourceGroup `
--name $SqlDatabaseName `
--edition GeneralPurpose `
--compute-model Serverless `
--family Gen5 `
--capacity 1 `
--auto-pause-delay 60 `
--min-capacity 0.5 `
--output table
if ($LASTEXITCODE -ne 0) {
Write-Host " ⚠ Failed to create database - falling back to SQLite" -ForegroundColor Yellow
$SkipAzureSql = $true
}
else {
Write-Host " ✓ Database created: $SqlDatabaseName" -ForegroundColor Green
}
}
# Build DATABASE_URL for the app
if (-not $SkipAzureSql) {
$DatabaseUrl = "mssql+pyodbc://@${SqlServerFqdn}:1433/${SqlDatabaseName}?driver=ODBC+Driver+18+for+SQL+Server&Encrypt=yes&TrustServerCertificate=no"
Write-Host " → Database URL: $DatabaseUrl"
# Grant Managed Identity access to SQL Database
Write-Host "`n✓ Configuring SQL Database access for Managed Identity..." -ForegroundColor Green
Write-Host " → Creating database user for Managed Identity..."
Write-Host ""
Write-Host " ⚠ IMPORTANT: Run this SQL command in Azure Portal SQL Query Editor" -ForegroundColor Yellow
Write-Host " (or Azure Data Studio connected with your Azure AD account):" -ForegroundColor Yellow
Write-Host ""
$IdentityName = "id-$ContainerAppName"
$sqlCmd = @"
-- Run this in database: $SqlDatabaseName
CREATE USER [$IdentityName] FROM EXTERNAL PROVIDER;
ALTER ROLE db_datareader ADD MEMBER [$IdentityName];
ALTER ROLE db_datawriter ADD MEMBER [$IdentityName];
ALTER ROLE db_ddladmin ADD MEMBER [$IdentityName];
"@
Write-Host " $sqlCmd" -ForegroundColor Cyan
Write-Host ""
# Save SQL command for later
$sqlSetupPath = ".azure/sql-setup.sql"
$sqlCmd | Out-File -FilePath $sqlSetupPath -Force
Write-Host " → SQL setup script saved to: $sqlSetupPath" -ForegroundColor Gray
}
}
}
if ($SkipAzureSql) {
Write-Host "`n⚠ Using SQLite database (local/container storage)" -ForegroundColor Yellow
}
# 2. Create or get Azure Container Registry
Write-Host "`n✓ Checking Azure Container Registry..." -ForegroundColor Green
$AcrName = $null
try {
$AcrName = az acr list --resource-group $ResourceGroup --query "[0].name" -o tsv 2>$null
}
catch {
# Ignore error if no ACR exists
}
if ($AcrName) {
Write-Host " → Using existing ACR: $AcrName"
}
else {
Write-Host " → Creating Azure Container Registry..."
# Generate unique ACR name (lowercase, alphanumeric only)
$AcrName = "acradmecp$(Get-Random -Maximum 999999)"
Write-Host " → ACR Name: $AcrName"
az acr create `
--resource-group $ResourceGroup `
--name $AcrName `
--sku Basic `
--admin-enabled true `
--location $Location `
--output table
if ($LASTEXITCODE -ne 0) {
Write-Host " ✗ Failed to create ACR" -ForegroundColor Red
exit 1
}
Write-Host " → Waiting for ACR to be ready..."
Start-Sleep -Seconds 10
Write-Host " ✓ ACR created: $AcrName" -ForegroundColor Green
}
# Grant AcrPull to the user-assigned identity for image pulls
if ($UserAssignedIdentityPrincipalId) {
Write-Host " → Ensuring Managed Identity has AcrPull on $AcrName..."
$acrScope = az acr show --name $AcrName --query id -o tsv
try {
az role assignment create `
--role "AcrPull" `
--assignee-object-id $UserAssignedIdentityPrincipalId `
--assignee-principal-type ServicePrincipal `
--scope $acrScope `
--only-show-errors | Out-Null
Write-Host " ✓ AcrPull assigned" -ForegroundColor Green
}
catch {
Write-Host " ⚠ Could not assign AcrPull (requires Owner/User Access Administrator)" -ForegroundColor Yellow
}
}
# 3. Create Storage Account for SQLite persistence
Write-Host "`n✓ Checking Storage Account for database persistence..." -ForegroundColor Green
$StorageAccountName = $null
$StorageEnabled = $false
$StorageUsingIdentity = $false
try {
$StorageAccountName = az storage account list --resource-group $ResourceGroup --query "[0].name" -o tsv 2>$null
}
catch {
# Ignore error if no storage account exists
}
if ($StorageAccountName) {
Write-Host " → Using existing Storage Account: $StorageAccountName"
}
else {
Write-Host " → Creating Storage Account..."
# Generate unique storage account name (lowercase, alphanumeric only, max 24 chars)
$StorageAccountName = "stadmecp$(Get-Random -Maximum 999999)"
az storage account create `
--name $StorageAccountName `
--resource-group $ResourceGroup `
--location $Location `
--sku Standard_LRS `
--kind StorageV2 `
--allow-shared-key-access true `
--output table 2>$null
if ($LASTEXITCODE -ne 0) {
Write-Host " ⚠ Failed to create Storage Account (may be blocked by policy)" -ForegroundColor Yellow
$StorageAccountName = $null
}
else {
Write-Host " → Waiting for Storage Account to be ready..."
Start-Sleep -Seconds 5
Write-Host " ✓ Storage Account created: $StorageAccountName" -ForegroundColor Green
}
}
# 4. Create File Share for SQLite database
$FileShareName = "controlplane-data"
$StorageKey = $null
if ($StorageAccountName) {
Write-Host "`n✓ Checking File Share for SQLite database..." -ForegroundColor Green
# First try with storage key
try {
$StorageKey = az storage account keys list --resource-group $ResourceGroup --account-name $StorageAccountName --query "[0].value" -o tsv 2>$null
if ($StorageKey) {
$shareExists = az storage share exists --name $FileShareName --account-name $StorageAccountName --account-key $StorageKey --query "exists" -o tsv 2>$null
if ($shareExists -eq "true") {
Write-Host " → File Share already exists: $FileShareName"
$StorageEnabled = $true
}
else {
Write-Host " → Creating File Share..."
az storage share create `
--name $FileShareName `
--account-name $StorageAccountName `
--account-key $StorageKey `
--quota 1 `
--output table 2>$null
if ($LASTEXITCODE -eq 0) {
Write-Host " ✓ File Share created: $FileShareName" -ForegroundColor Green
$StorageEnabled = $true
}
}
}
}
catch {
Write-Host " → Storage key access not available, will try Managed Identity" -ForegroundColor Yellow
}
# If key-based access failed but we have Managed Identity, set up identity-based access
if (-not $StorageEnabled -and $UserAssignedIdentityPrincipalId) {
Write-Host " → Setting up Managed Identity access for storage..." -ForegroundColor Yellow
$storageScope = "/subscriptions/$subscriptionId/resourceGroups/$ResourceGroup/providers/Microsoft.Storage/storageAccounts/$StorageAccountName"
# Assign Storage File Data SMB Share Contributor role
Write-Host " → Assigning 'Storage File Data SMB Share Contributor' role..."
try {
az role assignment create `
--role "Storage File Data SMB Share Contributor" `
--assignee-object-id $UserAssignedIdentityPrincipalId `
--assignee-principal-type ServicePrincipal `
--scope $storageScope `
--output json 2>&1 | Out-Null
if ($LASTEXITCODE -eq 0) {
Write-Host " ✓ Storage role assigned to Managed Identity" -ForegroundColor Green
$StorageUsingIdentity = $true
}
}
catch {
Write-Host " ⚠ Could not assign storage role (requires Owner permissions)" -ForegroundColor Yellow
}
# Create file share using Azure CLI with login credentials
Write-Host " → Creating File Share using Azure AD auth..."
az storage share create `
--name $FileShareName `
--account-name $StorageAccountName `
--auth-mode login `
--quota 1 `
--output table 2>$null
if ($LASTEXITCODE -eq 0) {
Write-Host " ✓ File Share created with identity access" -ForegroundColor Green
$StorageEnabled = $true
}
else {
Write-Host " ⚠ Could not create file share" -ForegroundColor Yellow
}
}
}
if (-not $StorageEnabled) {
Write-Host "`n⚠ Storage not available" -ForegroundColor Yellow
Write-Host " → App will run without persistent storage (data in container)" -ForegroundColor Yellow
Write-Host " → Database will be recreated on each deployment" -ForegroundColor Gray
}
# 5. Build and push Docker image
Write-Host "`n✓ Cleaning caches before build..." -ForegroundColor Green
# Remove Python cache folders
Get-ChildItem -Path . -Directory -Recurse -Filter "__pycache__" -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
Get-ChildItem -Path . -Directory -Recurse -Filter ".pytest_cache" -ErrorAction SilentlyContinue | Remove-Item -Recurse -Force -ErrorAction SilentlyContinue
# Remove Streamlit cache
if (Test-Path ".streamlit") {
Remove-Item -Path ".streamlit" -Recurse -Force -ErrorAction SilentlyContinue
}
# Remove any .pyc files
Get-ChildItem -Path . -Recurse -Filter "*.pyc" -ErrorAction SilentlyContinue | Remove-Item -Force -ErrorAction SilentlyContinue
Write-Host " ✓ Caches cleaned" -ForegroundColor Green
Write-Host "`n✓ Building and pushing Docker image (no cache)..." -ForegroundColor Green
$ImageTag = Get-Date -Format "yyyyMMdd-HHmmss"
$BuildId = [guid]::NewGuid().ToString().Substring(0, 8)
az acr build `
--registry $AcrName `
--image "adme-control-plane:latest" `
--image "adme-control-plane:$ImageTag" `
--file Dockerfile `
--build-arg CACHE_BUST=$BuildId `
. `
--output table
Write-Host " ✓ Image pushed: adme-control-plane:latest" -ForegroundColor Green
# 4. Get ACR login server (identity will be used for auth)
Write-Host "`n✓ Getting ACR login server..." -ForegroundColor Green
$AcrServer = az acr show --name $AcrName --query loginServer -o tsv
# 5. Create Container Apps Environment (idempotent)
Write-Host "`n✓ Checking Container Apps Environment..." -ForegroundColor Green
$envExists = $false
$envIsVnetIntegrated = $false
try {
$envCheck = az containerapp env show --name $ContainerAppEnv --resource-group $ResourceGroup 2>$null
if ($envCheck) {
$envExists = $true
# Check if environment is already VNet integrated
$envVnet = az containerapp env show --name $ContainerAppEnv --resource-group $ResourceGroup --query "properties.vnetConfiguration.infrastructureSubnetId" -o tsv 2>$null
if ($envVnet) {
$envIsVnetIntegrated = $true
}
}
}
catch {
# Environment doesn't exist
}
if ($envExists) {
Write-Host " → Container Apps Environment already exists"
if ($envIsVnetIntegrated) {
Write-Host " → Environment is VNet integrated" -ForegroundColor Green
}
elseif (-not $SkipPrivateLink -and $SubnetContainerAppsId) {
Write-Host " ⚠ Warning: Existing environment is NOT VNet integrated." -ForegroundColor Yellow
Write-Host " To use Private Link, delete the existing environment and re-run deployment." -ForegroundColor Yellow
Write-Host " Command: az containerapp env delete --name $ContainerAppEnv --resource-group $ResourceGroup --yes" -ForegroundColor Gray
}
}
else {
# Create new environment - with or without VNet integration
if (-not $SkipPrivateLink -and $SubnetContainerAppsId) {
Write-Host " → Creating Container Apps Environment with VNet integration (this may take 5-7 minutes)..."
az containerapp env create `
--name $ContainerAppEnv `
--resource-group $ResourceGroup `
--location $Location `
--infrastructure-subnet-resource-id $SubnetContainerAppsId `
--internal-only false `
--output table
}
else {
Write-Host " → Creating Container Apps Environment (this may take 2-3 minutes)..."
az containerapp env create `
--name $ContainerAppEnv `
--resource-group $ResourceGroup `
--location $Location `
--output table
}
if ($LASTEXITCODE -ne 0) {
Write-Host " ✗ Failed to create Container Apps Environment" -ForegroundColor Red
exit 1
}
Write-Host " ✓ Environment created" -ForegroundColor Green
}
# 7. Add Azure Files storage to Container Apps Environment (if storage is available)
$StorageMountName = "sqlitedata"
if ($StorageEnabled) {
Write-Host "`n✓ Configuring Azure Files storage mount..." -ForegroundColor Green
# Check if storage already configured
$storageConfigured = $false
try {
$storageCheck = az containerapp env storage show --name $StorageMountName --resource-group $ResourceGroup --environment $ContainerAppEnv 2>$null
if ($storageCheck) {
$storageConfigured = $true
}
}
catch {
# Storage not configured
}
if ($storageConfigured) {
Write-Host " → Storage mount already configured"
}
else {
Write-Host " → Adding Azure Files storage to environment..."
if ($StorageKey -and -not $StorageUsingIdentity) {
# Use storage key authentication
Write-Host " → Using storage key authentication"
az containerapp env storage set `
--name $ContainerAppEnv `
--resource-group $ResourceGroup `
--storage-name $StorageMountName `
--azure-file-account-name $StorageAccountName `
--azure-file-account-key $StorageKey `
--azure-file-share-name $FileShareName `
--access-mode ReadWrite `
--output table
}
else {
# Use identity-based authentication (SMB)
Write-Host " → Using Managed Identity authentication"
# Note: Container Apps environment storage with identity requires the storage account resource ID
$storageResourceId = "/subscriptions/$subscriptionId/resourceGroups/$ResourceGroup/providers/Microsoft.Storage/storageAccounts/$StorageAccountName"
az containerapp env storage set `
--name $ContainerAppEnv `
--resource-group $ResourceGroup `
--storage-name $StorageMountName `
--azure-file-account-name $StorageAccountName `
--azure-file-share-name $FileShareName `
--access-mode ReadWrite `
--output table 2>$null
# If that fails, we may need to use key-based with identity fallback
if ($LASTEXITCODE -ne 0) {
Write-Host " ⚠ Identity-based storage mount not supported, trying alternative..." -ForegroundColor Yellow
}
}
if ($LASTEXITCODE -ne 0) {
Write-Host " ⚠ Failed to configure storage mount - continuing without persistence" -ForegroundColor Yellow
$StorageEnabled = $false
}
else {
Write-Host " ✓ Storage mount configured" -ForegroundColor Green
}
}
}
else {
Write-Host "`n⚠ Skipping storage mount (storage not available)" -ForegroundColor Yellow
}
# 8. Deploy or Update Container App
Write-Host "`n✓ Deploying Container App..." -ForegroundColor Green
$appExists = $false
try {
$appCheck = az containerapp show --name $ContainerAppName --resource-group $ResourceGroup 2>$null
if ($appCheck) {
$appExists = $true
}
}
catch {
# App doesn't exist
}
# Check for Key Vault setup
$useKeyVault = (-not $SkipKeyVault -and $UserAssignedIdentityId)
# Use template-based YAML generation (more reliable than string building)
$templatePath = ".azure/containerapp.template.yaml"
$yamlPath = ".azure/containerapp.yaml"
if (-not (Test-Path $templatePath)) {
Write-Host " ✗ Template file not found: $templatePath" -ForegroundColor Red
exit 1
}
# Read template
$yamlContent = Get-Content $templatePath -Raw
# Replace placeholders (using PLACEHOLDER_ prefix to avoid YAML parsing issues)
$yamlContent = $yamlContent -replace 'PLACEHOLDER_LOCATION', $Location
$yamlContent = $yamlContent -replace 'PLACEHOLDER_APP_NAME', $ContainerAppName
$yamlContent = $yamlContent -replace 'PLACEHOLDER_RESOURCE_GROUP', $ResourceGroup
$yamlContent = $yamlContent -replace 'PLACEHOLDER_IDENTITY_ID', $UserAssignedIdentityId
$yamlContent = $yamlContent -replace 'PLACEHOLDER_ENVIRONMENT_ID', "/subscriptions/$subscriptionId/resourceGroups/$ResourceGroup/providers/Microsoft.App/managedEnvironments/$ContainerAppEnv"
$yamlContent = $yamlContent -replace 'PLACEHOLDER_ACR_SERVER', $AcrServer
$yamlContent = $yamlContent -replace 'PLACEHOLDER_IMAGE', "${AcrServer}/adme-control-plane:latest"
$yamlContent = $yamlContent -replace 'PLACEHOLDER_ENCRYPTION_KEY', $EncryptionKey
$yamlContent = $yamlContent -replace 'PLACEHOLDER_LOG_LEVEL', $LogLevel
$yamlContent = $yamlContent -replace 'PLACEHOLDER_KEYVAULT_URL', $(if ($useKeyVault) { $KeyVaultUrl } else { '' })
$yamlContent = $yamlContent -replace 'PLACEHOLDER_IDENTITY_CLIENT_ID', $(if ($useKeyVault -or $DatabaseUrl) { $UserAssignedIdentityClientId } else { '' })
$yamlContent = $yamlContent -replace 'PLACEHOLDER_DATABASE_PATH', $(if ($StorageEnabled) { '/mnt/data/control_plane.db' } else { '/app/data/control_plane.db' })
$yamlContent = $yamlContent -replace 'PLACEHOLDER_DATABASE_URL', $(if ($DatabaseUrl) { $DatabaseUrl } else { '' })
# If storage not enabled, remove volume sections
if (-not $StorageEnabled) {
Write-Host " → Deploying without persistent storage$(if ($useKeyVault) { ' (with Key Vault)' })..." -ForegroundColor Yellow
# Remove volumeMounts section
$yamlContent = $yamlContent -replace '(?ms) volumeMounts:\r?\n - volumeName: sqlitedata\r?\n mountPath: /mnt/data\r?\n', ''