-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathmain.tf
More file actions
3003 lines (2656 loc) · 114 KB
/
main.tf
File metadata and controls
3003 lines (2656 loc) · 114 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
# Create resource group if it does not exist
resource "azurerm_resource_group" "rg" {
name = var.resource_group_name
location = var.location
}
# Subscription context for role assignments
data "azurerm_client_config" "current" {}
# Random suffix to mimic uniqueString(resourceGroup().id)
resource "random_id" "suffix" {
byte_length = 4
}
locals {
# Use provided user_principal_id or default to current Azure CLI user
principal_id = var.user_principal_id != null ? var.user_principal_id : data.azurerm_client_config.current.object_id
suffix = substr(random_id.suffix.hex, 0, 8)
cosmos_account_name = "${var.name_prefix}${local.suffix}cosmosdb"
cosmos_db_name = "${var.name_prefix}-db" # Dynamic cosmos db name
storage_account = lower(replace("${var.name_prefix}${local.suffix}sa", "-", ""))
ai_foundry_name = "aif-${local.suffix}" # custom subdomain
ai_project_name = "proj-${local.suffix}"
search_service_name = "${var.name_prefix}-${local.suffix}-search"
app_service_plan = "${var.name_prefix}-${local.suffix}-asp"
log_analytics_name = "${var.name_prefix}-${local.suffix}-la"
app_insights_name = "${var.name_prefix}-${local.suffix}-ai"
registry_name = lower(replace("${var.name_prefix}${local.suffix}cosureg", "-", ""))
web_app_name = "${var.name_prefix}-${local.suffix}-app"
key_vault_name = "${var.name_prefix}-${local.suffix}-kv"
cosmos_connection_auth_type = var.enable_cosmos_local_auth ? "AccountKey" : "AAD"
dockerfile_hash = filesha256("../src/Dockerfile")
# Hash of application source & templates to trigger container rebuild when logic/UI changes
# Combine Python files and HTML templates for source tracking
app_source_hash = sha256(join("", [
for f in concat(
[for py in fileset("../src", "**/*.py") : py],
["app/templates/index.html"] # Explicitly include the HTML template
) : fileexists("../src/${f}") ? filesha256("../src/${f}") : ""
]))
product_catalog_hash = fileexists("../src/data/updated_product_catalog(in).csv") ? filesha256("../src/data/updated_product_catalog(in).csv") : "missing"
deploy_to_appservice = var.deployment_target == "appservice"
deploy_to_container_apps = var.deployment_target == "containerapps"
}
resource "azurerm_cosmosdb_account" "cosmos" {
name = local.cosmos_account_name
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
offer_type = "Standard"
kind = "GlobalDocumentDB"
consistency_policy {
consistency_level = "Session"
max_interval_in_seconds = 5
max_staleness_prefix = 100
}
geo_location {
location = var.location
failover_priority = 0
zone_redundant = false # Disable zone redundancy to avoid high demand issues for demo
}
free_tier_enabled = false
analytical_storage_enabled = false
local_authentication_disabled = !var.enable_cosmos_local_auth
}
resource "azurerm_cosmosdb_sql_database" "cosmosdb" {
name = local.cosmos_db_name
resource_group_name = azurerm_resource_group.rg.name
account_name = azurerm_cosmosdb_account.cosmos.name
throughput = 400
}
resource "azurerm_cosmosdb_sql_container" "products" {
name = "product_catalog"
resource_group_name = azurerm_resource_group.rg.name
account_name = azurerm_cosmosdb_account.cosmos.name
database_name = azurerm_cosmosdb_sql_database.cosmosdb.name
partition_key_paths = ["/ProductID"]
throughput = 400
}
# Storage account using AzAPI to bypass policy restrictions
resource "azapi_resource" "storage" {
type = "Microsoft.Storage/storageAccounts@2023-01-01"
name = local.storage_account
location = var.location
parent_id = azurerm_resource_group.rg.id
body = jsonencode({
sku = {
name = "Standard_LRS"
}
kind = "StorageV2"
properties = {
accessTier = "Hot"
allowSharedKeyAccess = true
minimumTlsVersion = "TLS1_2"
supportsHttpsTrafficOnly = true
}
})
identity {
type = "SystemAssigned"
}
}
# AI Foundry account (preview) using AzAPI provider.
# Using managed identity authentication (disableLocalAuth = true for better security)
resource "azapi_resource" "ai_foundry" {
type = "Microsoft.CognitiveServices/accounts@2024-10-01"
name = local.ai_foundry_name
location = var.location
parent_id = azurerm_resource_group.rg.id
schema_validation_enabled = false
identity { type = "SystemAssigned" }
body = jsonencode({
sku = { name = "S0" }
kind = "AIServices"
properties = {
allowProjectManagement = true
customSubDomainName = local.ai_foundry_name
disableLocalAuth = true
}
})
}
# Ensure allowProjectManagement is applied (some older API versions ignore it during create).
# This PATCH uses a newer api-version that supports the property and updates the existing account in place.
resource "azapi_update_resource" "ai_foundry_enable_project_mgmt" {
type = "Microsoft.CognitiveServices/accounts@2025-06-01"
resource_id = azapi_resource.ai_foundry.id
body = jsonencode({
properties = {
allowProjectManagement = true
}
})
}
resource "azapi_resource" "ai_project" {
type = "Microsoft.CognitiveServices/accounts/projects@2025-06-01"
name = local.ai_project_name
location = var.location
parent_id = azapi_resource.ai_foundry.id
schema_validation_enabled = false
identity { type = "SystemAssigned" }
body = jsonencode({ properties = {} })
depends_on = [azapi_update_resource.ai_foundry_enable_project_mgmt]
}
# Grant current principal access to AI Foundry + AI Project for Agents API
resource "azurerm_role_assignment" "ai_foundry_openai_user" {
scope = azapi_resource.ai_foundry.id
role_definition_name = "Cognitive Services OpenAI User"
principal_id = local.principal_id
depends_on = [azapi_resource.ai_foundry]
}
resource "azurerm_role_assignment" "ai_project_user" {
scope = azapi_resource.ai_project.id
role_definition_name = "Azure AI User"
principal_id = local.principal_id
depends_on = [azapi_resource.ai_project]
}
# === Real Multi-Agent Creation (ochartarotr) ===
# NOTE: Azure Agents API not yet available via ARM/Terraform (returns 500 Internal Server Error)
# Keeping these commented for future use when the API becomes available
# resource "azapi_resource" "cora_agent" {
# type = "Microsoft.CognitiveServices/accounts/projects/agents@2025-06-01"
# name = "cora-agent"
# location = var.location
# parent_id = azapi_resource.ai_project.id
# schema_validation_enabled = false
# body = jsonencode({
# properties = {
# displayName = "Cora - Zava Shopping Assistant"
# description = "Domain expert for shopping assistance"
# domain = "cora"
# modelDeploymentName = "gpt-4o-mini"
# }
# })
# depends_on = [azapi_resource.ai_project]
# }# resource "azapi_resource" "interior_design_agent" {
# type = "Microsoft.CognitiveServices/accounts/projects/agents@2025-06-01"
# name = "interior-design-agent"
# location = var.location
# parent_id = azapi_resource.ai_project.id
# schema_validation_enabled = false
# body = jsonencode({
# properties = {
# displayName = "Interior Designer"
# description = "Domain expert for interior design guidance"
# domain = "interior_design"
# modelDeploymentName = "gpt-4o-mini"
# }
# })
# depends_on = [azapi_resource.ai_project]
# }# resource "azapi_resource" "inventory_agent" {
# type = "Microsoft.CognitiveServices/accounts/projects/agents@2025-06-01"
# name = "inventory-agent"
# location = var.location
# parent_id = azapi_resource.ai_project.id
# schema_validation_enabled = false
# body = jsonencode({
# properties = {
# displayName = "Inventory Manager"
# description = "Domain expert for inventory status"
# domain = "inventory"
# modelDeploymentName = "gpt-4o-mini"
# }
# })
# depends_on = [azapi_resource.ai_project]
# }# resource "azapi_resource" "customer_loyalty_agent" {
# type = "Microsoft.CognitiveServices/accounts/projects/agents@2025-06-01"
# name = "customer-loyalty-agent"
# location = var.location
# parent_id = azapi_resource.ai_project.id
# schema_validation_enabled = false
# body = jsonencode({
# properties = {
# displayName = "Customer Loyalty Specialist"
# description = "Domain expert for loyalty and rewards"
# domain = "customer_loyalty"
# modelDeploymentName = "gpt-4o-mini"
# }
# })
# depends_on = [azapi_resource.ai_project]
# }# resource "azapi_resource" "cart_manager_agent" {
# type = "Microsoft.CognitiveServices/accounts/projects/agents@2025-06-01"
# name = "cart-manager-agent"
# location = var.location
# parent_id = azapi_resource.ai_project.id
# schema_validation_enabled = false
# body = jsonencode({
# properties = {
# displayName = "Cart Manager"
# description = "Domain expert for cart management"
# domain = "cart_management"
# modelDeploymentName = "gpt-4o-mini"
# }
# })
# depends_on = [azapi_resource.ai_project]
# }
resource "azurerm_search_service" "search" {
name = local.search_service_name
resource_group_name = azurerm_resource_group.rg.name
location = var.location
sku = "standard"
identity { type = "SystemAssigned" }
}
resource "azurerm_log_analytics_workspace" "law" {
name = local.log_analytics_name
location = var.location
resource_group_name = azurerm_resource_group.rg.name
sku = "PerGB2018"
retention_in_days = 90
depends_on = [
azurerm_resource_group.rg
]
}
resource "azurerm_application_insights" "appinsights" {
name = local.app_insights_name
location = var.location
resource_group_name = azurerm_resource_group.rg.name
application_type = "web"
workspace_id = azurerm_log_analytics_workspace.law.id
# Disable billing features to avoid 404 errors
daily_data_cap_in_gb = 1
daily_data_cap_notifications_disabled = true
sampling_percentage = 100
lifecycle {
ignore_changes = [
tags,
disable_ip_masking,
force_customer_storage_for_profiler,
internet_ingestion_enabled,
internet_query_enabled,
local_authentication_disabled
]
}
depends_on = [
azurerm_resource_group.rg,
azurerm_log_analytics_workspace.law
]
}
resource "azurerm_container_registry" "acr" {
name = local.registry_name
resource_group_name = azurerm_resource_group.rg.name
location = var.location
sku = "Standard"
admin_enabled = true
depends_on = [
azurerm_resource_group.rg
]
}
# Container Apps environment (alternative to App Service)
resource "azurerm_container_app_environment" "app_env" {
count = local.deploy_to_container_apps ? 1 : 0
name = "${var.name_prefix}-${local.suffix}-cae"
location = var.location
resource_group_name = azurerm_resource_group.rg.name
log_analytics_workspace_id = azurerm_log_analytics_workspace.law.id
}
resource "azurerm_user_assigned_identity" "containerapp_identity" {
count = local.deploy_to_container_apps ? 1 : 0
name = "${var.name_prefix}-${local.suffix}-ca-id"
resource_group_name = azurerm_resource_group.rg.name
location = azurerm_resource_group.rg.location
}
# Container Apps deployment (uses ACR image)
resource "azurerm_container_app" "app" {
count = local.deploy_to_container_apps ? 1 : 0
name = "${var.name_prefix}-${local.suffix}-ca"
resource_group_name = azurerm_resource_group.rg.name
container_app_environment_id = azurerm_container_app_environment.app_env[0].id
revision_mode = "Single"
identity {
type = "UserAssigned"
identity_ids = [azurerm_user_assigned_identity.containerapp_identity[0].id]
}
template {
container {
name = "zava-chat-app"
image = "${azurerm_container_registry.acr.login_server}/zava-chat-app:latest"
cpu = 1
memory = "2Gi"
env {
name = "WEBSITES_PORT"
value = "8000"
}
env {
name = "USE_MULTI_AGENT"
value = var.enable_multi_agent ? "true" : "false"
}
env {
name = "AZURE_AI_FOUNDRY_ENDPOINT"
value = "https://${local.ai_foundry_name}.cognitiveservices.azure.com/"
}
env {
name = "AZURE_AI_PROJECT_NAME"
value = local.ai_project_name
}
env {
name = "AZURE_AI_PROJECT_ENDPOINT"
value = "https://${local.ai_foundry_name}.services.ai.azure.com/api/projects/${local.ai_project_name}"
}
env {
name = "AZURE_AI_AGENT_ENDPOINT"
value = "https://${local.ai_foundry_name}.services.ai.azure.com/api/projects/${local.ai_project_name}"
}
env {
name = "AZURE_AI_AGENT_MODEL_DEPLOYMENT_NAME"
value = var.chat_model_deployment
}
env {
name = "AZURE_OPENAI_CHAT_DEPLOYMENT"
value = var.chat_model_deployment
}
env {
name = "AZURE_OPENAI_EMBEDDING_DEPLOYMENT"
value = "text-embedding-3-small"
}
env {
name = "AZURE_OPENAI_ENDPOINT"
value = "https://${local.ai_foundry_name}.cognitiveservices.azure.com/"
}
env {
name = "AZURE_OPENAI_API_VERSION"
value = "2024-02-01"
}
env {
name = "gpt_endpoint"
value = "https://${local.ai_foundry_name}.cognitiveservices.azure.com/"
}
env {
name = "gpt_deployment"
value = var.chat_model_deployment
}
env {
name = "gpt_api_version"
value = "2024-12-01-preview"
}
env {
name = "COSMOS_DB_ENDPOINT"
value = azurerm_cosmosdb_account.cosmos.endpoint
}
env {
name = "COSMOS_DB_NAME"
value = local.cosmos_db_name
}
env {
name = "COSMOS_DB_CONTAINER_NAME"
value = "product_catalog"
}
env {
name = "COSMOS_SKIP_IF_EXISTS"
value = "true"
}
env {
name = "SEARCH_SERVICE_ENDPOINT"
value = "https://${local.search_service_name}.search.windows.net"
}
env {
name = "SEARCH_INDEX_NAME"
value = "products-index"
}
env {
name = "STORAGE_ACCOUNT_NAME"
value = local.storage_account
}
env {
name = "AZURE_SUBSCRIPTION_ID"
value = data.azurerm_client_config.current.subscription_id
}
env {
name = "AZURE_RESOURCE_GROUP"
value = azurerm_resource_group.rg.name
}
env {
name = "AZURE_LOCATION"
value = var.location
}
env {
name = "AZURE_CLIENT_ID"
value = azurerm_user_assigned_identity.containerapp_identity[0].client_id
}
env {
name = "CUSTOMER_ID"
value = "CUST001"
}
# Secrets (Key Vault references)
env {
name = "SEARCH_SERVICE_KEY"
secret_name = "search-service-key"
}
env {
name = "STORAGE_CONNECTION_STRING"
secret_name = "storage-connection-string"
}
# Cosmos auth: use AAD when local auth disabled
dynamic "env" {
for_each = var.enable_cosmos_local_auth ? [1] : []
content {
name = "COSMOS_DB_KEY"
secret_name = "cosmos-primary-key"
}
}
dynamic "env" {
for_each = var.enable_cosmos_local_auth ? [] : [1]
content {
name = "COSMOS_DB_KEY"
value = "AAD_AUTH"
}
}
# Agent IDs (non-secret) - set explicitly to avoid secret set drift
env {
name = "AGENT_CORA_ID"
value = data.external.agents_state.result["agent_cora_id"]
}
env {
name = "AGENT_INTERIOR_DESIGNER_ID"
value = data.external.agents_state.result["agent_interior_designer_id"]
}
env {
name = "AGENT_INVENTORY_AGENT_ID"
value = data.external.agents_state.result["agent_inventory_agent_id"]
}
env {
name = "AGENT_CUSTOMER_LOYALTY_ID"
value = data.external.agents_state.result["agent_customer_loyalty_id"]
}
env {
name = "AGENT_CART_MANAGER_ID"
value = data.external.agents_state.result["agent_cart_manager_id"]
}
env {
name = "cora"
value = data.external.agents_state.result["agent_cora_id"]
}
env {
name = "interior_designer"
value = data.external.agents_state.result["agent_interior_designer_id"]
}
env {
name = "inventory_agent"
value = data.external.agents_state.result["agent_inventory_agent_id"]
}
env {
name = "customer_loyalty"
value = data.external.agents_state.result["agent_customer_loyalty_id"]
}
env {
name = "cart_manager"
value = data.external.agents_state.result["agent_cart_manager_id"]
}
}
}
ingress {
external_enabled = true
target_port = 8000
transport = "auto"
traffic_weight {
percentage = 100
latest_revision = true
}
}
registry {
server = azurerm_container_registry.acr.login_server
identity = azurerm_user_assigned_identity.containerapp_identity[0].id
}
secret {
name = "search-service-key"
key_vault_secret_id = "${azurerm_key_vault.kv.vault_uri}secrets/search-admin-key"
identity = azurerm_user_assigned_identity.containerapp_identity[0].id
}
secret {
name = "storage-connection-string"
key_vault_secret_id = "${azurerm_key_vault.kv.vault_uri}secrets/storage-connection-string"
identity = azurerm_user_assigned_identity.containerapp_identity[0].id
}
dynamic "secret" {
for_each = var.enable_cosmos_local_auth ? [1] : []
content {
name = "cosmos-primary-key"
key_vault_secret_id = "${azurerm_key_vault.kv.vault_uri}secrets/cosmos-primary-key"
identity = azurerm_user_assigned_identity.containerapp_identity[0].id
}
}
depends_on = [
azurerm_container_registry.acr,
azurerm_user_assigned_identity.containerapp_identity,
azurerm_role_assignment.kv_secrets_user_containerapp,
azurerm_role_assignment.containerapp_acr_pull,
null_resource.docker_image_build,
null_resource.set_kv_secrets,
null_resource.set_agent_kv_secrets
]
}
resource "azurerm_container_registry_webhook" "webhook" {
count = local.deploy_to_appservice ? 1 : 0
name = "${local.registry_name}webhook"
resource_group_name = azurerm_resource_group.rg.name
registry_name = azurerm_container_registry.acr.name
location = var.location
service_uri = "https://${local.web_app_name}.scm.azurewebsites.net/api/registry/webhook"
status = "enabled"
scope = "zava-chat-app:latest"
actions = ["push"]
custom_headers = {
"Content-Type" = "application/json"
}
depends_on = [
azurerm_container_registry.acr,
azurerm_linux_web_app.app
]
}
# Standalone Docker Image Build - Always runs to ensure ACR has the required image
resource "null_resource" "docker_image_build" {
# Trigger rebuild when:
# 1. Dockerfile changes
# 2. Application source code changes
# 3. Requirements.txt changes
# 4. ACR or app changes
# 5. Force rebuild on every apply (always_run ensures terraform always executes the provisioner)
triggers = {
dockerfile_hash = local.dockerfile_hash
app_source_hash = local.app_source_hash
requirements_hash = fileexists("../src/requirements.txt") ? filesha256("../src/requirements.txt") : "missing"
acr_id = azurerm_container_registry.acr.id
always_run = timestamp() # Forces provisioner to run on every apply
}
depends_on = [
azurerm_container_registry.acr
]
provisioner "local-exec" {
command = <<-EOT
Write-Host ""
Write-Host "=========================================="
Write-Host "Building & Pushing Docker Image to ACR"
Write-Host "=========================================="
Write-Host ""
$ErrorActionPreference = "Continue" # Don't stop on warnings
cd ..
$srcPath = "src"
Write-Host "Starting Docker build and push to ACR..."
Write-Host "Registry: ${local.registry_name}"
Write-Host "Image: zava-chat-app:latest"
Write-Host "Dockerfile: $srcPath/Dockerfile"
Write-Host "Source Path: $srcPath"
Write-Host ""
# Set encoding for Azure CLI
$env:PYTHONIOENCODING = "utf-8"
chcp 65001 > $null
Write-Host "Executing ACR build command..."
Write-Host ""
try {
# Build and push image
az acr build `
--resource-group ${azurerm_resource_group.rg.name} `
--registry ${local.registry_name} `
--image zava-chat-app:latest `
--file "$srcPath\Dockerfile" `
"$srcPath" `
--no-logs
if ($LASTEXITCODE -eq 0) {
Write-Host ""
Write-Host "[SUCCESS] Docker image successfully built and pushed to ACR"
Write-Host ""
Write-Host "Image details:"
Write-Host " Registry: ${local.registry_name}.azurecr.io"
Write-Host " Repository: zava-chat-app"
Write-Host " Tag: latest"
Write-Host ""
# Wait for image to be available
Write-Host "Waiting for image to be available in registry..."
Start-Sleep -Seconds 10
# Verify image exists in ACR
Write-Host "Verifying image in ACR..."
$imgCheck = az acr repository show --name ${local.registry_name} --image zava-chat-app:latest --query "name" -o tsv 2>$null
if ($LASTEXITCODE -eq 0 -and $imgCheck -eq "zava-chat-app") {
Write-Host "[VERIFIED] Image confirmed in ACR registry"
Write-Host ""
exit 0
} else {
Write-Host "[WARNING] Image verification failed but build succeeded"
Write-Host "This may be a timing issue. Image should be available shortly."
Write-Host ""
exit 0
}
} else {
Write-Host ""
Write-Host "[ERROR] ACR build failed with exit code: $LASTEXITCODE"
Write-Host ""
Write-Host "Troubleshooting steps:"
Write-Host " 1. Check requirements.txt for dependency conflicts"
Write-Host " 2. Verify Dockerfile paths are correct"
Write-Host " 3. Manual build command:"
Write-Host " az acr build --resource-group ${azurerm_resource_group.rg.name} --registry ${local.registry_name} --image zava-chat-app:latest --file $srcPath\Dockerfile $srcPath"
Write-Host ""
exit 1
}
} catch {
Write-Host ""
Write-Host "[ERROR] Exception during build: $_"
Write-Host "Manual build command:"
Write-Host "az acr build --resource-group ${azurerm_resource_group.rg.name} --registry ${local.registry_name} --image zava-chat-app:latest --file $srcPath\Dockerfile $srcPath"
Write-Host ""
exit 1
}
EOT
interpreter = ["PowerShell", "-Command"]
working_dir = path.module
}
}
resource "azurerm_service_plan" "appserviceplan" {
count = local.deploy_to_appservice ? 1 : 0
name = local.app_service_plan
resource_group_name = azurerm_resource_group.rg.name
location = var.location
os_type = "Linux"
sku_name = var.app_service_sku
}
resource "azurerm_linux_web_app" "app" {
count = local.deploy_to_appservice ? 1 : 0
name = local.web_app_name
resource_group_name = azurerm_resource_group.rg.name
location = var.location
service_plan_id = azurerm_service_plan.appserviceplan[0].id
https_only = true
identity {
type = "SystemAssigned"
}
site_config {
always_on = true
http2_enabled = true
minimum_tls_version = "1.2"
# Ensure App Service waits for container readiness
health_check_path = "/health"
health_check_eviction_time_in_min = 10
application_stack {
docker_image_name = "zava-chat-app:latest"
# Use full https URL for docker registry
docker_registry_url = "https://${local.registry_name}.azurecr.io"
}
# Use system-assigned managed identity for ACR pulls (AcrPull role assignment granted below)
container_registry_use_managed_identity = true
}
app_settings = {
WEBSITES_ENABLE_APP_SERVICE_STORAGE = "false"
DOCKER_ENABLE_CI = "true"
WEBSITES_PORT = "8000"
# GPT Configuration (using managed identity)
gpt_endpoint = "https://${local.ai_foundry_name}.cognitiveservices.azure.com/"
gpt_deployment = var.chat_model_deployment
gpt_api_version = "2024-12-01-preview"
# MSFT Foundry Configuration (using managed identity)
AZURE_AI_FOUNDRY_ENDPOINT = "https://${local.ai_foundry_name}.cognitiveservices.azure.com/"
AZURE_AI_PROJECT_NAME = local.ai_project_name
AZURE_AI_PROJECT_ENDPOINT = "@Microsoft.KeyVault(SecretUri=${azurerm_key_vault.kv.vault_uri}secrets/agent-endpoint)"
AZURE_AI_AGENT_MODEL_DEPLOYMENT_NAME = var.chat_model_deployment
# MSFT Foundry OpenAI Configuration (using managed identity)
AZURE_OPENAI_CHAT_DEPLOYMENT = var.chat_model_deployment
AZURE_OPENAI_EMBEDDING_DEPLOYMENT = "text-embedding-3-small"
AZURE_OPENAI_ENDPOINT = "https://${local.ai_foundry_name}.cognitiveservices.azure.com/"
AZURE_OPENAI_API_VERSION = "2024-02-01"
# External Service Keys via Key Vault
SEARCH_SERVICE_KEY = "@Microsoft.KeyVault(SecretUri=${azurerm_key_vault.kv.vault_uri}secrets/search-admin-key)"
COSMOS_DB_KEY = var.enable_cosmos_local_auth ? "@Microsoft.KeyVault(SecretUri=${azurerm_key_vault.kv.vault_uri}secrets/cosmos-primary-key)" : "AAD_AUTH"
STORAGE_CONNECTION_STRING = "@Microsoft.KeyVault(SecretUri=${azurerm_key_vault.kv.vault_uri}secrets/storage-connection-string)"
# Multi-Agent Configuration - Agent IDs from Key Vault
USE_MULTI_AGENT = var.enable_multi_agent ? "true" : "false"
AZURE_AI_AGENT_ENDPOINT = "@Microsoft.KeyVault(SecretUri=${azurerm_key_vault.kv.vault_uri}secrets/agent-endpoint)"
AGENT_CORA_ID = "@Microsoft.KeyVault(SecretUri=${azurerm_key_vault.kv.vault_uri}secrets/agent-cora-id)"
AGENT_INTERIOR_DESIGNER_ID = "@Microsoft.KeyVault(SecretUri=${azurerm_key_vault.kv.vault_uri}secrets/agent-interior-designer-id)"
AGENT_INVENTORY_AGENT_ID = "@Microsoft.KeyVault(SecretUri=${azurerm_key_vault.kv.vault_uri}secrets/agent-inventory-agent-id)"
AGENT_CUSTOMER_LOYALTY_ID = "@Microsoft.KeyVault(SecretUri=${azurerm_key_vault.kv.vault_uri}secrets/agent-customer-loyalty-id)"
AGENT_CART_MANAGER_ID = "@Microsoft.KeyVault(SecretUri=${azurerm_key_vault.kv.vault_uri}secrets/agent-cart-manager-id)"
cora = "@Microsoft.KeyVault(SecretUri=${azurerm_key_vault.kv.vault_uri}secrets/agent-cora-id)"
interior_designer = "@Microsoft.KeyVault(SecretUri=${azurerm_key_vault.kv.vault_uri}secrets/agent-interior-designer-id)"
inventory_agent = "@Microsoft.KeyVault(SecretUri=${azurerm_key_vault.kv.vault_uri}secrets/agent-inventory-agent-id)"
customer_loyalty = "@Microsoft.KeyVault(SecretUri=${azurerm_key_vault.kv.vault_uri}secrets/agent-customer-loyalty-id)"
cart_manager = "@Microsoft.KeyVault(SecretUri=${azurerm_key_vault.kv.vault_uri}secrets/agent-cart-manager-id)"
CUSTOMER_ID = "CUST001"
}
depends_on = [
azurerm_container_registry.acr,
null_resource.ai_model_deployments,
null_resource.docker_image_build
]
}
# Grant AcrPull role to Web App managed identity so it can pull private images without admin credentials
resource "azurerm_role_assignment" "webapp_acr_pull" {
count = local.deploy_to_appservice ? 1 : 0
scope = azurerm_container_registry.acr.id
role_definition_name = "AcrPull"
principal_id = azurerm_linux_web_app.app[0].identity[0].principal_id
depends_on = [
azurerm_linux_web_app.app,
azurerm_container_registry.acr
]
}
# Key Vault for central secret management
resource "azurerm_key_vault" "kv" {
name = local.key_vault_name
location = azurerm_resource_group.rg.location
resource_group_name = azurerm_resource_group.rg.name
tenant_id = data.azurerm_client_config.current.tenant_id
sku_name = "standard"
soft_delete_retention_days = 7
purge_protection_enabled = true
enable_rbac_authorization = true
public_network_access_enabled = true
network_acls {
default_action = "Allow"
bypass = "AzureServices"
}
tags = { purpose = "multi-agent-ai-secrets" }
}
# Ensure Key Vault public access is enabled before data-plane secret reads
resource "null_resource" "enable_kv_public_access" {
depends_on = [azurerm_key_vault.kv]
provisioner "local-exec" {
command = <<-EOT
Write-Host "Ensuring Key Vault public access is enabled..."
az keyvault update `
--name "${azurerm_key_vault.kv.name}" `
--resource-group "${azurerm_resource_group.rg.name}" `
--public-network-access Enabled `
--default-action Allow `
--bypass AzureServices | Out-Null
EOT
interpreter = ["PowerShell", "-Command"]
working_dir = path.module
}
triggers = {
always_run = timestamp()
}
}
# Data source to retrieve the web app identity after it's created/updated
data "azurerm_linux_web_app" "app_identity" {
count = local.deploy_to_appservice ? 1 : 0
name = azurerm_linux_web_app.app[0].name
resource_group_name = azurerm_resource_group.rg.name
depends_on = [azurerm_linux_web_app.app]
}
# RBAC role assignments for Key Vault access
resource "azurerm_role_assignment" "kv_secrets_officer_user" {
scope = azurerm_key_vault.kv.id
role_definition_name = "Key Vault Secrets Officer"
principal_id = local.principal_id
}
resource "azurerm_role_assignment" "kv_secrets_user_containerapp" {
count = local.deploy_to_container_apps ? 1 : 0
scope = azurerm_key_vault.kv.id
role_definition_name = "Key Vault Secrets User"
principal_id = azurerm_user_assigned_identity.containerapp_identity[0].principal_id
depends_on = [azurerm_user_assigned_identity.containerapp_identity]
}
resource "azurerm_role_assignment" "kv_secrets_user_webapp" {
count = local.deploy_to_appservice ? 1 : 0
scope = azurerm_key_vault.kv.id
role_definition_name = "Key Vault Secrets User"
principal_id = data.azurerm_linux_web_app.app_identity[0].identity[0].principal_id
depends_on = [data.azurerm_linux_web_app.app_identity]
}
# Populate Key Vault secrets via CLI to avoid data-plane read failures
# Note: AI Foundry now uses managed identity instead of keys
# Fetch storage keys unconditionally
data "azapi_resource_action" "storage_keys_unconditional" {
type = "Microsoft.Storage/storageAccounts@2023-01-01"
resource_id = azapi_resource.storage.id
action = "listKeys"
response_export_values = ["keys"]
body = jsonencode({})
depends_on = [azapi_resource.storage]
}
resource "null_resource" "set_kv_secrets" {
depends_on = [
azurerm_key_vault.kv,
azurerm_role_assignment.kv_secrets_officer_user,
null_resource.enable_kv_public_access,
data.azapi_resource_action.search_admin_keys,
data.azapi_resource_action.storage_keys_unconditional,
data.azapi_resource_action.cosmos_keys
]
provisioner "local-exec" {
command = <<-EOT
$kv = "${azurerm_key_vault.kv.name}"
Write-Host "Setting Key Vault secrets (search/storage/cosmos/agent-endpoint)..."
az keyvault secret set --vault-name $kv --name "search-admin-key" --value "${jsondecode(data.azapi_resource_action.search_admin_keys[0].output).primaryKey}" | Out-Null
az keyvault secret set --vault-name $kv --name "storage-connection-string" --value "DefaultEndpointsProtocol=https;AccountName=${local.storage_account};AccountKey=${jsondecode(data.azapi_resource_action.storage_keys_unconditional.output).keys[0].value};EndpointSuffix=core.windows.net" | Out-Null
if (${var.enable_cosmos_local_auth ? "$true" : "$false"}) {
az keyvault secret set --vault-name $kv --name "cosmos-primary-key" --value "${jsondecode(data.azapi_resource_action.cosmos_keys[0].output).primaryMasterKey}" | Out-Null
}
az keyvault secret set --vault-name $kv --name "agent-endpoint" --value "https://${local.ai_foundry_name}.services.ai.azure.com/api/projects/${local.ai_project_name}" | Out-Null
EOT
interpreter = ["PowerShell", "-Command"]
working_dir = path.module
}
triggers = {
always_run = timestamp()
}
}
# External data source for agents state
data "external" "agents_state" {
program = ["python", "read_agents_state.py"]
depends_on = [null_resource.deploy_multi_agents]
}
# Store agent IDs in Key Vault via CLI
resource "null_resource" "set_agent_kv_secrets" {
depends_on = [
azurerm_key_vault.kv,
azurerm_role_assignment.kv_secrets_officer_user,
null_resource.enable_kv_public_access,
data.external.agents_state
]
provisioner "local-exec" {
command = <<-EOT
$kv = "${azurerm_key_vault.kv.name}"
Write-Host "Setting Key Vault agent ID secrets..."
az keyvault secret set --vault-name $kv --name "agent-cora-id" --value "${data.external.agents_state.result["agent_cora_id"]}" | Out-Null
az keyvault secret set --vault-name $kv --name "agent-interior-designer-id" --value "${data.external.agents_state.result["agent_interior_designer_id"]}" | Out-Null
az keyvault secret set --vault-name $kv --name "agent-inventory-agent-id" --value "${data.external.agents_state.result["agent_inventory_agent_id"]}" | Out-Null
az keyvault secret set --vault-name $kv --name "agent-customer-loyalty-id" --value "${data.external.agents_state.result["agent_customer_loyalty_id"]}" | Out-Null
az keyvault secret set --vault-name $kv --name "agent-cart-manager-id" --value "${data.external.agents_state.result["agent_cart_manager_id"]}" | Out-Null
EOT
interpreter = ["PowerShell", "-Command"]
working_dir = path.module
}
triggers = {
always_run = timestamp()
}
}
# App Service Plan autoscale
resource "azurerm_monitor_autoscale_setting" "appservice_autoscale" {
count = local.deploy_to_appservice ? 1 : 0
name = "${var.name_prefix}-${local.suffix}-asp-autoscale"
resource_group_name = azurerm_resource_group.rg.name
location = var.location
target_resource_id = azurerm_service_plan.appserviceplan[0].id
profile {
name = "default"
capacity {
minimum = "1"
maximum = "3"
default = "1"
}
rule {
metric_trigger {
metric_name = "CpuPercentage"
metric_resource_id = azurerm_service_plan.appserviceplan[0].id
time_grain = "PT1M"
statistic = "Average"
time_window = "PT5M"
time_aggregation = "Average"
operator = "GreaterThan"
threshold = 70
}
scale_action {
direction = "Increase"
type = "ChangeCount"
value = "1"
cooldown = "PT5M"
}
}
rule {
metric_trigger {
metric_name = "CpuPercentage"
metric_resource_id = azurerm_service_plan.appserviceplan[0].id
time_grain = "PT1M"
statistic = "Average"
time_window = "PT10M"
time_aggregation = "Average"