-
Notifications
You must be signed in to change notification settings - Fork 115
Expand file tree
/
Copy pathazure.yaml
More file actions
1241 lines (1070 loc) · 57 KB
/
Copy pathazure.yaml
File metadata and controls
1241 lines (1070 loc) · 57 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
name: simplechat
metadata:
template: custom
infra:
provider: bicep
path: bicep
services:
web:
project: ../application/single_app
language: python
host: appservice
# Container-based App Service deployment.
# Gunicorn startup is provided by application/single_app/Dockerfile,
# so no App Service Stack Settings startup command is required.
docker:
context: ../../
dockerfile: application/single_app/Dockerfile
hooks:
preprovision:
# this is run before infrastructure provisioning begins
# primary use is to explain prerequisites and stop early when required networking inputs are missing
posix:
shell: sh
run: |
set -e
echo "========================================"
echo "PRE-PROVISION: Validating prerequisites"
echo "========================================"
python3 ./bicep/validate_azd_prerequisites.py
windows:
shell: pwsh
run: |
Write-Host "========================================"
Write-Host "PRE-PROVISION: Validating prerequisites"
Write-Host "========================================"
python .\bicep\validate_azd_prerequisites.py
postprovision:
# this is run after the infrastructure has been provisioned but before services are deployed.
# primary use is to configure application settings and permissions
posix:
shell: sh
run: |
set -e
echo "========================================"
echo "POST-PROVISION: Starting configuration"
echo "========================================"
export var_acrName=${var_acrname}
export var_configureApplication=${var_configureApplication}
export var_cosmosDb_uri=${var_cosmosDb_uri}
export var_cosmosDb_accountName=${var_cosmosDb_accountName}
export var_subscriptionId=${AZURE_SUBSCRIPTION_ID}
export var_rgName=${var_rgName}
export var_keyVaultUri=${var_keyVaultUri}
export var_keyVaultName=${var_keyVaultName}
export var_authenticationType=${var_authenticationType}
export var_redisAuthenticationType=${var_redisAuthenticationType}
export var_openAIEndpoint=${var_openAIEndpoint}
export var_openAISubscriptionId=${var_openAISubscriptionId}
export var_openAIResourceGroup=${var_openAIResourceGroup}
export var_openAIGPTModels='${var_openAIGPTModels}'
export var_openAIEmbeddingModels='${var_openAIEmbeddingModels}'
export var_blobStorageEndpoint=${var_blobStorageEndpoint}
export var_contentSafetyEndpoint=${var_contentSafetyEndpoint}
export var_searchServiceEndpoint=${var_searchServiceEndpoint}
export var_documentIntelligenceServiceEndpoint=${var_documentIntelligenceServiceEndpoint}
export var_redisCacheHostName=${var_redisCacheHostName}
export var_videoIndexerArmApiVersion=${var_videoIndexerArmApiVersion}
export var_videoIndexerEndpoint=${var_videoIndexerEndpoint}
export var_videoIndexerName=${var_videoIndexerName}
export var_deploymentLocation=${var_deploymentLocation}
export var_videoIndexerAccountId=${var_videoIndexerAccountId}
export var_speechServiceEndpoint=${var_speechServiceEndpoint}
is_mfa_error() {
printf '%s' "$1" | grep -qiE 'AADSTS50076|multi-factor authentication|claims challenge'
}
print_manual_cosmos_firewall_message() {
runner_public_ip="$1"
echo "✗ ERROR: Azure CLI requires multi-factor authentication before it can update the Cosmos DB firewall." >&2
echo " Manually add IP ${runner_public_ip} to Azure Portal -> Cosmos DB account '${var_cosmosDb_accountName}' -> Networking -> Firewall in resource group '${var_rgName}'." >&2
echo " If you already added the IP manually, allow up to 30 minutes for the firewall change to propagate before rerunning 'azd provision' or 'azd up'." >&2
}
test_cosmos_runner_access() {
python3 -c "from azure.cosmos import CosmosClient; import os; client = CosmosClient(os.environ['var_cosmosDb_uri'], os.environ['var_cosmosDb_key']); next(client.list_databases(), None); print('ok')" >/dev/null 2>&1
}
runner_ip_matches_rules() {
current_rules="$1"
runner_public_ip="$2"
CURRENT_RULES="${current_rules}" RUNNER_PUBLIC_IP="${runner_public_ip}" python3 -c "import ipaddress, os; rules = [rule.strip() for rule in os.environ.get('CURRENT_RULES', '').split(',') if rule.strip()]; ip = ipaddress.ip_address(os.environ['RUNNER_PUBLIC_IP']); matched = any(ip in ipaddress.ip_network(rule, strict=False) if '/' in rule else ip == ipaddress.ip_address(rule) for rule in rules); raise SystemExit(0 if matched else 1)"
}
wait_for_cosmos_runner_access() {
runner_public_ip="$1"
max_attempts=20
attempt=1
while [ ${attempt} -le ${max_attempts} ]; do
if test_cosmos_runner_access; then
echo "✓ CosmosDB data-plane access is now available for deployment runner IP ${runner_public_ip}"
return 0
fi
echo " Waiting for CosmosDB firewall propagation for ${runner_public_ip} (${attempt}/${max_attempts})..."
sleep 30
attempt=$((attempt + 1))
done
echo "✗ ERROR: CosmosDB firewall rule for ${runner_public_ip} is configured but data-plane access is still not available." >&2
echo " Firewall changes can take up to 30 minutes to propagate. Wait and rerun 'azd provision' or 'azd up'." >&2
return 1
}
python_is_virtual_environment() {
python3 -c "import sys; raise SystemExit(0 if sys.prefix != getattr(sys, 'base_prefix', sys.prefix) else 1)"
}
install_postprovision_python_dependencies() {
install_output_file=$(mktemp)
if python_is_virtual_environment; then
python3 -m pip install -r ./bicep/requirements.txt > "${install_output_file}" 2>&1
else
python3 -m pip install --user -r ./bicep/requirements.txt > "${install_output_file}" 2>&1
fi
install_exit_code=$?
if [ ${install_exit_code} -ne 0 ]; then
cat "${install_output_file}" >&2
rm -f "${install_output_file}"
return ${install_exit_code}
fi
rm -f "${install_output_file}"
return 0
}
ensure_cosmos_runner_access() {
current_rules=$(az cosmosdb show \
--name ${var_cosmosDb_accountName} \
--resource-group ${var_rgName} \
--subscription ${AZURE_SUBSCRIPTION_ID} \
--query "properties.ipRules[].ipAddressOrRange" \
-o tsv 2>/dev/null | tr '\n' ',' | sed 's/,$//')
runner_public_ip=$(python3 -c "import urllib.request; print(urllib.request.urlopen('https://api.ipify.org', timeout=10).read().decode().strip())")
if [ -z "${runner_public_ip}" ]; then
echo "✗ ERROR: Failed to resolve the deployment runner public IP for Cosmos firewall access" >&2
exit 1
fi
if runner_ip_matches_rules "${current_rules}" "${runner_public_ip}"; then
echo "✓ Deployment runner IP ${runner_public_ip} is already configured on the CosmosDB firewall"
wait_for_cosmos_runner_access "${runner_public_ip}" || exit 1
return
fi
updated_rules=$(python3 -c "existing = '${current_rules}'.strip(','); runner = '${runner_public_ip}'; rules = [rule.strip() for rule in existing.split(',') if rule.strip()]; rules.append(runner); deduped = []; [deduped.append(rule) for rule in rules if rule not in deduped]; print(','.join(deduped))")
update_output=$(az cosmosdb update \
--name ${var_cosmosDb_accountName} \
--resource-group ${var_rgName} \
--subscription ${AZURE_SUBSCRIPTION_ID} \
--ip-range-filter "${updated_rules}" 2>&1)
if [ $? -ne 0 ]; then
if is_mfa_error "${update_output}"; then
print_manual_cosmos_firewall_message "${runner_public_ip}"
echo " Checking whether CosmosDB access is already available without an Azure CLI firewall update..." >&2
wait_for_cosmos_runner_access "${runner_public_ip}" || exit 1
return
fi
echo "✗ ERROR: Failed to allow deployment runner IP ${runner_public_ip} through the CosmosDB firewall" >&2
echo "${update_output}" >&2
exit 1
fi
echo "✓ Added deployment runner IP ${runner_public_ip} to the CosmosDB firewall"
wait_for_cosmos_runner_access "${runner_public_ip}" || exit 1
}
if [ "${var_configureApplication}" = "true" ]; then
echo ""
echo "[1/4] Granting permissions to CosmosDB..."
if bash ./bicep/cosmosDb-postDeployPerms.sh; then
echo "✓ CosmosDB permissions granted successfully"
else
echo "✗ ERROR: Failed to grant CosmosDB permissions" >&2
exit 1
fi
echo ""
echo "[2/4] Installing Python dependencies..."
if install_postprovision_python_dependencies; then
echo "✓ Dependencies installed successfully"
else
echo "✗ ERROR: Failed to install Python dependencies" >&2
exit 1
fi
export var_cosmosDb_key=$(az cosmosdb keys list \
--name ${var_cosmosDb_accountName} \
--resource-group ${var_rgName} \
--subscription ${AZURE_SUBSCRIPTION_ID} \
--query primaryMasterKey \
-o tsv)
if [ -z "${var_cosmosDb_key}" ]; then
echo "✗ ERROR: Failed to resolve Cosmos DB primary key for post-deployment configuration" >&2
exit 1
fi
if test_cosmos_runner_access; then
echo "✓ Deployment runner already has CosmosDB data-plane access"
else
ensure_cosmos_runner_access
fi
echo ""
echo "[3/4] Running post-deployment configuration..."
if .venv/bin/python3 ./bicep/postconfig.py; then
echo "✓ Post-deployment configuration completed"
else
echo "✗ ERROR: Post-deployment configuration failed" >&2
exit 1
fi
echo ""
echo "[4/4] Restarting web service to apply settings..."
if az webapp restart --name ${var_webService} --resource-group ${var_rgName}; then
echo "✓ Web service restarted successfully"
else
echo "✗ ERROR: Failed to restart web service" >&2
exit 1
fi
echo ""
echo "========================================"
echo "POST-PROVISION: Completed successfully"
echo "========================================"
else
echo ""
echo "ℹ Skipping post-deployment configuration (var_configureApplication is not true)"
echo ""
echo "========================================"
echo "POST-PROVISION: Completed (skipped)"
echo "========================================"
fi
windows:
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
function Import-AzdHookEnvironment {
param(
[string[]]$Names
)
foreach ($name in $Names) {
$currentValue = [Environment]::GetEnvironmentVariable($name, 'Process')
if (-not [string]::IsNullOrWhiteSpace($currentValue)) {
continue
}
$resolvedValue = azd env get-value $name 2>$null
if ($LASTEXITCODE -eq 0) {
$resolvedText = ($resolvedValue | Out-String).Trim()
[Environment]::SetEnvironmentVariable($name, $resolvedText, 'Process')
}
}
}
Import-AzdHookEnvironment -Names @(
'AZURE_SUBSCRIPTION_ID',
'var_acrName',
'var_authenticationType',
'var_blobStorageEndpoint',
'var_configureApplication',
'var_contentSafetyEndpoint',
'var_cosmosDb_accountName',
'var_cosmosDb_uri',
'var_deploymentLocation',
'var_documentIntelligenceServiceEndpoint',
'var_keyVaultName',
'var_keyVaultUri',
'var_openAIEmbeddingModels',
'var_openAIEndpoint',
'var_openAIGPTModels',
'var_openAIResourceGroup',
'var_openAISubscriptionId',
'var_redisAuthenticationType',
'var_redisCacheHostName',
'var_rgName',
'var_searchServiceEndpoint',
'var_speechServiceEndpoint',
'var_subscriptionId',
'var_videoIndexerAccountId',
'var_videoIndexerArmApiVersion',
'var_videoIndexerEndpoint',
'var_videoIndexerName',
'var_webService'
)
function Get-TargetSubscriptionId {
if (-not [string]::IsNullOrWhiteSpace($env:AZURE_SUBSCRIPTION_ID)) {
return $env:AZURE_SUBSCRIPTION_ID
}
if (-not [string]::IsNullOrWhiteSpace($env:var_subscriptionId)) {
return $env:var_subscriptionId
}
$resolvedSubscriptionId = az account show --query id -o tsv
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($resolvedSubscriptionId)) {
throw 'Failed to resolve the target subscription ID for postprovision.'
}
return $resolvedSubscriptionId
}
function Test-AzureCliAuthRequired {
param(
[string]$Output
)
return $Output -match 'InteractionRequired|Need user interaction|AADSTS50076|multi-factor authentication|claims challenge'
}
function Get-AzureCliLoginCommand {
$tenantId = az account show --query tenantId -o tsv 2>$null
if ($LASTEXITCODE -eq 0 -and -not [string]::IsNullOrWhiteSpace($tenantId)) {
return "az login --tenant `"$($tenantId.Trim())`" --scope `"https://management.core.windows.net//.default`""
}
return 'az login --scope "https://management.core.windows.net//.default"'
}
function Assert-ResourceLookupSucceeded {
param(
[string]$Operation,
[int]$ExitCode,
[string]$Output
)
if ($ExitCode -eq 0) {
return
}
if (Test-AzureCliAuthRequired -Output $Output) {
$loginCommand = Get-AzureCliLoginCommand
throw "Azure CLI requires interactive authentication while $Operation. Run $loginCommand, then rerun 'azd deploy'.`n$Output"
}
}
function Resolve-ResourceGroupName {
$subscriptionId = Get-TargetSubscriptionId
if (-not [string]::IsNullOrWhiteSpace($env:var_rgName)) {
$groupExistsOutput = az group exists --name $env:var_rgName --subscription $subscriptionId -o tsv 2>&1 | Out-String
$groupExistsExitCode = $LASTEXITCODE
Assert-ResourceLookupSucceeded -Operation "checking resource group '$($env:var_rgName)'" -ExitCode $groupExistsExitCode -Output $groupExistsOutput
if ($groupExistsExitCode -eq 0 -and $groupExistsOutput.Trim() -eq 'true') {
return $env:var_rgName
}
}
$cosmosAccountName = $env:var_cosmosDb_accountName
if ([string]::IsNullOrWhiteSpace($cosmosAccountName) -and -not [string]::IsNullOrWhiteSpace($env:var_cosmosDb_uri)) {
$cosmosAccountName = ([System.Uri]$env:var_cosmosDb_uri).Host.Split('.')[0]
}
$resolvedResourceGroup = $null
if (-not [string]::IsNullOrWhiteSpace($cosmosAccountName)) {
$cosmosLookupOutput = az cosmosdb list --subscription $subscriptionId --query "[?name=='$cosmosAccountName'].resourceGroup | [0]" -o tsv 2>&1 | Out-String
$cosmosLookupExitCode = $LASTEXITCODE
Assert-ResourceLookupSucceeded -Operation "resolving Cosmos DB account '$cosmosAccountName'" -ExitCode $cosmosLookupExitCode -Output $cosmosLookupOutput
if ($cosmosLookupExitCode -eq 0) {
$resolvedResourceGroup = $cosmosLookupOutput.Trim()
}
}
if ([string]::IsNullOrWhiteSpace($resolvedResourceGroup) -and -not [string]::IsNullOrWhiteSpace($env:var_webService)) {
$webAppLookupOutput = az resource list --subscription $subscriptionId --name "$($env:var_webService)" --resource-type Microsoft.Web/sites --query "[0].resourceGroup" -o tsv 2>&1 | Out-String
$webAppLookupExitCode = $LASTEXITCODE
Assert-ResourceLookupSucceeded -Operation "resolving Web App '$($env:var_webService)'" -ExitCode $webAppLookupExitCode -Output $webAppLookupOutput
if ($webAppLookupExitCode -eq 0) {
$resolvedResourceGroup = $webAppLookupOutput.Trim()
}
}
if ([string]::IsNullOrWhiteSpace($resolvedResourceGroup)) {
throw 'Unable to resolve resource group from var_rgName, Cosmos DB, or Web App.'
}
$env:var_rgName = $resolvedResourceGroup
return $resolvedResourceGroup
}
function Ensure-CosmosRunnerAccess {
param(
[string]$AccountName,
[string]$ResourceGroupName,
[string]$SubscriptionId
)
$currentRules = az cosmosdb show --name $AccountName --resource-group $ResourceGroupName --subscription $SubscriptionId --query "properties.ipRules[].ipAddressOrRange" -o tsv 2>$null
$runnerPublicIp = (Invoke-RestMethod -Uri 'https://api.ipify.org' -TimeoutSec 10).Trim()
if ([string]::IsNullOrWhiteSpace($runnerPublicIp)) {
throw 'Failed to resolve the deployment runner public IP for Cosmos DB firewall access.'
}
$ruleList = @()
if (-not [string]::IsNullOrWhiteSpace($currentRules)) {
$ruleList = $currentRules -split "`r?`n" | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }
}
if (Test-RunnerIpMatchesRules -Rules $ruleList -RunnerPublicIp $runnerPublicIp) {
Write-Host "✓ Deployment runner IP $runnerPublicIp is already configured on the CosmosDB firewall"
Wait-ForCosmosRunnerAccess -RunnerPublicIp $runnerPublicIp
return
}
$updatedRules = @($ruleList + $runnerPublicIp | Select-Object -Unique) -join ','
$updateOutput = az cosmosdb update --name $AccountName --resource-group $ResourceGroupName --subscription $SubscriptionId --ip-range-filter $updatedRules 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) {
if ($updateOutput -match 'AADSTS50076|multi-factor authentication|claims challenge') {
Write-Warning "Azure CLI requires multi-factor authentication before it can update the Cosmos DB firewall. Manually add IP $runnerPublicIp to Azure Portal -> Cosmos DB account '$AccountName' -> Networking -> Firewall in resource group '$ResourceGroupName'. Firewall changes can take up to 30 minutes to propagate, so wait before rerunning 'azd provision' or 'azd up'."
Write-Host " Checking whether CosmosDB access is already available without an Azure CLI firewall update..."
Wait-ForCosmosRunnerAccess -RunnerPublicIp $runnerPublicIp
return
}
throw "Failed to allow deployment runner IP $runnerPublicIp through the Cosmos DB firewall.`n$updateOutput"
}
Write-Host "✓ Added deployment runner IP $runnerPublicIp to the CosmosDB firewall"
Wait-ForCosmosRunnerAccess -RunnerPublicIp $runnerPublicIp
}
function Test-CosmosRunnerAccess {
$accessCheckOutput = python -c "from azure.cosmos import CosmosClient; import os; client = CosmosClient(os.environ['var_cosmosDb_uri'], os.environ['var_cosmosDb_key']); next(client.list_databases(), None); print('ok')" 2>&1 | Out-String
return $LASTEXITCODE -eq 0
}
function Test-RunnerIpMatchesRules {
param(
[string[]]$Rules,
[string]$RunnerPublicIp
)
$env:CURRENT_RULES = ($Rules | Where-Object { -not [string]::IsNullOrWhiteSpace($_) }) -join ','
$env:RUNNER_PUBLIC_IP = $RunnerPublicIp
python -c "import ipaddress, os; rules = [rule.strip() for rule in os.environ.get('CURRENT_RULES', '').split(',') if rule.strip()]; ip = ipaddress.ip_address(os.environ['RUNNER_PUBLIC_IP']); matched = any(ip in ipaddress.ip_network(rule, strict=False) if '/' in rule else ip == ipaddress.ip_address(rule) for rule in rules); raise SystemExit(0 if matched else 1)" 2>$null
return $LASTEXITCODE -eq 0
}
function Wait-ForCosmosRunnerAccess {
param(
[string]$RunnerPublicIp
)
for ($attempt = 1; $attempt -le 20; $attempt++) {
if (Test-CosmosRunnerAccess) {
Write-Host "✓ CosmosDB data-plane access is now available for deployment runner IP $RunnerPublicIp"
return
}
Write-Host " Waiting for CosmosDB firewall propagation for $RunnerPublicIp ($attempt/20)..."
Start-Sleep -Seconds 30
}
throw "CosmosDB firewall rule for $RunnerPublicIp is configured but data-plane access is still not available. Firewall changes can take up to 30 minutes to propagate. Wait and rerun 'azd provision' or 'azd up'."
}
function Test-PythonVirtualEnvironment {
python -c "import sys; raise SystemExit(0 if sys.prefix != getattr(sys, 'base_prefix', sys.prefix) else 1)" 2>$null
return $LASTEXITCODE -eq 0
}
function Install-PostprovisionPythonDependencies {
$outputFile = [System.IO.Path]::GetTempFileName()
try {
if (Test-PythonVirtualEnvironment) {
python -m pip install -r .\bicep\requirements.txt *> $outputFile
} else {
python -m pip install --user -r .\bicep\requirements.txt *> $outputFile
}
if ($LASTEXITCODE -ne 0) {
Get-Content -Path $outputFile -Raw | Write-Error
return $false
}
return $true
} finally {
Remove-Item -Path $outputFile -ErrorAction SilentlyContinue
}
}
Write-Host "========================================"
Write-Host "POST-PROVISION: Starting configuration"
Write-Host "========================================"
if ($env:var_configureApplication -eq 'true') {
Write-Host ""
Write-Host "[1/4] Granting permissions to CosmosDB..."
$subscriptionId = Get-TargetSubscriptionId
$rgName = Resolve-ResourceGroupName
$cosmosUri = $env:var_cosmosDb_uri
$accountName = ([System.Uri]$cosmosUri).Host.Split('.')[0]
$objectId = az ad signed-in-user show --query id -o tsv
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($objectId)) {
throw 'Failed to resolve the signed-in user object ID for Cosmos DB role assignment.'
}
$scope = "/subscriptions/$subscriptionId/resourceGroups/$rgName/providers/Microsoft.DocumentDB/databaseAccounts/$accountName"
$roleId = az role definition list --name Contributor --subscription $subscriptionId --query "[0].id" -o tsv
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($roleId)) {
throw 'Failed to resolve the Contributor role definition ID.'
}
$controlPlaneOutput = az role assignment create --assignee-object-id $objectId --assignee-principal-type User --role $roleId --scope $scope 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) {
if ($controlPlaneOutput -match 'already exists|RoleAssignmentExists|Conflict') {
Write-Host "Control-plane role already exists."
} elseif ($controlPlaneOutput -match 'AADSTS50076|multi-factor authentication|claims challenge') {
Write-Warning "Azure CLI requires multi-factor authentication before it can create the Cosmos DB control-plane role assignment."
Write-Warning "Continuing with Cosmos DB key-based post-deployment configuration."
} else {
throw "Failed to create the Cosmos DB control-plane role assignment.`n$controlPlaneOutput"
}
}
$dataPlaneRoleId = az cosmosdb sql role definition list --account-name $accountName --resource-group $rgName --subscription $subscriptionId --query "[?roleName=='Cosmos DB Built-in Data Contributor'].id | [0]" -o tsv
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($dataPlaneRoleId)) {
throw 'Failed to resolve the Cosmos DB built-in data contributor role definition ID.'
}
$dataPlaneOutput = az cosmosdb sql role assignment create --account-name $accountName --resource-group $rgName --subscription $subscriptionId --scope / --principal-id $objectId --role-definition-id $dataPlaneRoleId 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) {
if ($dataPlaneOutput -match 'already exists|RoleAssignmentExists|Conflict') {
Write-Host "Data-plane role already exists."
} elseif ($dataPlaneOutput -match 'AADSTS50076|multi-factor authentication|claims challenge') {
Write-Warning "Azure CLI requires multi-factor authentication before it can create the Cosmos DB data-plane role assignment."
Write-Warning "Continuing with Cosmos DB key-based post-deployment configuration."
} else {
throw "Failed to create the Cosmos DB data-plane role assignment.`n$dataPlaneOutput"
}
}
Write-Host "✓ CosmosDB permissions granted successfully"
Write-Host ""
Write-Host "[2/4] Installing Python dependencies..."
if (-not (Install-PostprovisionPythonDependencies)) {
throw 'Failed to install Python dependencies.'
}
Write-Host "✓ Dependencies installed successfully"
$cosmosDbKeyOutput = az cosmosdb keys list --name $accountName --resource-group $rgName --subscription $subscriptionId --query primaryMasterKey -o tsv 2>&1 | Out-String
if ($LASTEXITCODE -ne 0) {
if ($cosmosDbKeyOutput -match 'AADSTS50076|multi-factor authentication|claims challenge') {
throw "Azure CLI requires multi-factor authentication before it can read the Cosmos DB primary key. Run 'az login --scope https://management.azure.com//.default' and rerun 'azd provision' or 'azd up'."
}
throw "Failed to resolve the Cosmos DB primary key for post-deployment configuration.`n$cosmosDbKeyOutput"
}
$env:var_cosmosDb_key = $cosmosDbKeyOutput.Trim()
if ([string]::IsNullOrWhiteSpace($env:var_cosmosDb_key)) {
throw 'Failed to resolve the Cosmos DB primary key for post-deployment configuration.'
}
if (Test-CosmosRunnerAccess) {
Write-Host "✓ Deployment runner already has CosmosDB data-plane access"
} else {
Ensure-CosmosRunnerAccess -AccountName $accountName -ResourceGroupName $rgName -SubscriptionId $subscriptionId
}
Write-Host ""
Write-Host "[3/4] Running post-deployment configuration..."
python .\bicep\postconfig.py
if ($LASTEXITCODE -ne 0) {
throw 'Post-deployment configuration failed.'
}
Write-Host "✓ Post-deployment configuration completed"
Write-Host ""
Write-Host "[4/4] Restarting web service to apply settings..."
az webapp restart --name $env:var_webService --resource-group $rgName --subscription $subscriptionId | Out-Null
if ($LASTEXITCODE -ne 0) {
throw 'Failed to restart web service.'
}
Write-Host "✓ Web service restarted successfully"
Write-Host ""
Write-Host "========================================"
Write-Host "POST-PROVISION: Completed successfully"
Write-Host "========================================"
} else {
Write-Host ""
Write-Host "Skipping post-deployment configuration (var_configureApplication is not true)"
Write-Host ""
Write-Host "========================================"
Write-Host "POST-PROVISION: Completed (skipped)"
Write-Host "========================================"
}
predeploy:
# this is run after infrastructure and postprovisioning but before service deployment
# primary use is to build and push container images
posix:
shell: sh
run: |
set -e
cleanup_on_error() {
local exit_code=$?
echo ""
echo "✗ ERROR: Deployment failed at step: $1" >&2
echo "Attempting to restart web service..." >&2
az webapp start --name ${var_webService} --resource-group ${var_rgName} 2>/dev/null || true
exit ${exit_code}
}
echo "========================================"
echo "PRE-DEPLOY: Building and pushing image"
echo "========================================"
cd ..
timestamp="$(date +"%Y%m%d-%H%M%S")"
install_chromium="${SIMPLECHAT_INSTALL_CHROMIUM:-true}"
install_chromium="$(printf '%s' "${install_chromium}" | tr '[:upper:]' '[:lower:]')"
case "${install_chromium}" in
true|1|yes|on) install_chromium="true" ;;
false|0|no|off) install_chromium="false" ;;
*)
echo "⚠ Invalid SIMPLECHAT_INSTALL_CHROMIUM value '${install_chromium}'. Defaulting to true."
install_chromium="true"
;;
esac
install_audio_ffmpeg="${SIMPLECHAT_INSTALL_FFMPEG:-true}"
install_audio_ffmpeg="$(printf '%s' "${install_audio_ffmpeg}" | tr '[:upper:]' '[:lower:]')"
case "${install_audio_ffmpeg}" in
true|1|yes|on) install_audio_ffmpeg="true" ;;
false|0|no|off) install_audio_ffmpeg="false" ;;
*)
echo "⚠ Invalid SIMPLECHAT_INSTALL_FFMPEG value '${install_audio_ffmpeg}'. Defaulting to true."
install_audio_ffmpeg="true"
;;
esac
echo ""
echo "Deployment timestamp: ${timestamp}"
echo "Image: ${var_containerRegistry}/${var_imageName}:${timestamp}"
echo "Chromium rendering runtime install: ${install_chromium}"
echo "Audio FFmpeg runtime install: ${install_audio_ffmpeg}"
echo ""
echo "[1/4] Stopping web service..."
if az webapp stop --name ${var_webService} --resource-group ${var_rgName}; then
echo "✓ Web service stopped successfully"
else
echo "✗ ERROR: Failed to stop web service" >&2
exit 1
fi
echo ""
echo "[2/4] Building image in ACR Tasks..."
echo "Context: $(pwd)"
echo "Dockerfile: application/single_app/Dockerfile"
if [ "${var_enablePrivateNetworking}" = "true" ]; then
echo "ℹ ACR public access remains enabled until POST-UP so Azure Container Registry Tasks can complete the build"
fi
if az acr build \
--registry ${var_acrName} \
--file application/single_app/Dockerfile \
--build-arg INSTALL_PLAYWRIGHT_CHROMIUM=${install_chromium} \
--build-arg INSTALL_AUDIO_FFMPEG=${install_audio_ffmpeg} \
--image ${var_imageName}:${timestamp} \
--image ${var_imageName}:latest \
.; then
echo "✓ ACR image build completed successfully"
else
cleanup_on_error "ACR build"
fi
echo ""
echo "[3/5] Enabling SimpleChat background tasks..."
if az webapp config appsettings set \
--name ${var_webService} \
--resource-group ${var_rgName} \
--settings SIMPLECHAT_RUN_BACKGROUND_TASKS=1 > /dev/null; then
echo "✓ SimpleChat background tasks enabled"
else
cleanup_on_error "Enable SimpleChat background tasks"
fi
echo ""
echo "[4/5] Restarting web service..."
if az webapp start --name ${var_webService} --resource-group ${var_rgName}; then
echo "✓ Web service restarted successfully"
else
echo "✗ ERROR: Failed to restart web service" >&2
exit 1
fi
echo ""
echo "[5/5] Image build and restart complete"
echo " -> Published ${var_imageName}:${timestamp}"
echo " -> Published ${var_imageName}:latest"
echo ""
echo "========================================"
echo "PRE-DEPLOY: Completed successfully"
echo "========================================"
windows:
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
function Import-AzdHookEnvironment {
param(
[string[]]$Names
)
foreach ($name in $Names) {
$currentValue = [Environment]::GetEnvironmentVariable($name, 'Process')
if (-not [string]::IsNullOrWhiteSpace($currentValue)) {
continue
}
$resolvedValue = azd env get-value $name 2>$null
if ($LASTEXITCODE -eq 0) {
$resolvedText = ($resolvedValue | Out-String).Trim()
[Environment]::SetEnvironmentVariable($name, $resolvedText, 'Process')
}
}
}
Import-AzdHookEnvironment -Names @(
'AZURE_SUBSCRIPTION_ID',
'SIMPLECHAT_INSTALL_CHROMIUM',
'SIMPLECHAT_INSTALL_FFMPEG',
'var_acrName',
'var_containerRegistry',
'var_cosmosDb_accountName',
'var_cosmosDb_uri',
'var_enablePrivateNetworking',
'var_imageName',
'var_rgName',
'var_subscriptionId',
'var_webService'
)
function Get-TargetSubscriptionId {
if (-not [string]::IsNullOrWhiteSpace($env:AZURE_SUBSCRIPTION_ID)) {
return $env:AZURE_SUBSCRIPTION_ID
}
if (-not [string]::IsNullOrWhiteSpace($env:var_subscriptionId)) {
return $env:var_subscriptionId
}
$resolvedSubscriptionId = az account show --query id -o tsv
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($resolvedSubscriptionId)) {
throw 'Failed to resolve the target subscription ID for predeploy.'
}
return $resolvedSubscriptionId
}
function Test-AzureCliAuthRequired {
param(
[string]$Output
)
return $Output -match 'InteractionRequired|Need user interaction|AADSTS50076|multi-factor authentication|claims challenge'
}
function Get-AzureCliLoginCommand {
$tenantId = az account show --query tenantId -o tsv 2>$null
if ($LASTEXITCODE -eq 0 -and -not [string]::IsNullOrWhiteSpace($tenantId)) {
return "az login --tenant `"$($tenantId.Trim())`" --scope `"https://management.core.windows.net//.default`""
}
return 'az login --scope "https://management.core.windows.net//.default"'
}
function Assert-ResourceLookupSucceeded {
param(
[string]$Operation,
[int]$ExitCode,
[string]$Output
)
if ($ExitCode -eq 0) {
return
}
if (Test-AzureCliAuthRequired -Output $Output) {
$loginCommand = Get-AzureCliLoginCommand
throw "Azure CLI requires interactive authentication while $Operation. Run $loginCommand, then rerun 'azd deploy'.`n$Output"
}
}
function Resolve-ResourceGroupName {
$subscriptionId = Get-TargetSubscriptionId
if (-not [string]::IsNullOrWhiteSpace($env:var_rgName)) {
$groupExistsOutput = az group exists --name $env:var_rgName --subscription $subscriptionId -o tsv 2>&1 | Out-String
$groupExistsExitCode = $LASTEXITCODE
Assert-ResourceLookupSucceeded -Operation "checking resource group '$($env:var_rgName)'" -ExitCode $groupExistsExitCode -Output $groupExistsOutput
if ($groupExistsExitCode -eq 0 -and $groupExistsOutput.Trim() -eq 'true') {
return $env:var_rgName
}
}
$cosmosAccountName = $env:var_cosmosDb_accountName
if ([string]::IsNullOrWhiteSpace($cosmosAccountName) -and -not [string]::IsNullOrWhiteSpace($env:var_cosmosDb_uri)) {
$cosmosAccountName = ([System.Uri]$env:var_cosmosDb_uri).Host.Split('.')[0]
}
$resolvedResourceGroup = $null
if (-not [string]::IsNullOrWhiteSpace($cosmosAccountName)) {
$cosmosLookupOutput = az cosmosdb list --subscription $subscriptionId --query "[?name=='$cosmosAccountName'].resourceGroup | [0]" -o tsv 2>&1 | Out-String
$cosmosLookupExitCode = $LASTEXITCODE
Assert-ResourceLookupSucceeded -Operation "resolving Cosmos DB account '$cosmosAccountName'" -ExitCode $cosmosLookupExitCode -Output $cosmosLookupOutput
if ($cosmosLookupExitCode -eq 0) {
$resolvedResourceGroup = $cosmosLookupOutput.Trim()
}
}
if ([string]::IsNullOrWhiteSpace($resolvedResourceGroup) -and -not [string]::IsNullOrWhiteSpace($env:var_webService)) {
$webAppLookupOutput = az resource list --subscription $subscriptionId --name "$($env:var_webService)" --resource-type Microsoft.Web/sites --query "[0].resourceGroup" -o tsv 2>&1 | Out-String
$webAppLookupExitCode = $LASTEXITCODE
Assert-ResourceLookupSucceeded -Operation "resolving Web App '$($env:var_webService)'" -ExitCode $webAppLookupExitCode -Output $webAppLookupOutput
if ($webAppLookupExitCode -eq 0) {
$resolvedResourceGroup = $webAppLookupOutput.Trim()
}
}
if ([string]::IsNullOrWhiteSpace($resolvedResourceGroup)) {
throw 'Unable to resolve resource group from var_rgName, Cosmos DB, or Web App.'
}
$env:var_rgName = $resolvedResourceGroup
return $resolvedResourceGroup
}
$subscriptionId = Get-TargetSubscriptionId
$rgName = Resolve-ResourceGroupName
function Cleanup-OnError {
param(
[string]$StepName
)
Write-Host ""
Write-Error "Deployment failed at step: $StepName"
Write-Host "Attempting to restart web service..."
az webapp start --name $env:var_webService --resource-group $rgName --subscription $subscriptionId 2>$null | Out-Null
exit 1
}
function Wait-ForAcrBuildRun {
param(
[string]$RunId
)
for ($attempt = 1; $attempt -le 120; $attempt++) {
$runStatus = az acr task show-run --registry $env:var_acrName --resource-group $rgName --subscription $subscriptionId --run-id $RunId --query status -o tsv 2>$null
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($runStatus)) {
throw "Failed to query ACR build run status for run ID $RunId."
}
switch ($runStatus) {
'Succeeded' {
Write-Host "✓ ACR build run $RunId completed successfully"
return
}
'Failed' {
throw "ACR build run $RunId failed. Run 'az acr task show-run --registry $($env:var_acrName) --resource-group $rgName --subscription $subscriptionId --run-id $RunId -o json' for details."
}
'Error' {
throw "ACR build run $RunId errored. Run 'az acr task show-run --registry $($env:var_acrName) --resource-group $rgName --subscription $subscriptionId --run-id $RunId -o json' for details."
}
'Canceled' {
throw "ACR build run $RunId was canceled."
}
'Timeout' {
throw "ACR build run $RunId timed out."
}
default {
Write-Host " ACR build run $RunId status: $runStatus ($attempt/120)..."
Start-Sleep -Seconds 10
}
}
}
throw "ACR build run $RunId did not complete within the expected time window."
}
Write-Host "========================================"
Write-Host "PRE-DEPLOY: Building and pushing image"
Write-Host "========================================"
Set-Location ..
$timestamp = Get-Date -Format 'yyyyMMdd-HHmmss'
$installChromium = if ([string]::IsNullOrWhiteSpace($env:SIMPLECHAT_INSTALL_CHROMIUM)) { 'true' } else { $env:SIMPLECHAT_INSTALL_CHROMIUM.Trim().ToLowerInvariant() }
switch ($installChromium) {
{ $_ -in @('true', '1', 'yes', 'on') } { $installChromium = 'true'; break }
{ $_ -in @('false', '0', 'no', 'off') } { $installChromium = 'false'; break }
default {
Write-Warning "Invalid SIMPLECHAT_INSTALL_CHROMIUM value '$installChromium'. Defaulting to true."
$installChromium = 'true'
}
}
$installAudioFfmpeg = if ([string]::IsNullOrWhiteSpace($env:SIMPLECHAT_INSTALL_FFMPEG)) { 'true' } else { $env:SIMPLECHAT_INSTALL_FFMPEG.Trim().ToLowerInvariant() }
switch ($installAudioFfmpeg) {
{ $_ -in @('true', '1', 'yes', 'on') } { $installAudioFfmpeg = 'true'; break }
{ $_ -in @('false', '0', 'no', 'off') } { $installAudioFfmpeg = 'false'; break }
default {
Write-Warning "Invalid SIMPLECHAT_INSTALL_FFMPEG value '$installAudioFfmpeg'. Defaulting to true."
$installAudioFfmpeg = 'true'
}
}
Write-Host ""
Write-Host "Deployment timestamp: $timestamp"
Write-Host "Image: $($env:var_containerRegistry)/$($env:var_imageName):$timestamp"
Write-Host "Chromium rendering runtime install: $installChromium"
Write-Host "Audio FFmpeg runtime install: $installAudioFfmpeg"
Write-Host ""
Write-Host "[1/4] Stopping web service..."
az webapp stop --name $env:var_webService --resource-group $rgName --subscription $subscriptionId | Out-Null
if ($LASTEXITCODE -ne 0) {
throw 'Failed to stop web service.'
}
Write-Host "✓ Web service stopped successfully"
Write-Host ""
Write-Host "[2/4] Building image in ACR Tasks..."
Write-Host "Context: $(Get-Location)"
Write-Host "Dockerfile: application/single_app/Dockerfile"
if ($env:var_enablePrivateNetworking -eq 'true') {
Write-Host "ℹ ACR public access remains enabled until POST-UP so Azure Container Registry Tasks can complete the build"
}
$runId = az acr build --registry $env:var_acrName --resource-group $rgName --subscription $subscriptionId --file application/single_app/Dockerfile --build-arg "INSTALL_PLAYWRIGHT_CHROMIUM=$installChromium" --build-arg "INSTALL_AUDIO_FFMPEG=$installAudioFfmpeg" --image "$($env:var_imageName):$timestamp" --image "$($env:var_imageName):latest" --no-logs --query runId -o tsv .
if ($LASTEXITCODE -ne 0 -or [string]::IsNullOrWhiteSpace($runId)) {
Cleanup-OnError -StepName 'ACR build'
}
Write-Host "Queued ACR build run ID: $runId"
Wait-ForAcrBuildRun -RunId $runId
Write-Host "✓ ACR image build completed successfully"
Write-Host ""
Write-Host "[3/5] Enabling SimpleChat background tasks..."
az webapp config appsettings set --name $env:var_webService --resource-group $rgName --subscription $subscriptionId --settings SIMPLECHAT_RUN_BACKGROUND_TASKS=1 | Out-Null
if ($LASTEXITCODE -ne 0) {
Cleanup-OnError -StepName 'Enable SimpleChat background tasks'
}
Write-Host "✓ SimpleChat background tasks enabled"
Write-Host ""
Write-Host "[4/5] Restarting web service..."
az webapp start --name $env:var_webService --resource-group $rgName --subscription $subscriptionId | Out-Null
if ($LASTEXITCODE -ne 0) {
throw 'Failed to restart web service.'
}
Write-Host "✓ Web service restarted successfully"
Write-Host ""
Write-Host "[5/5] Image build and restart complete"
Write-Host " -> Published $($env:var_imageName):$timestamp"
Write-Host " -> Published $($env:var_imageName):latest"
Write-Host ""
Write-Host "========================================"
Write-Host "PRE-DEPLOY: Completed successfully"
Write-Host "========================================"
postup:
# this is the final step to run after everything else is done
# primary use is disable public network access if private endpoints are used
posix:
shell: sh
run: |
set -e
echo "========================================"
echo "POST-UP: Final configuration"
echo "========================================"
if [ "${var_enablePrivateNetworking}" = "true" ]; then
echo ""
echo "Configuring private networking..."