diff --git a/.github/workflows/deploy-waf.yml b/.github/workflows/deploy-waf.yml index 8ec0a5e19..0427638d0 100644 --- a/.github/workflows/deploy-waf.yml +++ b/.github/workflows/deploy-waf.yml @@ -109,13 +109,15 @@ jobs: --resource-group ${{ env.RESOURCE_GROUP_NAME }} \ --template-file infra/main.bicep \ --parameters \ - environmentName=${{ env.SOLUTION_PREFIX }} \ - useWafAlignedArchitecture=true \ - aiDeploymentsLocation='${{ env.AZURE_LOCATION }}' \ + solutionName=${{ env.SOLUTION_PREFIX }} \ + location="${{ env.AZURE_LOCATION }}" \ + azureAiServiceLocation='${{ env.AZURE_LOCATION }}' \ gptModelCapacity=5 \ - virtualMachineConfiguration='{"adminUsername": "adminuser", "adminPassword": "P@ssw0rd1234"}' \ - logAnalyticsWorkspaceConfiguration='{"existingWorkspaceResourceId": ""}' - + enableTelemetry=true \ + enableMonitoring=true \ + enablePrivateNetworking=true \ + enableScalability=true \ + - name: Send Notification on Failure if: failure() diff --git a/.github/workflows/deploy.yml b/.github/workflows/deploy.yml index 747d8de53..82f0941b1 100644 --- a/.github/workflows/deploy.yml +++ b/.github/workflows/deploy.yml @@ -129,19 +129,14 @@ jobs: --resource-group ${{ env.RESOURCE_GROUP_NAME }} \ --template-file infra/main.bicep \ --parameters \ - environmentName=${{ env.SOLUTION_PREFIX }} \ - solutionLocation="${{ env.AZURE_LOCATION }}" \ - modelDeploymentType="GlobalStandard" \ + solutionName=${{ env.SOLUTION_PREFIX }} \ + location="${{ env.AZURE_LOCATION }}" \ + gptModelDeploymentType="GlobalStandard" \ gptModelName="gpt-4o" \ gptModelVersion="2024-08-06" \ imageTag="${IMAGE_TAG}" \ - useWafAlignedArchitecture=false \ - aiDeploymentsLocation='${{ env.AZURE_LOCATION }}' \ + azureAiServiceLocation='${{ env.AZURE_LOCATION }}' \ gptModelCapacity=150 \ - logAnalyticsWorkspaceConfiguration='{"dataRetentionInDays": 30, "existingWorkspaceResourceId": ""}' \ - applicationInsightsConfiguration='{"retentionInDays": 30}' \ - virtualNetworkConfiguration='{"enabled": false}' \ - webServerFarmConfiguration='{"skuCapacity": 1, "skuName": "B2"}' \ --output json - name: Extract Web App and API App URLs diff --git a/.gitignore b/.gitignore index 0f8c238ca..a1fefd2ca 100644 --- a/.gitignore +++ b/.gitignore @@ -458,3 +458,7 @@ __pycache__/ *.whl .azure .github/copilot-instructions.md + +# Bicep local files +*.local*.bicepparam +*.local*.parameters.json \ No newline at end of file diff --git a/docs/CustomizingAzdParameters.md b/docs/CustomizingAzdParameters.md index bc28fc345..79830249a 100644 --- a/docs/CustomizingAzdParameters.md +++ b/docs/CustomizingAzdParameters.md @@ -19,6 +19,8 @@ By default this template will use the environment name as the prefix to prevent | `AZURE_ENV_IMAGETAG` | string | `latest` | Docker image tag used for container deployments. | | `AZURE_ENV_ENABLE_TELEMETRY` | bool | `true` | Enables telemetry for monitoring and diagnostics. | | `AZURE_ENV_LOG_ANALYTICS_WORKSPACE_ID` | string | Guide to get your [Existing Workspace ID](/docs/re-use-log-analytics.md) | Set this if you want to reuse an existing Log Analytics Workspace instead of creating a new one. | +| `AZURE_ENV_VM_ADMIN_USERNAME` | string | `take(newGuid(), 20)` | The administrator username for the virtual machine. | +| `AZURE_ENV_VM_ADMIN_PASSWORD` | string | `newGuid()` | The administrator password for the virtual machine. | --- ## How to Set a Parameter diff --git a/docs/DeploymentGuide.md b/docs/DeploymentGuide.md index fb4fca41a..7cc4aced2 100644 --- a/docs/DeploymentGuide.md +++ b/docs/DeploymentGuide.md @@ -26,17 +26,41 @@ Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass This will allow the scripts to run for the current session without permanently changing your system's policy. +### **Azure Developer CLI (azd) Requirement** + +Ensure that you are using the latest version of the [Azure Developer CLI](https://learn.microsoft.com/en-us/azure/developer/azure-developer-cli/overview). +The `azd` version must be **1.18.0 or higher**. + +Upgrade commands by OS: + +* **Windows (using winget):** + + ```bash + winget install microsoft.azd + ``` + +* **Linux (using apt):** + + ```bash + curl -fsSL https://aka.ms/install-azd.sh | bash + ``` + +* **macOS (using Homebrew):** + + ```bash + brew update && brew tap azure/azd && brew install azd + ``` + ## Deployment Options & Steps ### Sandbox or WAF Aligned Deployment Options The [`infra`](../infra) folder of the Multi Agent Solution Accelerator contains the [`main.bicep`](../infra/main.bicep) Bicep script, which defines all Azure infrastructure components for this solution. -When running `azd up`, you’ll now be prompted to choose between a **WAF-aligned configuration** and a **sandbox configuration** using a simple selection: +By default, the `azd up` command uses the [`main.parameters.json`](../infra/main.parameters.json) file to deploy the solution. This file is pre-configured for a **sandbox environment** — ideal for development and proof-of-concept scenarios, with minimal security and cost controls for rapid iteration. -- A **sandbox environment** — ideal for development and proof-of-concept scenarios, with minimal security and cost controls for rapid iteration. +For **production deployments**, the repository also provides [`main.waf.parameters.json`](../infra/main.waf.parameters.json), which applies a [Well-Architected Framework (WAF) aligned](https://learn.microsoft.com/en-us/azure/well-architected/) configuration. This option enables additional Azure best practices for reliability, security, cost optimization, operational excellence, and performance efficiency, such as: -- A **production deployments environment**, which applies a [Well-Architected Framework (WAF) aligned](https://learn.microsoft.com/en-us/azure/well-architected/) configuration. This option enables additional Azure best practices for reliability, security, cost optimization, operational excellence, and performance efficiency, such as: - Enhanced network security (e.g., Network protection with private endpoints) - Stricter access controls and managed identities - Logging, monitoring, and diagnostics enabled by default @@ -44,24 +68,26 @@ When running `azd up`, you’ll now be prompted to choose between a **WAF-aligne **How to choose your deployment configuration:** -When prompted during `azd up`: +* Use the default `main.parameters.json` file for a **sandbox/dev environment** +* For a **WAF-aligned, production-ready deployment**, copy the contents of `main.waf.parameters.json` into `main.parameters.json` before running `azd up` + +--- -![useWAFAlignedArchitecture](images/macae_waf_prompt.png) +### VM Credentials Configuration -- Select **`true`** to deploy a **WAF-aligned, production-ready environment** -- Select **`false`** to deploy a **lightweight sandbox/dev environment** +By default, the solution sets the VM administrator username and password from environment variables. +If you do not configure these values, a randomly generated GUID will be used for both the username and password. + +To set your own VM credentials before deployment, use: + +```sh +azd env set AZURE_ENV_VM_ADMIN_USERNAME +azd env set AZURE_ENV_VM_ADMIN_PASSWORD +``` > [!TIP] > Always review and adjust parameter values (such as region, capacity, security settings and log analytics workspace configuration) to match your organization’s requirements before deploying. For production, ensure you have sufficient quota and follow the principle of least privilege for all identities and role assignments. -> To reuse an existing Log Analytics workspace, update the existingWorkspaceResourceId field under the logAnalyticsWorkspaceConfiguration parameter in the .bicep file with the resource ID of your existing workspace. -For example: -``` -param logAnalyticsWorkspaceConfiguration = { - dataRetentionInDays: 30 - existingWorkspaceResourceId: '/subscriptions//resourceGroups//providers/Microsoft.OperationalInsights/workspaces/' -} -``` > [!IMPORTANT] > The WAF-aligned configuration is under active development. More Azure Well-Architected recommendations will be added in future updates. diff --git a/infra/main.bicep b/infra/main.bicep index f6ea978ee..1fc9582c4 100644 --- a/infra/main.bicep +++ b/infra/main.bicep @@ -1,305 +1,307 @@ -metadata name = 'Multi-Agent Custom Automation Engine' -metadata description = 'This module contains the resources required to deploy the Multi-Agent Custom Automation Engine solution accelerator for both Sandbox environments and WAF aligned environments.' - -@description('Set to true if you want to deploy WAF-aligned infrastructure.') -param useWafAlignedArchitecture bool - -@description('Use this parameter to use an existing AI project resource ID') -param existingFoundryProjectResourceId string = '' - -@description('Required. Name of the environment to deploy the solution into.') -param environmentName string - -@description('Required. Location for all Resources except AI Foundry.') -param solutionLocation string = resourceGroup().location - -@description('Optional. Enable/Disable usage telemetry for module.') -param enableTelemetry bool = true +// // ========== main.bicep ========== // +targetScope = 'resourceGroup' -param existingLogAnalyticsWorkspaceId string = '' - -param azureopenaiVersion string = '2025-01-01-preview' +metadata name = 'Multi-Agent Custom Automation Engine' +metadata description = '''This module contains the resources required to deploy the [Multi-Agent Custom Automation Engine solution accelerator](https://github.com/microsoft/Multi-Agent-Custom-Automation-Engine-Solution-Accelerator) for both Sandbox environments and WAF aligned environments. + +> **Note:** This module is not intended for broad, generic use, as it was designed by the Commercial Solution Areas CTO team, as a Microsoft Solution Accelerator. Feature requests and bug fix requests are welcome if they support the needs of this organization but may not be incorporated if they aim to make this module more generic than what it needs to be for its primary use case. This module will likely be updated to leverage AVM resource modules in the future. This may result in breaking changes in upcoming versions when these features are implemented. +''' + +@description('Optional. A unique application/solution name for all resources in this deployment. This should be 3-16 characters long.') +@minLength(3) +@maxLength(16) +param solutionName string = 'macae' + +@maxLength(5) +@description('Optional. A unique text value for the solution. This is used to ensure resource names are unique for global resources. Defaults to a 5-character substring of the unique string generated from the subscription ID, resource group name, and solution name.') +param solutionUniqueText string = take(uniqueString(subscription().id, resourceGroup().name, solutionName), 5) + +@metadata({ azd: { type: 'location' } }) +@description('Required. Azure region for all services. Regions are restricted to guarantee compatibility with paired regions and replica locations for data redundancy and failover scenarios based on articles [Azure regions list](https://learn.microsoft.com/azure/reliability/regions-list) and [Azure Database for MySQL Flexible Server - Azure Regions](https://learn.microsoft.com/azure/mysql/flexible-server/overview#azure-regions).') +@allowed([ + 'australiaeast' + 'centralus' + 'eastasia' + 'eastus' + 'eastus2' + 'japaneast' + 'northeurope' + 'southeastasia' + 'westeurope' + 'uksouth' +]) +param location string // Restricting deployment to only supported Azure OpenAI regions validated with GPT-4o model +@allowed(['australiaeast', 'eastus2', 'francecentral', 'japaneast', 'norwayeast', 'swedencentral', 'uksouth', 'westus']) @metadata({ - azd : { + azd: { type: 'location' - usageName : [ + usageName: [ 'OpenAI.GlobalStandard.gpt-4o, 150' ] } }) -@allowed(['australiaeast', 'eastus2', 'francecentral', 'japaneast', 'norwayeast', 'swedencentral', 'uksouth', 'westus']) -@description('Azure OpenAI Location') -param aiDeploymentsLocation string +@description('Required. Location for all AI service resources. This should be one of the supported Azure AI Service locations.') +param azureAiServiceLocation string @minLength(1) -@description('Name of the GPT model to deploy:') +@description('Optional. Name of the GPT model to deploy:') param gptModelName string = 'gpt-4o' +@description('Optional. Version of the GPT model to deploy. Defaults to 2024-08-06.') param gptModelVersion string = '2024-08-06' -@minLength(1) -@description('GPT model deployment type:') -param modelDeploymentType string = 'GlobalStandard' +@description('Optional. Version of the Azure OpenAI service to deploy. Defaults to 2025-01-01-preview.') +param azureopenaiVersion string = '2025-01-01-preview' -@description('Optional. AI model deployment token capacity.') +@minLength(1) +@allowed([ + 'Standard' + 'GlobalStandard' +]) +@description('Optional. GPT model deployment type. Defaults to GlobalStandard.') +param gptModelDeploymentType string = 'GlobalStandard' + +@description('Optional. AI model deployment token capacity. Defaults to 150 for optimal performance.') param gptModelCapacity int = 150 -@description('Set the image tag for the container images used in the solution. Default is "latest".') -param imageTag string = 'latest' - -param solutionPrefix string = 'macae-${padLeft(take(toLower(uniqueString(subscription().id, environmentName, resourceGroup().location, resourceGroup().name)), 12), 12, '0')}' - @description('Optional. The tags to apply to all deployed Azure resources.') -param tags object = { - app: solutionPrefix - location: solutionLocation -} +param tags resourceInput<'Microsoft.Resources/resourceGroups@2025-04-01'>.tags = {} -@description('Optional. The configuration to apply for the Multi-Agent Custom Automation Engine Log Analytics Workspace resource.') -param logAnalyticsWorkspaceConfiguration logAnalyticsWorkspaceConfigurationType = { - enabled: true - name: 'log-${solutionPrefix}' - location: solutionLocation - sku: 'PerGB2018' - tags: tags - dataRetentionInDays: useWafAlignedArchitecture ? 365 : 30 - existingWorkspaceResourceId: existingLogAnalyticsWorkspaceId -} +@description('Optional. Enable monitoring applicable resources, aligned with the Well Architected Framework recommendations. This setting enables Application Insights and Log Analytics and configures all the resources applicable resources to send logs. Defaults to false.') +param enableMonitoring bool = false -@description('Optional. The configuration to apply for the Multi-Agent Custom Automation Engine Application Insights resource.') -param applicationInsightsConfiguration applicationInsightsConfigurationType = { - enabled: true - name: 'appi-${solutionPrefix}' - location: solutionLocation - tags: tags - retentionInDays: useWafAlignedArchitecture ? 365 : 30 -} +@description('Optional. Enable scalability for applicable resources, aligned with the Well Architected Framework recommendations. Defaults to false.') +param enableScalability bool = false -@description('Optional. The configuration to apply for the Multi-Agent Custom Automation Engine Managed Identity resource.') -param userAssignedManagedIdentityConfiguration userAssignedManagedIdentityType = { - enabled: true - name: 'id-${solutionPrefix}' - location: solutionLocation - tags: tags -} +@description('Optional. Enable redundancy for applicable resources, aligned with the Well Architected Framework recommendations. Defaults to false.') +param enableRedundancy bool = false -@description('Optional. The configuration to apply for the Multi-Agent Custom Automation Engine Network Security Group resource for the backend subnet.') -param networkSecurityGroupBackendConfiguration networkSecurityGroupConfigurationType = { - enabled: true - name: 'nsg-backend-${solutionPrefix}' - location: solutionLocation - tags: tags - securityRules: null //Default value set on module configuration -} +@description('Optional. Enable private networking for applicable resources, aligned with the Well Architected Framework recommendations. Defaults to false.') +param enablePrivateNetworking bool = false -@description('Optional. The configuration to apply for the Multi-Agent Custom Automation Engine Network Security Group resource for the containers subnet.') -param networkSecurityGroupContainersConfiguration networkSecurityGroupConfigurationType = { - enabled: true - name: 'nsg-containers-${solutionPrefix}' - location: solutionLocation - tags: tags - securityRules: null //Default value set on module configuration -} +@secure() +@description('Optional. The user name for the administrator account of the virtual machine. Allows to customize credentials if `enablePrivateNetworking` is set to true.') +param virtualMachineAdminUsername string = take(newGuid(), 20) -@description('Optional. The configuration to apply for the Multi-Agent Custom Automation Engine Network Security Group resource for the Bastion subnet.') -param networkSecurityGroupBastionConfiguration networkSecurityGroupConfigurationType = { - enabled: true - name: 'nsg-bastion-${solutionPrefix}' - location: solutionLocation - tags: tags - securityRules: null //Default value set on module configuration -} +@description('Optional. The password for the administrator account of the virtual machine. Allows to customize credentials if `enablePrivateNetworking` is set to true.') +@secure() +param virtualMachineAdminPassword string = newGuid() -@description('Optional. The configuration to apply for the Multi-Agent Custom Automation Engine Network Security Group resource for the administration subnet.') -param networkSecurityGroupAdministrationConfiguration networkSecurityGroupConfigurationType = { - enabled: true - name: 'nsg-administration-${solutionPrefix}' - location: solutionLocation - tags: tags - securityRules: null //Default value set on module configuration -} +@description('Optional. The Container Registry hostname where the docker images for the backend are located.') +param backendContainerRegistryHostname string = 'biabcontainerreg.azurecr.io' -@description('Optional. The configuration to apply for the Multi-Agent Custom Automation Engine virtual network resource.') -param virtualNetworkConfiguration virtualNetworkConfigurationType = { - enabled: useWafAlignedArchitecture ? true : false - name: 'vnet-${solutionPrefix}' - location: solutionLocation - tags: tags - addressPrefixes: null //Default value set on module configuration - subnets: null //Default value set on module configuration -} +@description('Optional. The Container Image Name to deploy on the backend.') +param backendContainerImageName string = 'macaebackend' -@description('Optional. The configuration to apply for the Multi-Agent Custom Automation Engine bastion resource.') -param bastionConfiguration bastionConfigurationType = { - enabled: true - name: 'bas-${solutionPrefix}' - location: solutionLocation - tags: tags - sku: 'Standard' - virtualNetworkResourceId: null //Default value set on module configuration - publicIpResourceName: 'pip-bas${solutionPrefix}' -} +@description('Optional. The Container Image Tag to deploy on the backend.') +param backendContainerImageTag string = 'latest_2025-07-22_895' -@description('Optional. Configuration for the Windows virtual machine.') -param virtualMachineConfiguration virtualMachineConfigurationType = { - enabled: true - name: 'vm${solutionPrefix}' - location: solutionLocation - tags: tags - adminUsername: 'adminuser' - adminPassword: useWafAlignedArchitecture? 'P@ssw0rd1234' : guid(solutionPrefix, subscription().subscriptionId) - vmSize: 'Standard_D2s_v3' - subnetResourceId: null //Default value set on module configuration -} +@description('Optional. The Container Registry hostname where the docker images for the frontend are located.') +param frontendContainerRegistryHostname string = 'biabcontainerreg.azurecr.io' -@description('Optional. The configuration to apply for the AI Foundry AI Services resource.') -param aiFoundryAiServicesConfiguration aiServicesConfigurationType = { - enabled: true - name: 'aisa-${solutionPrefix}' - location: aiDeploymentsLocation - sku: 'S0' - deployments: null //Default value set on module configuration - subnetResourceId: null //Default value set on module configuration - modelCapacity: gptModelCapacity -} +@description('Optional. The Container Image Name to deploy on the frontend.') +param frontendContainerImageName string = 'macaefrontend' -@description('Optional. The configuration to apply for the AI Foundry AI Project resource.') -param aiFoundryAiProjectConfiguration aiProjectConfigurationType = { - enabled: true - name: 'aifp-${solutionPrefix}' - location: aiDeploymentsLocation - sku: 'Basic' - tags: tags -} +@description('Optional. The Container Image Tag to deploy on the frontend.') +param frontendContainerImageTag string = 'latest_2025-07-22_895' -@description('Optional. The configuration to apply for the Cosmos DB Account resource.') -param cosmosDbAccountConfiguration cosmosDbAccountConfigurationType = { - enabled: true - name: 'cosmos-${solutionPrefix}' - location: solutionLocation - tags: tags - subnetResourceId: null //Default value set on module configuration - sqlDatabases: null //Default value set on module configuration -} +@description('Optional. Enable/Disable usage telemetry for module.') +param enableTelemetry bool = true -@description('Optional. The configuration to apply for the Container App Environment resource.') -param containerAppEnvironmentConfiguration containerAppEnvironmentConfigurationType = { - enabled: true - name: 'cae-${solutionPrefix}' - location: solutionLocation - tags: tags - subnetResourceId: null //Default value set on module configuration -} +@description('Optional. Resource ID of an existing Log Analytics Workspace.') +param existingLogAnalyticsWorkspaceId string = '' -@description('Optional. The configuration to apply for the Container App resource.') -param containerAppConfiguration containerAppConfigurationType = { - enabled: true - name: 'ca-${solutionPrefix}' - location: solutionLocation - tags: tags - environmentResourceId: null //Default value set on module configuration - concurrentRequests: '100' - containerCpu: '2.0' - containerMemory: '4.0Gi' - containerImageRegistryDomain: 'biabcontainerreg.azurecr.io' - containerImageName: 'macaebackend' - containerImageTag: imageTag - containerName: 'backend' - ingressTargetPort: 8000 - maxReplicas: 1 - minReplicas: 1 +@description('Optional. Resource ID of an existing Ai Foundry AI Services resource.') +param existingAiFoundryAiProjectResourceId string = '' + +// ============== // +// Variables // +// ============== // + +var solutionSuffix = toLower(trim(replace( + replace( + replace(replace(replace(replace('${solutionName}${solutionUniqueText}', '-', ''), '_', ''), '.', ''), '/', ''), + ' ', + '' + ), + '*', + '' +))) + +// Region pairs list based on article in [Azure Database for MySQL Flexible Server - Azure Regions](https://learn.microsoft.com/azure/mysql/flexible-server/overview#azure-regions) for supported high availability regions for CosmosDB. +var cosmosDbZoneRedundantHaRegionPairs = { + australiaeast: 'uksouth' + centralus: 'eastus2' + eastasia: 'southeastasia' + eastus: 'centralus' + eastus2: 'centralus' + japaneast: 'australiaeast' + northeurope: 'westeurope' + southeastasia: 'eastasia' + uksouth: 'westeurope' + westeurope: 'northeurope' } - -@description('Optional. The configuration to apply for the Web Server Farm resource.') -param webServerFarmConfiguration webServerFarmConfigurationType = { - enabled: true - name: 'asp-${solutionPrefix}' - location: solutionLocation - skuName: useWafAlignedArchitecture? 'P1v3' : 'B2' - skuCapacity: useWafAlignedArchitecture ? 3 : 1 - tags: tags +// Paired location calculated based on 'location' parameter. This location will be used by applicable resources if `enableScalability` is set to `true` +var cosmosDbHaLocation = cosmosDbZoneRedundantHaRegionPairs[location] + +// Replica regions list based on article in [Azure regions list](https://learn.microsoft.com/azure/reliability/regions-list) and [Enhance resilience by replicating your Log Analytics workspace across regions](https://learn.microsoft.com/azure/azure-monitor/logs/workspace-replication#supported-regions) for supported regions for Log Analytics Workspace. +var replicaRegionPairs = { + australiaeast: 'australiasoutheast' + centralus: 'westus' + eastasia: 'japaneast' + eastus: 'centralus' + eastus2: 'centralus' + japaneast: 'eastasia' + northeurope: 'westeurope' + southeastasia: 'eastasia' + uksouth: 'westeurope' + westeurope: 'northeurope' } +var replicaLocation = replicaRegionPairs[location] -@description('Optional. The configuration to apply for the Web Server Farm resource.') -param webSiteConfiguration webSiteConfigurationType = { - enabled: true - name: 'app-${solutionPrefix}' - location: solutionLocation - containerImageRegistryDomain: 'biabcontainerreg.azurecr.io' - containerImageName: 'macaefrontend' - containerImageTag: imageTag - containerName: 'backend' - tags: tags - environmentResourceId: null //Default value set on module configuration -} +// ============== // +// Resources // +// ============== // -// ========== Resource Group Tag ========== // -resource resourceGroupTags 'Microsoft.Resources/tags@2021-04-01' = { - name: 'default' +#disable-next-line no-deployments-resources +resource avmTelemetry 'Microsoft.Resources/deployments@2024-03-01' = if (enableTelemetry) { + name: '46d3xbcp.ptn.sa-multiagentcustauteng.${replace('-..--..-', '.', '-')}.${substring(uniqueString(deployment().name, location), 0, 4)}' properties: { - tags: { - ...tags - TemplateName: 'Macae' + mode: 'Incremental' + template: { + '$schema': 'https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#' + contentVersion: '1.0.0.0' + resources: [] + outputs: { + telemetry: { + type: 'String' + value: 'For more information, see https://aka.ms/avm/TelemetryInfo' + } + } } } } +// Extracts subscription, resource group, and workspace name from the resource ID when using an existing Log Analytics workspace +var useExistingLogAnalytics = !empty(existingLogAnalyticsWorkspaceId) + +var existingLawSubscription = useExistingLogAnalytics ? split(existingLogAnalyticsWorkspaceId, '/')[2] : '' +var existingLawResourceGroup = useExistingLogAnalytics ? split(existingLogAnalyticsWorkspaceId, '/')[4] : '' +var existingLawName = useExistingLogAnalytics ? split(existingLogAnalyticsWorkspaceId, '/')[8] : '' + +resource existingLogAnalyticsWorkspace 'Microsoft.OperationalInsights/workspaces@2020-08-01' existing = if (useExistingLogAnalytics) { + name: existingLawName + scope: resourceGroup(existingLawSubscription, existingLawResourceGroup) +} + // ========== Log Analytics Workspace ========== // // WAF best practices for Log Analytics: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/azure-log-analytics -// Log Analytics configuration defaults -var logAnalyticsWorkspaceEnabled = logAnalyticsWorkspaceConfiguration.?enabled ?? true -var logAnalyticsWorkspaceResourceName = logAnalyticsWorkspaceConfiguration.?name ?? 'log-${solutionPrefix}' -var existingWorkspaceResourceId = logAnalyticsWorkspaceConfiguration.?existingWorkspaceResourceId ?? '' -var useExistingWorkspace = existingWorkspaceResourceId != '' - -module logAnalyticsWorkspace 'br/public:avm/res/operational-insights/workspace:0.11.2' = if (logAnalyticsWorkspaceEnabled && !useExistingWorkspace) { +// WAF PSRules for Log Analytics: https://azure.github.io/PSRule.Rules.Azure/en/rules/resource/#azure-monitor-logs +var logAnalyticsWorkspaceResourceName = 'log-${solutionSuffix}' +module logAnalyticsWorkspace 'br/public:avm/res/operational-insights/workspace:0.12.0' = if (enableMonitoring && !useExistingLogAnalytics) { name: take('avm.res.operational-insights.workspace.${logAnalyticsWorkspaceResourceName}', 64) params: { name: logAnalyticsWorkspaceResourceName - tags: logAnalyticsWorkspaceConfiguration.?tags ?? tags - location: logAnalyticsWorkspaceConfiguration.?location ?? solutionLocation + tags: tags + location: location enableTelemetry: enableTelemetry - skuName: logAnalyticsWorkspaceConfiguration.?sku ?? 'PerGB2018' - dataRetention: logAnalyticsWorkspaceConfiguration.?dataRetentionInDays ?? 365 + skuName: 'PerGB2018' + dataRetention: 365 + features: { enableLogAccessUsingOnlyResourcePermissions: true } diagnosticSettings: [{ useThisWorkspace: true }] + // WAF aligned configuration for Redundancy + dailyQuotaGb: enableRedundancy ? 10 : null //WAF recommendation: 10 GB per day is a good starting point for most workloads + replication: enableRedundancy + ? { + enabled: true + location: replicaLocation + } + : null + // WAF aligned configuration for Private Networking + publicNetworkAccessForIngestion: enablePrivateNetworking ? 'Disabled' : 'Enabled' + publicNetworkAccessForQuery: enablePrivateNetworking ? 'Disabled' : 'Enabled' + dataSources: enablePrivateNetworking + ? [ + { + tags: tags + eventLogName: 'Application' + eventTypes: [ + { + eventType: 'Error' + } + { + eventType: 'Warning' + } + { + eventType: 'Information' + } + ] + kind: 'WindowsEvent' + name: 'applicationEvent' + } + { + counterName: '% Processor Time' + instanceName: '*' + intervalSeconds: 60 + kind: 'WindowsPerformanceCounter' + name: 'windowsPerfCounter1' + objectName: 'Processor' + } + { + kind: 'IISLogs' + name: 'sampleIISLog1' + state: 'OnPremiseEnabled' + } + ] + : null } } - -var logAnalyticsWorkspaceId = useExistingWorkspace ? existingWorkspaceResourceId : logAnalyticsWorkspace.outputs.resourceId +// Log Analytics Name, workspace ID, customer ID, and shared key (existing or new) +var logAnalyticsWorkspaceName = useExistingLogAnalytics + ? existingLogAnalyticsWorkspace!.name + : logAnalyticsWorkspace!.outputs.name +var logAnalyticsWorkspaceResourceId = useExistingLogAnalytics + ? existingLogAnalyticsWorkspaceId + : logAnalyticsWorkspace!.outputs.resourceId +var logAnalyticsPrimarySharedKey = useExistingLogAnalytics + ? existingLogAnalyticsWorkspace!.listKeys().primarySharedKey + : logAnalyticsWorkspace!.outputs!.primarySharedKey +var logAnalyticsWorkspaceId = useExistingLogAnalytics + ? existingLogAnalyticsWorkspace!.properties.customerId + : logAnalyticsWorkspace!.outputs.logAnalyticsWorkspaceId // ========== Application Insights ========== // // WAF best practices for Application Insights: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/application-insights -// Application Insights configuration defaults -var applicationInsightsEnabled = applicationInsightsConfiguration.?enabled ?? true -var applicationInsightsResourceName = applicationInsightsConfiguration.?name ?? 'appi-${solutionPrefix}' -module applicationInsights 'br/public:avm/res/insights/component:0.6.0' = if (applicationInsightsEnabled) { +// WAF PSRules for Application Insights: https://azure.github.io/PSRule.Rules.Azure/en/rules/resource/#application-insights +var applicationInsightsResourceName = 'appi-${solutionSuffix}' +module applicationInsights 'br/public:avm/res/insights/component:0.6.0' = if (enableMonitoring) { name: take('avm.res.insights.component.${applicationInsightsResourceName}', 64) params: { name: applicationInsightsResourceName - workspaceResourceId: logAnalyticsWorkspaceId - location: applicationInsightsConfiguration.?location ?? solutionLocation + tags: tags + location: location enableTelemetry: enableTelemetry - tags: applicationInsightsConfiguration.?tags ?? tags - retentionInDays: applicationInsightsConfiguration.?retentionInDays ?? 365 - diagnosticSettings: [{ workspaceResourceId: logAnalyticsWorkspaceId }] + retentionInDays: 365 kind: 'web' disableIpMasking: false flowType: 'Bluefield' + // WAF aligned configuration for Monitoring + workspaceResourceId: enableMonitoring ? logAnalyticsWorkspaceResourceId : '' + diagnosticSettings: enableMonitoring ? [{ workspaceResourceId: logAnalyticsWorkspaceResourceId }] : null } } -// ========== User assigned identity Web Site ========== // +// ========== User Assigned Identity ========== // // WAF best practices for identity and access management: https://learn.microsoft.com/en-us/azure/well-architected/security/identity-access -var userAssignedManagedIdentityEnabled = userAssignedManagedIdentityConfiguration.?enabled ?? true -var userAssignedManagedIdentityResourceName = userAssignedManagedIdentityConfiguration.?name ?? 'id-${solutionPrefix}' -module userAssignedIdentity 'br/public:avm/res/managed-identity/user-assigned-identity:0.4.1' = if (userAssignedManagedIdentityEnabled) { - name: take('avm.res.managed-identity.user-assigned-identity.${userAssignedManagedIdentityResourceName}', 64) +var userAssignedIdentityResourceName = 'id-${solutionSuffix}' +module userAssignedIdentity 'br/public:avm/res/managed-identity/user-assigned-identity:0.4.1' = { + name: take('avm.res.managed-identity.user-assigned-identity.${userAssignedIdentityResourceName}', 64) params: { - name: userAssignedManagedIdentityResourceName - tags: userAssignedManagedIdentityConfiguration.?tags ?? tags - location: userAssignedManagedIdentityConfiguration.?location ?? solutionLocation + name: userAssignedIdentityResourceName + location: location + tags: tags enableTelemetry: enableTelemetry } } @@ -307,79 +309,46 @@ module userAssignedIdentity 'br/public:avm/res/managed-identity/user-assigned-id // ========== Network Security Groups ========== // // WAF best practices for virtual networks: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/virtual-network // WAF recommendations for networking and connectivity: https://learn.microsoft.com/en-us/azure/well-architected/security/networking -var networkSecurityGroupBackendEnabled = networkSecurityGroupBackendConfiguration.?enabled ?? true -var networkSecurityGroupBackendResourceName = networkSecurityGroupBackendConfiguration.?name ?? 'nsg-backend-${solutionPrefix}' -module networkSecurityGroupBackend 'br/public:avm/res/network/network-security-group:0.5.1' = if (virtualNetworkEnabled && networkSecurityGroupBackendEnabled) { +var networkSecurityGroupBackendResourceName = 'nsg-${solutionSuffix}-backend' +module networkSecurityGroupBackend 'br/public:avm/res/network/network-security-group:0.5.1' = if (enablePrivateNetworking) { name: take('avm.res.network.network-security-group.${networkSecurityGroupBackendResourceName}', 64) params: { name: networkSecurityGroupBackendResourceName - location: networkSecurityGroupBackendConfiguration.?location ?? solutionLocation - tags: networkSecurityGroupBackendConfiguration.?tags ?? tags - enableTelemetry: enableTelemetry - diagnosticSettings: [{ workspaceResourceId: logAnalyticsWorkspaceId }] - securityRules: networkSecurityGroupBackendConfiguration.?securityRules ?? [ - // { - // name: 'DenySshRdpOutbound' //Azure Bastion - // properties: { - // priority: 200 - // access: 'Deny' - // protocol: '*' - // direction: 'Outbound' - // sourceAddressPrefix: 'VirtualNetwork' - // sourcePortRange: '*' - // destinationAddressPrefix: '*' - // destinationPortRanges: [ - // '3389' - // '22' - // ] - // } - // } - ] - } -} - -var networkSecurityGroupContainersEnabled = networkSecurityGroupContainersConfiguration.?enabled ?? true -var networkSecurityGroupContainersResourceName = networkSecurityGroupContainersConfiguration.?name ?? 'nsg-containers-${solutionPrefix}' -module networkSecurityGroupContainers 'br/public:avm/res/network/network-security-group:0.5.1' = if (virtualNetworkEnabled && networkSecurityGroupContainersEnabled) { - name: take('avm.res.network.network-security-group.${networkSecurityGroupContainersResourceName}', 64) - params: { - name: networkSecurityGroupContainersResourceName - location: networkSecurityGroupContainersConfiguration.?location ?? solutionLocation - tags: networkSecurityGroupContainersConfiguration.?tags ?? tags + location: location + tags: tags enableTelemetry: enableTelemetry - diagnosticSettings: [{ workspaceResourceId: logAnalyticsWorkspaceId }] - securityRules: networkSecurityGroupContainersConfiguration.?securityRules ?? [ - // { - // name: 'DenySshRdpOutbound' //Azure Bastion - // properties: { - // priority: 200 - // access: 'Deny' - // protocol: '*' - // direction: 'Outbound' - // sourceAddressPrefix: 'VirtualNetwork' - // sourcePortRange: '*' - // destinationAddressPrefix: '*' - // destinationPortRanges: [ - // '3389' - // '22' - // ] - // } - // } + diagnosticSettings: enableMonitoring ? [{ workspaceResourceId: logAnalyticsWorkspaceResourceId }] : null + securityRules: [ + { + name: 'deny-hop-outbound' + properties: { + access: 'Deny' + destinationAddressPrefix: '*' + destinationPortRanges: [ + '22' + '3389' + ] + direction: 'Outbound' + priority: 200 + protocol: 'Tcp' + sourceAddressPrefix: 'VirtualNetwork' + sourcePortRange: '*' + } + } ] } } -var networkSecurityGroupBastionEnabled = networkSecurityGroupBastionConfiguration.?enabled ?? true -var networkSecurityGroupBastionResourceName = networkSecurityGroupBastionConfiguration.?name ?? 'nsg-bastion-${solutionPrefix}' -module networkSecurityGroupBastion 'br/public:avm/res/network/network-security-group:0.5.1' = if (virtualNetworkEnabled && networkSecurityGroupBastionEnabled) { +var networkSecurityGroupBastionResourceName = 'nsg-${solutionSuffix}-bastion' +module networkSecurityGroupBastion 'br/public:avm/res/network/network-security-group:0.5.1' = if (enablePrivateNetworking) { name: take('avm.res.network.network-security-group.${networkSecurityGroupBastionResourceName}', 64) params: { name: networkSecurityGroupBastionResourceName - location: networkSecurityGroupBastionConfiguration.?location ?? solutionLocation - tags: networkSecurityGroupBastionConfiguration.?tags ?? tags + location: location + tags: tags enableTelemetry: enableTelemetry - diagnosticSettings: [{ workspaceResourceId: logAnalyticsWorkspaceId }] - securityRules: networkSecurityGroupBastionConfiguration.?securityRules ?? [ + diagnosticSettings: enableMonitoring ? [{ workspaceResourceId: logAnalyticsWorkspaceResourceId }] : null + securityRules: [ { name: 'AllowHttpsInBound' properties: { @@ -526,33 +495,92 @@ module networkSecurityGroupBastion 'br/public:avm/res/network/network-security-g } } -var networkSecurityGroupAdministrationEnabled = networkSecurityGroupAdministrationConfiguration.?enabled ?? true -var networkSecurityGroupAdministrationResourceName = networkSecurityGroupAdministrationConfiguration.?name ?? 'nsg-administration-${solutionPrefix}' -module networkSecurityGroupAdministration 'br/public:avm/res/network/network-security-group:0.5.1' = if (virtualNetworkEnabled && networkSecurityGroupAdministrationEnabled) { +var networkSecurityGroupAdministrationResourceName = 'nsg-${solutionSuffix}-administration' +module networkSecurityGroupAdministration 'br/public:avm/res/network/network-security-group:0.5.1' = if (enablePrivateNetworking) { name: take('avm.res.network.network-security-group.${networkSecurityGroupAdministrationResourceName}', 64) params: { name: networkSecurityGroupAdministrationResourceName - location: networkSecurityGroupAdministrationConfiguration.?location ?? solutionLocation - tags: networkSecurityGroupAdministrationConfiguration.?tags ?? tags + location: location + tags: tags + enableTelemetry: enableTelemetry + diagnosticSettings: enableMonitoring ? [{ workspaceResourceId: logAnalyticsWorkspaceResourceId }] : null + securityRules: [ + { + name: 'deny-hop-outbound' + properties: { + access: 'Deny' + destinationAddressPrefix: '*' + destinationPortRanges: [ + '22' + '3389' + ] + direction: 'Outbound' + priority: 200 + protocol: 'Tcp' + sourceAddressPrefix: 'VirtualNetwork' + sourcePortRange: '*' + } + } + ] + } +} + +var networkSecurityGroupContainersResourceName = 'nsg-${solutionSuffix}-containers' +module networkSecurityGroupContainers 'br/public:avm/res/network/network-security-group:0.5.1' = if (enablePrivateNetworking) { + name: take('avm.res.network.network-security-group.${networkSecurityGroupContainersResourceName}', 64) + params: { + name: networkSecurityGroupContainersResourceName + location: location + tags: tags + enableTelemetry: enableTelemetry + diagnosticSettings: enableMonitoring ? [{ workspaceResourceId: logAnalyticsWorkspaceResourceId }] : null + securityRules: [ + { + name: 'deny-hop-outbound' + properties: { + access: 'Deny' + destinationAddressPrefix: '*' + destinationPortRanges: [ + '22' + '3389' + ] + direction: 'Outbound' + priority: 200 + protocol: 'Tcp' + sourceAddressPrefix: 'VirtualNetwork' + sourcePortRange: '*' + } + } + ] + } +} + +var networkSecurityGroupWebsiteResourceName = 'nsg-${solutionSuffix}-website' +module networkSecurityGroupWebsite 'br/public:avm/res/network/network-security-group:0.5.1' = if (enablePrivateNetworking) { + name: take('avm.res.network.network-security-group.${networkSecurityGroupWebsiteResourceName}', 64) + params: { + name: networkSecurityGroupWebsiteResourceName + location: location + tags: tags enableTelemetry: enableTelemetry - diagnosticSettings: [{ workspaceResourceId: logAnalyticsWorkspaceId }] - securityRules: networkSecurityGroupAdministrationConfiguration.?securityRules ?? [ - // { - // name: 'DenySshRdpOutbound' //Azure Bastion - // properties: { - // priority: 200 - // access: 'Deny' - // protocol: '*' - // direction: 'Outbound' - // sourceAddressPrefix: 'VirtualNetwork' - // sourcePortRange: '*' - // destinationAddressPrefix: '*' - // destinationPortRanges: [ - // '3389' - // '22' - // ] - // } - // } + diagnosticSettings: enableMonitoring ? [{ workspaceResourceId: logAnalyticsWorkspaceResourceId }] : null + securityRules: [ + { + name: 'deny-hop-outbound' + properties: { + access: 'Deny' + destinationAddressPrefix: '*' + destinationPortRanges: [ + '22' + '3389' + ] + direction: 'Outbound' + priority: 200 + protocol: 'Tcp' + sourceAddressPrefix: 'VirtualNetwork' + sourcePortRange: '*' + } + } ] } } @@ -560,34 +588,35 @@ module networkSecurityGroupAdministration 'br/public:avm/res/network/network-sec // ========== Virtual Network ========== // // WAF best practices for virtual networks: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/virtual-network // WAF recommendations for networking and connectivity: https://learn.microsoft.com/en-us/azure/well-architected/security/networking -var virtualNetworkEnabled = virtualNetworkConfiguration.?enabled ?? true -var virtualNetworkResourceName = virtualNetworkConfiguration.?name ?? 'vnet-${solutionPrefix}' -module virtualNetwork 'br/public:avm/res/network/virtual-network:0.6.1' = if (virtualNetworkEnabled) { +var virtualNetworkResourceName = 'vnet-${solutionSuffix}' +module virtualNetwork 'br/public:avm/res/network/virtual-network:0.7.0' = if (enablePrivateNetworking) { name: take('avm.res.network.virtual-network.${virtualNetworkResourceName}', 64) params: { name: virtualNetworkResourceName - location: virtualNetworkConfiguration.?location ?? solutionLocation - tags: virtualNetworkConfiguration.?tags ?? tags + location: location + tags: tags enableTelemetry: enableTelemetry - addressPrefixes: virtualNetworkConfiguration.?addressPrefixes ?? ['10.0.0.0/8'] - subnets: virtualNetworkConfiguration.?subnets ?? [ + addressPrefixes: ['10.0.0.0/8'] + subnets: [ { name: 'backend' addressPrefix: '10.0.0.0/27' //defaultOutboundAccess: false TODO: check this configuration for a more restricted outbound access - networkSecurityGroupResourceId: networkSecurityGroupBackend.outputs.resourceId + networkSecurityGroupResourceId: networkSecurityGroupBackend!.outputs.resourceId } { name: 'administration' addressPrefix: '10.0.0.32/27' - networkSecurityGroupResourceId: networkSecurityGroupAdministration.outputs.resourceId + networkSecurityGroupResourceId: networkSecurityGroupAdministration!.outputs.resourceId + //defaultOutboundAccess: false TODO: check this configuration for a more restricted outbound access + //natGatewayResourceId: natGateway.outputs.resourceId } { // For Azure Bastion resources deployed on or after November 2, 2021, the minimum AzureBastionSubnet size is /26 or larger (/25, /24, etc.). // https://learn.microsoft.com/en-us/azure/bastion/configuration-settings#subnet name: 'AzureBastionSubnet' //This exact name is required for Azure Bastion addressPrefix: '10.0.0.64/26' - networkSecurityGroupResourceId: networkSecurityGroupBastion.outputs.resourceId + networkSecurityGroupResourceId: networkSecurityGroupBastion!.outputs.resourceId } { // If you use your own vnw, you need to provide a subnet that is dedicated exclusively to the Container App environment you deploy. This subnet isn't available to other services @@ -595,67 +624,221 @@ module virtualNetwork 'br/public:avm/res/network/virtual-network:0.6.1' = if (vi name: 'containers' addressPrefix: '10.0.2.0/23' //subnet of size /23 is required for container app delegation: 'Microsoft.App/environments' - networkSecurityGroupResourceId: networkSecurityGroupContainers.outputs.resourceId - privateEndpointNetworkPolicies: 'Disabled' + networkSecurityGroupResourceId: networkSecurityGroupContainers!.outputs.resourceId + privateEndpointNetworkPolicies: 'Enabled' + privateLinkServiceNetworkPolicies: 'Enabled' + } + { + // If you use your own vnw, you need to provide a subnet that is dedicated exclusively to the App Environment you deploy. This subnet isn't available to other services + // https://learn.microsoft.com/en-us/azure/app-service/overview-vnet-integration#subnet-requirements + name: 'webserverfarm' + addressPrefix: '10.0.4.0/27' //When you're creating subnets in Azure portal as part of integrating with the virtual network, a minimum size of /27 is required + delegation: 'Microsoft.Web/serverfarms' + networkSecurityGroupResourceId: networkSecurityGroupWebsite!.outputs.resourceId + privateEndpointNetworkPolicies: 'Enabled' privateLinkServiceNetworkPolicies: 'Enabled' } ] } } -var bastionEnabled = bastionConfiguration.?enabled ?? true -var bastionResourceName = bastionConfiguration.?name ?? 'bas-${solutionPrefix}' +var bastionResourceName = 'bas-${solutionSuffix}' // ========== Bastion host ========== // // WAF best practices for virtual networks: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/virtual-network // WAF recommendations for networking and connectivity: https://learn.microsoft.com/en-us/azure/well-architected/security/networking -module bastionHost 'br/public:avm/res/network/bastion-host:0.6.1' = if (virtualNetworkEnabled && bastionEnabled) { +module bastionHost 'br/public:avm/res/network/bastion-host:0.7.0' = if (enablePrivateNetworking) { name: take('avm.res.network.bastion-host.${bastionResourceName}', 64) params: { name: bastionResourceName - location: bastionConfiguration.?location ?? solutionLocation - skuName: bastionConfiguration.?sku ?? 'Standard' + location: location + skuName: 'Standard' enableTelemetry: enableTelemetry - tags: bastionConfiguration.?tags ?? tags - virtualNetworkResourceId: bastionConfiguration.?virtualNetworkResourceId ?? virtualNetwork.?outputs.?resourceId + tags: tags + virtualNetworkResourceId: virtualNetwork!.?outputs.?resourceId publicIPAddressObject: { - name: bastionConfiguration.?publicIpResourceName ?? 'pip-bas${solutionPrefix}' - zones: [] + name: 'pip-bas${solutionSuffix}' + diagnosticSettings: enableMonitoring ? [{ workspaceResourceId: logAnalyticsWorkspaceResourceId }] : null + tags: tags } - disableCopyPaste: false + disableCopyPaste: true enableFileCopy: false - enableIpConnect: true - enableShareableLink: true + enableIpConnect: false + enableShareableLink: false + scaleUnits: 4 + diagnosticSettings: enableMonitoring ? [{ workspaceResourceId: logAnalyticsWorkspaceResourceId }] : null } } // ========== Virtual machine ========== // // WAF best practices for virtual machines: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/virtual-machines -var virtualMachineEnabled = virtualMachineConfiguration.?enabled ?? true -var virtualMachineResourceName = virtualMachineConfiguration.?name ?? 'vm${solutionPrefix}' -module virtualMachine 'br/public:avm/res/compute/virtual-machine:0.13.0' = if (virtualNetworkEnabled && virtualMachineEnabled) { - name: take('avm.res.compute.virtual-machine.${virtualMachineResourceName}', 64) +var maintenanceConfigurationResourceName = 'mc-${solutionSuffix}' +module maintenanceConfiguration 'br/public:avm/res/maintenance/maintenance-configuration:0.3.1' = if (enablePrivateNetworking) { + name: take('avm.res.compute.virtual-machine.${maintenanceConfigurationResourceName}', 64) params: { - name: virtualMachineResourceName - computerName: take(virtualMachineResourceName, 15) - location: virtualMachineConfiguration.?location ?? solutionLocation - tags: virtualMachineConfiguration.?tags ?? tags + name: maintenanceConfigurationResourceName + location: location + tags: tags enableTelemetry: enableTelemetry - vmSize: virtualMachineConfiguration.?vmSize ?? 'Standard_D2s_v3' - adminUsername: virtualMachineConfiguration.?adminUsername ?? 'adminuser' - adminPassword: virtualMachineConfiguration.?adminPassword ?? guid(solutionPrefix, subscription().subscriptionId) - nicConfigurations: [ - { - name: 'nic-${virtualMachineResourceName}' - diagnosticSettings: [{ workspaceResourceId: logAnalyticsWorkspaceId }] - ipConfigurations: [ + extensionProperties: { + InGuestPatchMode: 'User' + } + maintenanceScope: 'InGuestPatch' + maintenanceWindow: { + startDateTime: '2024-06-16 00:00' + duration: '03:55' + timeZone: 'W. Europe Standard Time' + recurEvery: '1Day' + } + visibility: 'Custom' + installPatches: { + rebootSetting: 'IfRequired' + windowsParameters: { + classificationsToInclude: [ + 'Critical' + 'Security' + ] + } + linuxParameters: { + classificationsToInclude: [ + 'Critical' + 'Security' + ] + } + } + } +} + +var dataCollectionRulesResourceName = 'dcr-${solutionSuffix}' +var dataCollectionRulesLocation = useExistingLogAnalytics + ? existingLogAnalyticsWorkspace!.location + : logAnalyticsWorkspace!.outputs.location +module windowsVmDataCollectionRules 'br/public:avm/res/insights/data-collection-rule:0.6.1' = if (enablePrivateNetworking && enableMonitoring) { + name: take('avm.res.insights.data-collection-rule.${dataCollectionRulesResourceName}', 64) + params: { + name: dataCollectionRulesResourceName + tags: tags + enableTelemetry: enableTelemetry + location: dataCollectionRulesLocation + dataCollectionRuleProperties: { + kind: 'Windows' + dataSources: { + performanceCounters: [ { - name: '${virtualMachineResourceName}-nic01-ipconfig01' - subnetResourceId: virtualMachineConfiguration.?subnetResourceId ?? virtualNetwork.outputs.subnetResourceIds[1] - diagnosticSettings: [{ workspaceResourceId: logAnalyticsWorkspaceId }] + streams: [ + 'Microsoft-Perf' + ] + samplingFrequencyInSeconds: 60 + counterSpecifiers: [ + '\\Processor Information(_Total)\\% Processor Time' + '\\Processor Information(_Total)\\% Privileged Time' + '\\Processor Information(_Total)\\% User Time' + '\\Processor Information(_Total)\\Processor Frequency' + '\\System\\Processes' + '\\Process(_Total)\\Thread Count' + '\\Process(_Total)\\Handle Count' + '\\System\\System Up Time' + '\\System\\Context Switches/sec' + '\\System\\Processor Queue Length' + '\\Memory\\% Committed Bytes In Use' + '\\Memory\\Available Bytes' + '\\Memory\\Committed Bytes' + '\\Memory\\Cache Bytes' + '\\Memory\\Pool Paged Bytes' + '\\Memory\\Pool Nonpaged Bytes' + '\\Memory\\Pages/sec' + '\\Memory\\Page Faults/sec' + '\\Process(_Total)\\Working Set' + '\\Process(_Total)\\Working Set - Private' + '\\LogicalDisk(_Total)\\% Disk Time' + '\\LogicalDisk(_Total)\\% Disk Read Time' + '\\LogicalDisk(_Total)\\% Disk Write Time' + '\\LogicalDisk(_Total)\\% Idle Time' + '\\LogicalDisk(_Total)\\Disk Bytes/sec' + '\\LogicalDisk(_Total)\\Disk Read Bytes/sec' + '\\LogicalDisk(_Total)\\Disk Write Bytes/sec' + '\\LogicalDisk(_Total)\\Disk Transfers/sec' + '\\LogicalDisk(_Total)\\Disk Reads/sec' + '\\LogicalDisk(_Total)\\Disk Writes/sec' + '\\LogicalDisk(_Total)\\Avg. Disk sec/Transfer' + '\\LogicalDisk(_Total)\\Avg. Disk sec/Read' + '\\LogicalDisk(_Total)\\Avg. Disk sec/Write' + '\\LogicalDisk(_Total)\\Avg. Disk Queue Length' + '\\LogicalDisk(_Total)\\Avg. Disk Read Queue Length' + '\\LogicalDisk(_Total)\\Avg. Disk Write Queue Length' + '\\LogicalDisk(_Total)\\% Free Space' + '\\LogicalDisk(_Total)\\Free Megabytes' + '\\Network Interface(*)\\Bytes Total/sec' + '\\Network Interface(*)\\Bytes Sent/sec' + '\\Network Interface(*)\\Bytes Received/sec' + '\\Network Interface(*)\\Packets/sec' + '\\Network Interface(*)\\Packets Sent/sec' + '\\Network Interface(*)\\Packets Received/sec' + '\\Network Interface(*)\\Packets Outbound Errors' + '\\Network Interface(*)\\Packets Received Errors' + ] + name: 'perfCounterDataSource60' } ] } - ] + destinations: { + logAnalytics: [ + { + workspaceResourceId: logAnalyticsWorkspaceResourceId + name: 'la--1264800308' + } + ] + } + dataFlows: [ + { + streams: [ + 'Microsoft-Perf' + ] + destinations: [ + 'la--1264800308' + ] + transformKql: 'source' + outputStream: 'Microsoft-Perf' + } + ] + } + } +} + +var proximityPlacementGroupResourceName = 'ppg-${solutionSuffix}' +module proximityPlacementGroup 'br/public:avm/res/compute/proximity-placement-group:0.4.0' = if (enablePrivateNetworking) { + name: take('avm.res.compute.proximity-placement-group.${proximityPlacementGroupResourceName}', 64) + params: { + name: proximityPlacementGroupResourceName + location: location + tags: tags + enableTelemetry: enableTelemetry + availabilityZone: virtualMachineAvailabilityZone + intent: { vmSizes: [virtualMachineSize] } + } +} + +var virtualMachineResourceName = 'vm-${solutionSuffix}' +var virtualMachineAvailabilityZone = 1 +var virtualMachineSize = 'Standard_D2s_v3' +module virtualMachine 'br/public:avm/res/compute/virtual-machine:0.17.0' = if (enablePrivateNetworking) { + name: take('avm.res.compute.virtual-machine.${virtualMachineResourceName}', 64) + params: { + name: virtualMachineResourceName + location: location + tags: tags + enableTelemetry: enableTelemetry + computerName: take(virtualMachineResourceName, 15) + osType: 'Windows' + vmSize: virtualMachineSize + adminUsername: virtualMachineAdminUsername + adminPassword: virtualMachineAdminPassword + patchMode: 'AutomaticByPlatform' + bypassPlatformSafetyChecksOnUserSchedule: true + maintenanceConfigurationResourceId: maintenanceConfiguration!.outputs.resourceId + enableAutomaticUpdates: true + encryptionAtHost: false + availabilityZone: virtualMachineAvailabilityZone + proximityPlacementGroupResourceId: proximityPlacementGroup!.outputs.resourceId imageReference: { publisher: 'microsoft-dsvm' offer: 'dsvm-win-2022' @@ -664,112 +847,210 @@ module virtualMachine 'br/public:avm/res/compute/virtual-machine:0.13.0' = if (v } osDisk: { name: 'osdisk-${virtualMachineResourceName}' + caching: 'ReadWrite' createOption: 'FromImage' - managedDisk: { - storageAccountType: 'Standard_LRS' - } + deleteOption: 'Delete' diskSizeGB: 128 - caching: 'ReadWrite' + managedDisk: { storageAccountType: 'Premium_LRS' } } - osType: 'Windows' - encryptionAtHost: false //The property 'securityProfile.encryptionAtHost' is not valid because the 'Microsoft.Compute/EncryptionAtHost' feature is not enabled for this subscription. - zone: 0 + nicConfigurations: [ + { + name: 'nic-${virtualMachineResourceName}' + //networkSecurityGroupResourceId: virtualMachineConfiguration.?nicConfigurationConfiguration.networkSecurityGroupResourceId + //nicSuffix: 'nic-${virtualMachineResourceName}' + tags: tags + deleteOption: 'Delete' + diagnosticSettings: enableMonitoring //WAF aligned configuration for Monitoring + ? [{ workspaceResourceId: logAnalyticsWorkspaceResourceId }] + : null + ipConfigurations: [ + { + name: '${virtualMachineResourceName}-nic01-ipconfig01' + subnetResourceId: virtualNetwork!.outputs.subnetResourceIds[1] + diagnosticSettings: enableMonitoring //WAF aligned configuration for Monitoring + ? [{ workspaceResourceId: logAnalyticsWorkspaceResourceId }] + : null + } + ] + } + ] extensionAadJoinConfig: { enabled: true + tags: tags typeHandlerVersion: '1.0' } + extensionAntiMalwareConfig: { + enabled: true + settings: { + AntimalwareEnabled: 'true' + Exclusions: {} + RealtimeProtectionEnabled: 'true' + ScheduledScanSettings: { + day: '7' + isEnabled: 'true' + scanType: 'Quick' + time: '120' + } + } + tags: tags + } + //WAF aligned configuration for Monitoring + extensionMonitoringAgentConfig: enableMonitoring + ? { + dataCollectionRuleAssociations: [ + { + dataCollectionRuleResourceId: windowsVmDataCollectionRules!.outputs.resourceId + name: 'send-${logAnalyticsWorkspaceName}' + } + ] + enabled: true + tags: tags + } + : null + extensionNetworkWatcherAgentConfig: { + enabled: true + tags: tags + } } } -// ========== AI Foundry: AI Services ========== // -// WAF best practices for Open AI: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/azure-openai -var openAiSubResource = 'account' -var openAiPrivateDnsZones = { - 'privatelink.cognitiveservices.azure.com': openAiSubResource - 'privatelink.openai.azure.com': openAiSubResource - 'privatelink.services.ai.azure.com': openAiSubResource +// ========== Private DNS Zones ========== // +var privateDnsZones = [ + 'privatelink.cognitiveservices.azure.com' + 'privatelink.openai.azure.com' + 'privatelink.services.ai.azure.com' + 'privatelink.documents.azure.com' +] + +// DNS Zone Index Constants +var dnsZoneIndex = { + cognitiveServices: 0 + openAI: 1 + aiServices: 2 + cosmosDb: 3 } -module privateDnsZonesAiServices 'br/public:avm/res/network/private-dns-zone:0.7.1' = [ - for zone in objectKeys(openAiPrivateDnsZones): if (virtualNetworkEnabled && aiFoundryAIservicesEnabled) { - name: take( - 'avm.res.network.private-dns-zone.ai-services.${uniqueString(aiFoundryAiServicesResourceName,zone)}.${solutionPrefix}', - 64 - ) +// List of DNS zone indices that correspond to AI-related services. +var aiRelatedDnsZoneIndices = [ + dnsZoneIndex.cognitiveServices + dnsZoneIndex.openAI + dnsZoneIndex.aiServices +] + +// =================================================== +// DEPLOY PRIVATE DNS ZONES +// - Deploys all zones if no existing Foundry project is used +// - Excludes AI-related zones when using with an existing Foundry project +// =================================================== +@batchSize(5) +module avmPrivateDnsZones 'br/public:avm/res/network/private-dns-zone:0.7.1' = [ + for (zone, i) in privateDnsZones: if (enablePrivateNetworking && (!useExistingAiFoundryAiProject || !contains( + aiRelatedDnsZoneIndices, + i + ))) { + name: 'avm.res.network.private-dns-zone.${contains(zone, 'azurecontainerapps.io') ? 'containerappenv' : split(zone, '.')[1]}' params: { name: zone tags: tags enableTelemetry: enableTelemetry virtualNetworkLinks: [ { - name: 'vnetlink-${split(zone, '.')[1]}' - virtualNetworkResourceId: virtualNetwork.outputs.resourceId + name: take('vnetlink-${virtualNetworkResourceName}-${split(zone, '.')[1]}', 80) + virtualNetworkResourceId: virtualNetwork!.outputs.resourceId } ] } } ] -// NOTE: Required version 'Microsoft.CognitiveServices/accounts@2024-04-01-preview' not available in AVM -var useExistingFoundryProject = !empty(existingFoundryProjectResourceId) -var existingAiFoundryName = useExistingFoundryProject?split( existingFoundryProjectResourceId,'/')[8]:'' -var aiFoundryAiServicesResourceName = useExistingFoundryProject? existingAiFoundryName : aiFoundryAiServicesConfiguration.?name ?? 'aisa-${solutionPrefix}' -var aiFoundryAIservicesEnabled = aiFoundryAiServicesConfiguration.?enabled ?? true +// ========== AI Foundry: AI Services ========== // +// WAF best practices for Open AI: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/azure-openai + +var useExistingAiFoundryAiProject = !empty(existingAiFoundryAiProjectResourceId) +var aiFoundryAiServicesResourceGroupName = useExistingAiFoundryAiProject + ? split(existingAiFoundryAiProjectResourceId, '/')[4] + : 'rg-${solutionSuffix}' +var aiFoundryAiServicesSubscriptionId = useExistingAiFoundryAiProject + ? split(existingAiFoundryAiProjectResourceId, '/')[2] + : subscription().id +var aiFoundryAiServicesResourceName = useExistingAiFoundryAiProject + ? split(existingAiFoundryAiProjectResourceId, '/')[8] + : 'aif-${solutionSuffix}' +var aiFoundryAiProjectResourceName = useExistingAiFoundryAiProject + ? split(existingAiFoundryAiProjectResourceId, '/')[10] + : 'proj-${solutionSuffix}' // AI Project resource id: /subscriptions//resourceGroups//providers/Microsoft.CognitiveServices/accounts//projects/ var aiFoundryAiServicesModelDeployment = { format: 'OpenAI' name: gptModelName version: gptModelVersion sku: { - name: modelDeploymentType - //Curently the capacity is set to 140 for opinanal performance. - capacity: aiFoundryAiServicesConfiguration.?modelCapacity ?? gptModelCapacity + name: gptModelDeploymentType + capacity: gptModelCapacity } raiPolicyName: 'Microsoft.Default' } +var aiFoundryAiProjectDescription = 'AI Foundry Project' + +resource existingAiFoundryAiServices 'Microsoft.CognitiveServices/accounts@2025-06-01' existing = if (useExistingAiFoundryAiProject) { + name: aiFoundryAiServicesResourceName + scope: resourceGroup(aiFoundryAiServicesSubscriptionId, aiFoundryAiServicesResourceGroupName) +} -module aiFoundryAiServices 'modules/account/main.bicep' = if (aiFoundryAIservicesEnabled) { +module existingAiFoundryAiServicesDeployments 'modules/ai-services-deployments.bicep' = if (useExistingAiFoundryAiProject) { + name: take('module.ai-services-model-deployments.${existingAiFoundryAiServices.name}', 64) + scope: resourceGroup(aiFoundryAiServicesSubscriptionId, aiFoundryAiServicesResourceGroupName) + params: { + name: existingAiFoundryAiServices.name + deployments: [ + { + name: aiFoundryAiServicesModelDeployment.name + model: { + format: aiFoundryAiServicesModelDeployment.format + name: aiFoundryAiServicesModelDeployment.name + version: aiFoundryAiServicesModelDeployment.version + } + raiPolicyName: aiFoundryAiServicesModelDeployment.raiPolicyName + sku: { + name: aiFoundryAiServicesModelDeployment.sku.name + capacity: aiFoundryAiServicesModelDeployment.sku.capacity + } + } + ] + roleAssignments: [ + { + roleDefinitionIdOrName: '53ca6127-db72-4b80-b1b0-d745d6d5456d' // Azure AI User + principalId: userAssignedIdentity.outputs.principalId + principalType: 'ServicePrincipal' + } + { + roleDefinitionIdOrName: '64702f94-c441-49e6-a78b-ef80e0188fee' // Azure AI Developer + principalId: userAssignedIdentity.outputs.principalId + principalType: 'ServicePrincipal' + } + { + roleDefinitionIdOrName: '5e0bd9bd-7b93-4f28-af87-19fc36ad61bd' // Cognitive Services OpenAI User + principalId: userAssignedIdentity.outputs.principalId + principalType: 'ServicePrincipal' + } + ] + } +} + +module aiFoundryAiServices 'br:mcr.microsoft.com/bicep/avm/res/cognitive-services/account:0.13.2' = if (!useExistingAiFoundryAiProject) { name: take('avm.res.cognitive-services.account.${aiFoundryAiServicesResourceName}', 64) params: { name: aiFoundryAiServicesResourceName - tags: aiFoundryAiServicesConfiguration.?tags ?? tags - location: aiFoundryAiServicesConfiguration.?location ?? aiDeploymentsLocation - enableTelemetry: enableTelemetry - projectName: 'aifp-${solutionPrefix}' - projectDescription: 'aifp-${solutionPrefix}' - existingFoundryProjectResourceId: existingFoundryProjectResourceId - diagnosticSettings: [{ workspaceResourceId: logAnalyticsWorkspaceId }] - sku: aiFoundryAiServicesConfiguration.?sku ?? 'S0' + location: azureAiServiceLocation + tags: tags + sku: 'S0' kind: 'AIServices' - disableLocalAuth: true //Should be set to true for WAF aligned configuration + disableLocalAuth: true + allowProjectManagement: true customSubDomainName: aiFoundryAiServicesResourceName apiProperties: { //staticsEnabled: false } - allowProjectManagement: true - managedIdentities: { - systemAssigned: true - } - publicNetworkAccess: virtualNetworkEnabled ? 'Disabled' : 'Enabled' - networkAcls: { - bypass: 'AzureServices' - defaultAction: (virtualNetworkEnabled) ? 'Deny' : 'Allow' - } - privateEndpoints: virtualNetworkEnabled && !useExistingFoundryProject - ? ([ - { - name: 'pep-${aiFoundryAiServicesResourceName}' - customNetworkInterfaceName: 'nic-${aiFoundryAiServicesResourceName}' - subnetResourceId: aiFoundryAiServicesConfiguration.?subnetResourceId ?? virtualNetwork.outputs.subnetResourceIds[0] - privateDnsZoneGroup: { - privateDnsZoneGroupConfigs: map(objectKeys(openAiPrivateDnsZones), zone => { - name: replace(zone, '.', '-') - privateDnsZoneResourceId: resourceId('Microsoft.Network/privateDnsZones', zone) - }) - } - } - ]) - : [] - deployments: aiFoundryAiServicesConfiguration.?deployments ?? [ + deployments: [ { name: aiFoundryAiServicesModelDeployment.name model: { @@ -784,84 +1065,101 @@ module aiFoundryAiServices 'modules/account/main.bicep' = if (aiFoundryAIservice } } ] + networkAcls: { + defaultAction: 'Allow' + virtualNetworkRules: [] + ipRules: [] + } + managedIdentities: { userAssignedResourceIds: [userAssignedIdentity!.outputs.resourceId] } //To create accounts or projects, you must enable a managed identity on your resource + roleAssignments: [ + { + roleDefinitionIdOrName: '53ca6127-db72-4b80-b1b0-d745d6d5456d' // Azure AI User + principalId: userAssignedIdentity.outputs.principalId + principalType: 'ServicePrincipal' + } + { + roleDefinitionIdOrName: '64702f94-c441-49e6-a78b-ef80e0188fee' // Azure AI Developer + principalId: userAssignedIdentity.outputs.principalId + principalType: 'ServicePrincipal' + } + { + roleDefinitionIdOrName: '5e0bd9bd-7b93-4f28-af87-19fc36ad61bd' // Cognitive Services OpenAI User + principalId: userAssignedIdentity.outputs.principalId + principalType: 'ServicePrincipal' + } + ] + // WAF aligned configuration for Monitoring + diagnosticSettings: enableMonitoring ? [{ workspaceResourceId: logAnalyticsWorkspaceResourceId }] : null + publicNetworkAccess: enablePrivateNetworking ? 'Disabled' : 'Enabled' + privateEndpoints: (enablePrivateNetworking) + ? ([ + { + name: 'pep-${aiFoundryAiServicesResourceName}' + customNetworkInterfaceName: 'nic-${aiFoundryAiServicesResourceName}' + subnetResourceId: virtualNetwork!.outputs.subnetResourceIds[0] + privateDnsZoneGroup: { + privateDnsZoneGroupConfigs: [ + { + name: 'ai-services-dns-zone-cognitiveservices' + privateDnsZoneResourceId: avmPrivateDnsZones[dnsZoneIndex.cognitiveServices]!.outputs.resourceId + } + { + name: 'ai-services-dns-zone-openai' + privateDnsZoneResourceId: avmPrivateDnsZones[dnsZoneIndex.openAI]!.outputs.resourceId + } + { + name: 'ai-services-dns-zone-aiservices' + privateDnsZoneResourceId: avmPrivateDnsZones[dnsZoneIndex.aiServices]!.outputs.resourceId + } + ] + } + } + ]) + : [] } } -// AI Foundry: AI Project -// WAF best practices for Open AI: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/azure-openai -var existingAiFounryProjectName = useExistingFoundryProject ? last(split( existingFoundryProjectResourceId,'/')) : '' -var aiFoundryAiProjectName = useExistingFoundryProject ? existingAiFounryProjectName : aiFoundryAiProjectConfiguration.?name ?? 'aifp-${solutionPrefix}' - -var useExistingResourceId = !empty(existingFoundryProjectResourceId) - -module cogServiceRoleAssignmentsNew './modules/role.bicep' = if(!useExistingResourceId) { - params: { - name: 'new-${guid(containerApp.name, aiFoundryAiServices.outputs.resourceId)}' - principalId: containerApp.outputs.?systemAssignedMIPrincipalId! - aiServiceName: aiFoundryAiServices.outputs.name - } - scope: resourceGroup(subscription().subscriptionId, resourceGroup().name) +resource existingAiFoundryAiServicesProject 'Microsoft.CognitiveServices/accounts/projects@2025-06-01' existing = if (useExistingAiFoundryAiProject) { + name: aiFoundryAiProjectResourceName + parent: existingAiFoundryAiServices } -module cogServiceRoleAssignmentsExisting './modules/role.bicep' = if(useExistingResourceId) { +module aiFoundryAiServicesProject 'modules/ai-project.bicep' = if (!useExistingAiFoundryAiProject) { + name: take('module.ai-project.${aiFoundryAiProjectResourceName}', 64) params: { - name: 'reuse-${guid(containerApp.name, aiFoundryAiServices.outputs.aiProjectInfo.resourceId)}' - principalId: containerApp.outputs.?systemAssignedMIPrincipalId! - aiServiceName: aiFoundryAiServices.outputs.name + name: aiFoundryAiProjectResourceName + location: azureAiServiceLocation + tags: tags + desc: aiFoundryAiProjectDescription + //Implicit dependencies below + aiServicesName: aiFoundryAiServices!.outputs.name } - scope: resourceGroup( split(existingFoundryProjectResourceId, '/')[2], split(existingFoundryProjectResourceId, '/')[4]) } +var aiFoundryAiProjectName = useExistingAiFoundryAiProject + ? existingAiFoundryAiServicesProject.name + : aiFoundryAiServicesProject!.outputs.name +var aiFoundryAiProjectEndpoint = useExistingAiFoundryAiProject + ? existingAiFoundryAiServicesProject!.properties.endpoints['AI Foundry API'] + : aiFoundryAiServicesProject!.outputs.apiEndpoint + // ========== Cosmos DB ========== // // WAF best practices for Cosmos DB: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/cosmos-db -module privateDnsZonesCosmosDb 'br/public:avm/res/network/private-dns-zone:0.7.0' = if (virtualNetworkEnabled) { - name: take('avm.res.network.private-dns-zone.cosmos-db.${solutionPrefix}', 64) - params: { - name: 'privatelink.documents.azure.com' - enableTelemetry: enableTelemetry - virtualNetworkLinks: [ - { - name: 'vnetlink-cosmosdb' - virtualNetworkResourceId: virtualNetwork.outputs.resourceId - } - ] - tags: tags - } -} -var cosmosDbAccountEnabled = cosmosDbAccountConfiguration.?enabled ?? true -var cosmosDbResourceName = cosmosDbAccountConfiguration.?name ?? 'cosmos-${solutionPrefix}' +var cosmosDbResourceName = 'cosmos-${solutionSuffix}' var cosmosDbDatabaseName = 'macae' var cosmosDbDatabaseMemoryContainerName = 'memory' -module cosmosDb 'br/public:avm/res/document-db/database-account:0.12.0' = if (cosmosDbAccountEnabled) { + +//TODO: update to latest version of AVM module +module cosmosDb 'br/public:avm/res/document-db/database-account:0.15.0' = { name: take('avm.res.document-db.database-account.${cosmosDbResourceName}', 64) params: { // Required parameters - name: cosmosDbAccountConfiguration.?name ?? 'cosmos-${solutionPrefix}' - location: cosmosDbAccountConfiguration.?location ?? solutionLocation - tags: cosmosDbAccountConfiguration.?tags ?? tags + name: cosmosDbResourceName + location: location + tags: tags enableTelemetry: enableTelemetry - diagnosticSettings: [{ workspaceResourceId: logAnalyticsWorkspaceId }] - databaseAccountOfferType: 'Standard' - enableFreeTier: false - networkRestrictions: { - networkAclBypass: 'None' - publicNetworkAccess: virtualNetworkEnabled ? 'Disabled' : 'Enabled' - } - privateEndpoints: virtualNetworkEnabled - ? [ - { - name: 'pep-${cosmosDbResourceName}' - customNetworkInterfaceName: 'nic-${cosmosDbResourceName}' - privateDnsZoneGroup: { - privateDnsZoneGroupConfigs: [{ privateDnsZoneResourceId: privateDnsZonesCosmosDb.outputs.resourceId }] - } - service: 'Sql' - subnetResourceId: cosmosDbAccountConfiguration.?subnetResourceId ?? virtualNetwork.outputs.subnetResourceIds[0] - } - ] - : [] - sqlDatabases: concat(cosmosDbAccountConfiguration.?sqlDatabases ?? [], [ + sqlDatabases: [ { name: cosmosDbDatabaseName containers: [ @@ -875,92 +1173,146 @@ module cosmosDb 'br/public:avm/res/document-db/database-account:0.12.0' = if (co } ] } - ]) - locations: [ - { - locationName: cosmosDbAccountConfiguration.?location ?? solutionLocation - failoverPriority: 0 - isZoneRedundant: false - } ] - capabilitiesToAdd: [ - 'EnableServerless' - ] - sqlRoleAssignmentsPrincipalIds: [ - containerApp.outputs.?systemAssignedMIPrincipalId - ] - sqlRoleDefinitions: [ + dataPlaneRoleDefinitions: [ { - // Replace this with built-in role definition Cosmos DB Built-in Data Contributor: https://docs.azure.cn/en-us/cosmos-db/nosql/security/reference-data-plane-roles#cosmos-db-built-in-data-contributor - roleType: 'CustomRole' + // Cosmos DB Built-in Data Contributor: https://docs.azure.cn/en-us/cosmos-db/nosql/security/reference-data-plane-roles#cosmos-db-built-in-data-contributor roleName: 'Cosmos DB SQL Data Contributor' - name: 'cosmos-db-sql-data-contributor' - dataAction: [ + dataActions: [ 'Microsoft.DocumentDB/databaseAccounts/readMetadata' 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/*' 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/*' ] + assignments: [{ principalId: userAssignedIdentity.outputs.principalId }] } ] + // WAF aligned configuration for Monitoring + diagnosticSettings: enableMonitoring ? [{ workspaceResourceId: logAnalyticsWorkspaceResourceId }] : null + // WAF aligned configuration for Private Networking + networkRestrictions: { + networkAclBypass: 'None' + publicNetworkAccess: enablePrivateNetworking ? 'Disabled' : 'Enabled' + } + privateEndpoints: enablePrivateNetworking + ? [ + { + name: 'pep-${cosmosDbResourceName}' + customNetworkInterfaceName: 'nic-${cosmosDbResourceName}' + privateDnsZoneGroup: { + privateDnsZoneGroupConfigs: [ + { privateDnsZoneResourceId: avmPrivateDnsZones[dnsZoneIndex.cosmosDb]!.outputs.resourceId } + ] + } + service: 'Sql' + subnetResourceId: virtualNetwork!.outputs.subnetResourceIds[0] + } + ] + : [] + // WAF aligned configuration for Redundancy + zoneRedundant: enableRedundancy ? true : false + capabilitiesToAdd: enableRedundancy ? null : ['EnableServerless'] + automaticFailover: enableRedundancy ? true : false + failoverLocations: enableRedundancy + ? [ + { + failoverPriority: 0 + isZoneRedundant: true + locationName: location + } + { + failoverPriority: 1 + isZoneRedundant: true + locationName: cosmosDbHaLocation + } + ] + : [ + { + locationName: location + failoverPriority: 0 + } + ] } } // ========== Backend Container App Environment ========== // // WAF best practices for container apps: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/azure-container-apps -var containerAppEnvironmentEnabled = containerAppEnvironmentConfiguration.?enabled ?? true -var containerAppEnvironmentResourceName = containerAppEnvironmentConfiguration.?name ?? 'cae-${solutionPrefix}' -module containerAppEnvironment 'modules/container-app-environment.bicep' = if (containerAppEnvironmentEnabled) { - name: take('module.container-app-environment.${containerAppEnvironmentResourceName}', 64) +// PSRule for Container App: https://azure.github.io/PSRule.Rules.Azure/en/rules/resource/#container-app +var containerAppEnvironmentResourceName = 'cae-${solutionSuffix}' +module containerAppEnvironment 'br/public:avm/res/app/managed-environment:0.11.2' = { + name: take('avm.res.app.managed-environment.${containerAppEnvironmentResourceName}', 64) params: { name: containerAppEnvironmentResourceName - tags: containerAppEnvironmentConfiguration.?tags ?? tags - location: containerAppEnvironmentConfiguration.?location ?? solutionLocation - logAnalyticsResourceId: logAnalyticsWorkspaceId - publicNetworkAccess: 'Enabled' - zoneRedundant: false - applicationInsightsConnectionString: applicationInsights.outputs.connectionString + location: location + tags: tags enableTelemetry: enableTelemetry - subnetResourceId: virtualNetworkEnabled - ? containerAppEnvironmentConfiguration.?subnetResourceId ?? virtualNetwork.?outputs.?subnetResourceIds[3] ?? '' - : '' + // WAF aligned configuration for Private Networking + publicNetworkAccess: 'Enabled' // Always enabling the publicNetworkAccess for Container App Environment + internal: false // Must be false when publicNetworkAccess is'Enabled' + infrastructureSubnetResourceId: enablePrivateNetworking ? virtualNetwork.?outputs.?subnetResourceIds[3] : null + // WAF aligned configuration for Monitoring + appLogsConfiguration: enableMonitoring + ? { + destination: 'log-analytics' + logAnalyticsConfiguration: { + customerId: logAnalyticsWorkspaceId + sharedKey: logAnalyticsPrimarySharedKey + } + } + : null + appInsightsConnectionString: enableMonitoring ? applicationInsights!.outputs.connectionString : null + // WAF aligned configuration for Redundancy + zoneRedundant: enableRedundancy ? true : false + infrastructureResourceGroupName: enableRedundancy ? '${resourceGroup().name}-infra' : null + workloadProfiles: enableRedundancy + ? [ + { + maximumCount: 3 + minimumCount: 3 + name: 'CAW01' + workloadProfileType: 'D4' + } + ] + : [ + { + name: 'Consumption' + workloadProfileType: 'Consumption' + } + ] } } // ========== Backend Container App Service ========== // // WAF best practices for container apps: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/azure-container-apps -var containerAppEnabled = containerAppConfiguration.?enabled ?? true -var containerAppResourceName = containerAppConfiguration.?name ?? 'ca-${solutionPrefix}' -module containerApp 'br/public:avm/res/app/container-app:0.14.2' = if (containerAppEnabled) { +// PSRule for Container App: https://azure.github.io/PSRule.Rules.Azure/en/rules/resource/#container-app +var containerAppResourceName = 'ca-${solutionSuffix}' +module containerApp 'br/public:avm/res/app/container-app:0.18.1' = { name: take('avm.res.app.container-app.${containerAppResourceName}', 64) params: { name: containerAppResourceName - tags: containerAppConfiguration.?tags ?? tags - location: containerAppConfiguration.?location ?? solutionLocation + tags: tags + location: location enableTelemetry: enableTelemetry - environmentResourceId: containerAppConfiguration.?environmentResourceId ?? containerAppEnvironment.outputs.resourceId - managedIdentities: { - systemAssigned: true //Replace with user assigned identity - userAssignedResourceIds: [userAssignedIdentity.outputs.resourceId] - } - ingressTargetPort: containerAppConfiguration.?ingressTargetPort ?? 8000 + environmentResourceId: containerAppEnvironment.outputs.resourceId + managedIdentities: { userAssignedResourceIds: [userAssignedIdentity.outputs.resourceId] } + ingressTargetPort: 8000 ingressExternal: true activeRevisionsMode: 'Single' corsPolicy: { allowedOrigins: [ - 'https://${webSiteName}.azurewebsites.net' - 'http://${webSiteName}.azurewebsites.net' + 'https://${webSiteResourceName}.azurewebsites.net' + 'http://${webSiteResourceName}.azurewebsites.net' ] } + // WAF aligned configuration for Scalability scaleSettings: { - //TODO: Make maxReplicas and minReplicas parameterized - maxReplicas: containerAppConfiguration.?maxReplicas ?? 1 - minReplicas: containerAppConfiguration.?minReplicas ?? 1 + maxReplicas: enableScalability ? 3 : 1 + minReplicas: enableScalability ? 2 : 1 rules: [ { name: 'http-scaler' http: { metadata: { - concurrentRequests: containerAppConfiguration.?concurrentRequests ?? '100' + concurrentRequests: '100' } } } @@ -968,12 +1320,29 @@ module containerApp 'br/public:avm/res/app/container-app:0.14.2' = if (container } containers: [ { - name: containerAppConfiguration.?containerName ?? 'backend' - image: '${containerAppConfiguration.?containerImageRegistryDomain ?? 'biabcontainerreg.azurecr.io'}/${containerAppConfiguration.?containerImageName ?? 'macaebackend'}:${containerAppConfiguration.?containerImageTag ?? 'latest'}' + name: 'backend' + image: '${backendContainerRegistryHostname}/${backendContainerImageName}:${backendContainerImageTag}' + //TODO: configure probes for container app + // probes: [ + // { + // httpGet: { + // httpHeaders: [ + // { + // name: 'Custom-Header' + // value: 'Awesome' + // } + // ] + // path: '/health' + // port: 8080 + // } + // initialDelaySeconds: 3 + // periodSeconds: 3 + // type: 'Liveness' + // } + // ] resources: { - //TODO: Make cpu and memory parameterized - cpu: containerAppConfiguration.?containerCpu ?? '2.0' - memory: containerAppConfiguration.?containerMemory ?? '4.0Gi' + cpu: '2.0' + memory: '4.0Gi' } env: [ { @@ -1006,11 +1375,11 @@ module containerApp 'br/public:avm/res/app/container-app:0.14.2' = if (container } { name: 'APPLICATIONINSIGHTS_INSTRUMENTATION_KEY' - value: applicationInsights.outputs.instrumentationKey + value: enableMonitoring ? applicationInsights!.outputs.instrumentationKey : '' } { name: 'APPLICATIONINSIGHTS_CONNECTION_STRING' - value: applicationInsights.outputs.connectionString + value: enableMonitoring ? applicationInsights!.outputs.connectionString : '' } { name: 'AZURE_AI_SUBSCRIPTION_ID' @@ -1026,19 +1395,19 @@ module containerApp 'br/public:avm/res/app/container-app:0.14.2' = if (container } { name: 'FRONTEND_SITE_NAME' - value: 'https://${webSiteName}.azurewebsites.net' + value: 'https://${webSiteResourceName}.azurewebsites.net' } { name: 'AZURE_AI_AGENT_ENDPOINT' - value: aiFoundryAiServices.outputs.aiProjectInfo.apiEndpoint + value: aiFoundryAiProjectEndpoint } { name: 'AZURE_AI_AGENT_MODEL_DEPLOYMENT_NAME' value: aiFoundryAiServicesModelDeployment.name } { - name: 'APP_ENV' - value: 'Prod' + name: 'AZURE_CLIENT_ID' + value: userAssignedIdentity.outputs.clientId // NOTE: This is the client ID of the managed identity, not the Entra application, and is needed for the App Service to access the Cosmos DB account. } ] } @@ -1046,55 +1415,68 @@ module containerApp 'br/public:avm/res/app/container-app:0.14.2' = if (container } } -var webServerFarmEnabled = webServerFarmConfiguration.?enabled ?? true -var webServerFarmResourceName = webServerFarmConfiguration.?name ?? 'asp-${solutionPrefix}' - // ========== Frontend server farm ========== // -// WAF best practices for web app service: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/app-service-web-apps -module webServerFarm 'br/public:avm/res/web/serverfarm:0.4.1' = if (webServerFarmEnabled) { +// WAF best practices for Web Application Services: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/app-service-web-apps +// PSRule for Web Server Farm: https://azure.github.io/PSRule.Rules.Azure/en/rules/resource/#app-service +var webServerFarmResourceName = 'asp-${solutionSuffix}' +module webServerFarm 'br/public:avm/res/web/serverfarm:0.5.0' = { name: take('avm.res.web.serverfarm.${webServerFarmResourceName}', 64) params: { name: webServerFarmResourceName tags: tags - location: webServerFarmConfiguration.?location ?? solutionLocation - skuName: webServerFarmConfiguration.?skuName ?? 'P1v3' - skuCapacity: webServerFarmConfiguration.?skuCapacity ?? 3 + enableTelemetry: enableTelemetry + location: location reserved: true - diagnosticSettings: [{ workspaceResourceId: logAnalyticsWorkspaceId }] kind: 'linux' - zoneRedundant: false //TODO: make it zone redundant for waf aligned + // WAF aligned configuration for Monitoring + diagnosticSettings: enableMonitoring ? [{ workspaceResourceId: logAnalyticsWorkspaceResourceId }] : null + // WAF aligned configuration for Scalability + skuName: enableScalability || enableRedundancy ? 'P1v3' : 'B3' + skuCapacity: enableScalability ? 3 : 1 + // WAF aligned configuration for Redundancy + zoneRedundant: enableRedundancy ? true : false } } // ========== Frontend web site ========== // // WAF best practices for web app service: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/app-service-web-apps -var webSiteEnabled = webSiteConfiguration.?enabled ?? true +// PSRule for Web Server Farm: https://azure.github.io/PSRule.Rules.Azure/en/rules/resource/#app-service -var webSiteName = 'app-${solutionPrefix}' -module webSite 'br/public:avm/res/web/site:0.15.1' = if (webSiteEnabled) { - name: take('avm.res.web.site.${webSiteName}', 64) +//NOTE: AVM module adds 1 MB of overhead to the template. Keeping vanilla resource to save template size. +var webSiteResourceName = 'app-${solutionSuffix}' +module webSite 'modules/web-sites.bicep' = { + name: take('module.web-sites.${webSiteResourceName}', 64) params: { - name: webSiteName - tags: webSiteConfiguration.?tags ?? tags - location: webSiteConfiguration.?location ?? solutionLocation + name: webSiteResourceName + tags: tags + location: location kind: 'app,linux,container' - enableTelemetry: enableTelemetry - serverFarmResourceId: webSiteConfiguration.?environmentResourceId ?? webServerFarm.?outputs.resourceId - appInsightResourceId: applicationInsights.outputs.resourceId - diagnosticSettings: [{ workspaceResourceId: logAnalyticsWorkspaceId }] - publicNetworkAccess: 'Enabled' //TODO: use Azure Front Door WAF or Application Gateway WAF instead + serverFarmResourceId: webServerFarm.?outputs.resourceId siteConfig: { - linuxFxVersion: 'DOCKER|${webSiteConfiguration.?containerImageRegistryDomain ?? 'biabcontainerreg.azurecr.io'}/${webSiteConfiguration.?containerImageName ?? 'macaefrontend'}:${webSiteConfiguration.?containerImageTag ?? 'latest'}' - } - appSettingsKeyValuePairs: { - SCM_DO_BUILD_DURING_DEPLOYMENT: 'true' - DOCKER_REGISTRY_SERVER_URL: 'https://${webSiteConfiguration.?containerImageRegistryDomain ?? 'biabcontainerreg.azurecr.io'}' - WEBSITES_PORT: '3000' - WEBSITES_CONTAINER_START_TIME_LIMIT: '1800' // 30 minutes, adjust as needed - BACKEND_API_URL: 'https://${containerApp.outputs.fqdn}' - AUTH_ENABLED: 'false' - APP_ENV: 'Prod' + linuxFxVersion: 'DOCKER|${frontendContainerRegistryHostname}/${frontendContainerImageName}:${frontendContainerImageTag}' + minTlsVersion: '1.2' } + configs: [ + { + name: 'appsettings' + properties: { + SCM_DO_BUILD_DURING_DEPLOYMENT: 'true' + DOCKER_REGISTRY_SERVER_URL: 'https://${frontendContainerRegistryHostname}' + WEBSITES_PORT: '3000' + WEBSITES_CONTAINER_START_TIME_LIMIT: '1800' // 30 minutes, adjust as needed + BACKEND_API_URL: 'https://${containerApp.outputs.fqdn}' + AUTH_ENABLED: 'false' + } + // WAF aligned configuration for Monitoring + applicationInsightResourceId: enableMonitoring ? applicationInsights!.outputs.resourceId : null + } + ] + diagnosticSettings: enableMonitoring ? [{ workspaceResourceId: logAnalyticsWorkspaceResourceId }] : null + // WAF aligned configuration for Private Networking + vnetRouteAllEnabled: enablePrivateNetworking ? true : false + vnetImagePullEnabled: enablePrivateNetworking ? true : false + virtualNetworkSubnetId: enablePrivateNetworking ? virtualNetwork!.outputs.subnetResourceIds[4] : null + publicNetworkAccess: 'Enabled' // Always enabling the public network access for Web App } } @@ -1102,626 +1484,11 @@ module webSite 'br/public:avm/res/web/site:0.15.1' = if (webSiteEnabled) { // Outputs // // ============ // -// Add your outputs here +@description('The resource group the resources were deployed into.') +output resourceGroupName string = resourceGroup().name @description('The default url of the website to connect to the Multi-Agent Custom Automation Engine solution.') output webSiteDefaultHostname string = webSite.outputs.defaultHostname - -@export() -@description('The type for the Multi-Agent Custom Automation Engine Log Analytics Workspace resource configuration.') -type logAnalyticsWorkspaceConfigurationType = { - @description('Optional. If the Log Analytics Workspace resource should be deployed or not.') - enabled: bool? - - @description('Optional. The name of the Log Analytics Workspace resource.') - @maxLength(63) - name: string? - - @description('Optional. Location for the Log Analytics Workspace resource.') - @metadata({ azd: { type: 'location' } }) - location: string? - - @description('Optional. The tags to for the Log Analytics Workspace resource.') - tags: object? - - @description('Optional. The SKU for the Log Analytics Workspace resource.') - sku: ('CapacityReservation' | 'Free' | 'LACluster' | 'PerGB2018' | 'PerNode' | 'Premium' | 'Standalone' | 'Standard')? - - @description('Optional. The number of days to retain the data in the Log Analytics Workspace. If empty, it will be set to 365 days.') - @maxValue(730) - dataRetentionInDays: int? - - @description('Optional: Existing Log Analytics Workspace Resource ID') - existingWorkspaceResourceId: string? -} - -@export() -@description('The type for the Multi-Agent Custom Automation Engine Application Insights resource configuration.') -type applicationInsightsConfigurationType = { - @description('Optional. If the Application Insights resource should be deployed or not.') - enabled: bool? - - @description('Optional. The name of the Application Insights resource.') - @maxLength(90) - name: string? - - @description('Optional. Location for the Application Insights resource.') - @metadata({ azd: { type: 'location' } }) - location: string? - - @description('Optional. The tags to set for the Application Insights resource.') - tags: object? - - @description('Optional. The retention of Application Insights data in days. If empty, Standard will be used.') - retentionInDays: (120 | 180 | 270 | 30 | 365 | 550 | 60 | 730 | 90)? -} - -@export() -@description('The type for the Multi-Agent Custom Automation Engine Application User Assigned Managed Identity resource configuration.') -type userAssignedManagedIdentityType = { - @description('Optional. If the User Assigned Managed Identity resource should be deployed or not.') - enabled: bool? - - @description('Optional. The name of the User Assigned Managed Identity resource.') - @maxLength(128) - name: string? - - @description('Optional. Location for the User Assigned Managed Identity resource.') - @metadata({ azd: { type: 'location' } }) - location: string? - - @description('Optional. The tags to set for the User Assigned Managed Identity resource.') - tags: object? -} - -@export() -import { securityRuleType } from 'br/public:avm/res/network/network-security-group:0.5.1' -@description('The type for the Multi-Agent Custom Automation Engine Network Security Group resource configuration.') -type networkSecurityGroupConfigurationType = { - @description('Optional. If the Network Security Group resource should be deployed or not.') - enabled: bool? - - @description('Optional. The name of the Network Security Group resource.') - @maxLength(90) - name: string? - - @description('Optional. Location for the Network Security Group resource.') - @metadata({ azd: { type: 'location' } }) - location: string? - - @description('Optional. The tags to set for the Network Security Group resource.') - tags: object? - - @description('Optional. The security rules to set for the Network Security Group resource.') - securityRules: securityRuleType[]? -} - -@export() -@description('The type for the Multi-Agent Custom Automation virtual network resource configuration.') -type virtualNetworkConfigurationType = { - @description('Optional. If the Virtual Network resource should be deployed or not.') - enabled: bool? - - @description('Optional. The name of the Virtual Network resource.') - @maxLength(90) - name: string? - - @description('Optional. Location for the Virtual Network resource.') - @metadata({ azd: { type: 'location' } }) - location: string? - - @description('Optional. The tags to set for the Virtual Network resource.') - tags: object? - - @description('Optional. An array of 1 or more IP Addresses prefixes for the Virtual Network resource.') - addressPrefixes: string[]? - - @description('Optional. An array of 1 or more subnets for the Virtual Network resource.') - subnets: subnetType[]? -} - -import { roleAssignmentType } from 'br/public:avm/utl/types/avm-common-types:0.5.1' -type subnetType = { - @description('Optional. The Name of the subnet resource.') - name: string - - @description('Conditional. The address prefix for the subnet. Required if `addressPrefixes` is empty.') - addressPrefix: string? - - @description('Conditional. List of address prefixes for the subnet. Required if `addressPrefix` is empty.') - addressPrefixes: string[]? - - @description('Optional. Application gateway IP configurations of virtual network resource.') - applicationGatewayIPConfigurations: object[]? - - @description('Optional. The delegation to enable on the subnet.') - delegation: string? - - @description('Optional. The resource ID of the NAT Gateway to use for the subnet.') - natGatewayResourceId: string? - - @description('Optional. The resource ID of the network security group to assign to the subnet.') - networkSecurityGroupResourceId: string? - - @description('Optional. enable or disable apply network policies on private endpoint in the subnet.') - privateEndpointNetworkPolicies: ('Disabled' | 'Enabled' | 'NetworkSecurityGroupEnabled' | 'RouteTableEnabled')? - - @description('Optional. enable or disable apply network policies on private link service in the subnet.') - privateLinkServiceNetworkPolicies: ('Disabled' | 'Enabled')? - - @description('Optional. Array of role assignments to create.') - roleAssignments: roleAssignmentType[]? - - @description('Optional. The resource ID of the route table to assign to the subnet.') - routeTableResourceId: string? - - @description('Optional. An array of service endpoint policies.') - serviceEndpointPolicies: object[]? - - @description('Optional. The service endpoints to enable on the subnet.') - serviceEndpoints: string[]? - - @description('Optional. Set this property to false to disable default outbound connectivity for all VMs in the subnet. This property can only be set at the time of subnet creation and cannot be updated for an existing subnet.') - defaultOutboundAccess: bool? - - @description('Optional. Set this property to Tenant to allow sharing subnet with other subscriptions in your AAD tenant. This property can only be set if defaultOutboundAccess is set to false, both properties can only be set if subnet is empty.') - sharingScope: ('DelegatedServices' | 'Tenant')? -} - -@export() -@description('The type for the Multi-Agent Custom Automation Engine Bastion resource configuration.') -type bastionConfigurationType = { - @description('Optional. If the Bastion resource should be deployed or not.') - enabled: bool? - - @description('Optional. The name of the Bastion resource.') - @maxLength(90) - name: string? - - @description('Optional. Location for the Bastion resource.') - @metadata({ azd: { type: 'location' } }) - location: string? - - @description('Optional. The tags to set for the Bastion resource.') - tags: object? - - @description('Optional. The SKU for the Bastion resource.') - sku: ('Basic' | 'Developer' | 'Premium' | 'Standard')? - - @description('Optional. The Virtual Network resource id where the Bastion resource should be deployed.') - virtualNetworkResourceId: string? - - @description('Optional. The name of the Public Ip resource created to connect to Bastion.') - publicIpResourceName: string? -} - -@export() -@description('The type for the Multi-Agent Custom Automation Engine virtual machine resource configuration.') -type virtualMachineConfigurationType = { - @description('Optional. If the Virtual Machine resource should be deployed or not.') - enabled: bool? - - @description('Optional. The name of the Virtual Machine resource.') - @maxLength(90) - name: string? - - @description('Optional. Location for the Virtual Machine resource.') - @metadata({ azd: { type: 'location' } }) - location: string? - - @description('Optional. The tags to set for the Virtual Machine resource.') - tags: object? - - @description('Optional. Specifies the size for the Virtual Machine resource.') - vmSize: ( - | 'Basic_A0' - | 'Basic_A1' - | 'Basic_A2' - | 'Basic_A3' - | 'Basic_A4' - | 'Standard_A0' - | 'Standard_A1' - | 'Standard_A2' - | 'Standard_A3' - | 'Standard_A4' - | 'Standard_A5' - | 'Standard_A6' - | 'Standard_A7' - | 'Standard_A8' - | 'Standard_A9' - | 'Standard_A10' - | 'Standard_A11' - | 'Standard_A1_v2' - | 'Standard_A2_v2' - | 'Standard_A4_v2' - | 'Standard_A8_v2' - | 'Standard_A2m_v2' - | 'Standard_A4m_v2' - | 'Standard_A8m_v2' - | 'Standard_B1s' - | 'Standard_B1ms' - | 'Standard_B2s' - | 'Standard_B2ms' - | 'Standard_B4ms' - | 'Standard_B8ms' - | 'Standard_D1' - | 'Standard_D2' - | 'Standard_D3' - | 'Standard_D4' - | 'Standard_D11' - | 'Standard_D12' - | 'Standard_D13' - | 'Standard_D14' - | 'Standard_D1_v2' - | 'Standard_D2_v2' - | 'Standard_D3_v2' - | 'Standard_D4_v2' - | 'Standard_D5_v2' - | 'Standard_D2_v3' - | 'Standard_D4_v3' - | 'Standard_D8_v3' - | 'Standard_D16_v3' - | 'Standard_D32_v3' - | 'Standard_D64_v3' - | 'Standard_D2s_v3' - | 'Standard_D4s_v3' - | 'Standard_D8s_v3' - | 'Standard_D16s_v3' - | 'Standard_D32s_v3' - | 'Standard_D64s_v3' - | 'Standard_D11_v2' - | 'Standard_D12_v2' - | 'Standard_D13_v2' - | 'Standard_D14_v2' - | 'Standard_D15_v2' - | 'Standard_DS1' - | 'Standard_DS2' - | 'Standard_DS3' - | 'Standard_DS4' - | 'Standard_DS11' - | 'Standard_DS12' - | 'Standard_DS13' - | 'Standard_DS14' - | 'Standard_DS1_v2' - | 'Standard_DS2_v2' - | 'Standard_DS3_v2' - | 'Standard_DS4_v2' - | 'Standard_DS5_v2' - | 'Standard_DS11_v2' - | 'Standard_DS12_v2' - | 'Standard_DS13_v2' - | 'Standard_DS14_v2' - | 'Standard_DS15_v2' - | 'Standard_DS13-4_v2' - | 'Standard_DS13-2_v2' - | 'Standard_DS14-8_v2' - | 'Standard_DS14-4_v2' - | 'Standard_E2_v3' - | 'Standard_E4_v3' - | 'Standard_E8_v3' - | 'Standard_E16_v3' - | 'Standard_E32_v3' - | 'Standard_E64_v3' - | 'Standard_E2s_v3' - | 'Standard_E4s_v3' - | 'Standard_E8s_v3' - | 'Standard_E16s_v3' - | 'Standard_E32s_v3' - | 'Standard_E64s_v3' - | 'Standard_E32-16_v3' - | 'Standard_E32-8s_v3' - | 'Standard_E64-32s_v3' - | 'Standard_E64-16s_v3' - | 'Standard_F1' - | 'Standard_F2' - | 'Standard_F4' - | 'Standard_F8' - | 'Standard_F16' - | 'Standard_F1s' - | 'Standard_F2s' - | 'Standard_F4s' - | 'Standard_F8s' - | 'Standard_F16s' - | 'Standard_F2s_v2' - | 'Standard_F4s_v2' - | 'Standard_F8s_v2' - | 'Standard_F16s_v2' - | 'Standard_F32s_v2' - | 'Standard_F64s_v2' - | 'Standard_F72s_v2' - | 'Standard_G1' - | 'Standard_G2' - | 'Standard_G3' - | 'Standard_G4' - | 'Standard_G5' - | 'Standard_GS1' - | 'Standard_GS2' - | 'Standard_GS3' - | 'Standard_GS4' - | 'Standard_GS5' - | 'Standard_GS4-8' - | 'Standard_GS4-4' - | 'Standard_GS5-16' - | 'Standard_GS5-8' - | 'Standard_H8' - | 'Standard_H16' - | 'Standard_H8m' - | 'Standard_H16m' - | 'Standard_H16r' - | 'Standard_H16mr' - | 'Standard_L4s' - | 'Standard_L8s' - | 'Standard_L16s' - | 'Standard_L32s' - | 'Standard_M64s' - | 'Standard_M64ms' - | 'Standard_M128s' - | 'Standard_M128ms' - | 'Standard_M64-32ms' - | 'Standard_M64-16ms' - | 'Standard_M128-64ms' - | 'Standard_M128-32ms' - | 'Standard_NC6' - | 'Standard_NC12' - | 'Standard_NC24' - | 'Standard_NC24r' - | 'Standard_NC6s_v2' - | 'Standard_NC12s_v2' - | 'Standard_NC24s_v2' - | 'Standard_NC24rs_v2' - | 'Standard_NC6s_v3' - | 'Standard_NC12s_v3' - | 'Standard_NC24s_v3' - | 'Standard_NC24rs_v3' - | 'Standard_ND6s' - | 'Standard_ND12s' - | 'Standard_ND24s' - | 'Standard_ND24rs' - | 'Standard_NV6' - | 'Standard_NV12' - | 'Standard_NV24')? - - @description('Optional. The username for the administrator account on the virtual machine. Required if a virtual machine is created as part of the module.') - adminUsername: string? - - @description('Optional. The password for the administrator account on the virtual machine. Required if a virtual machine is created as part of the module.') - @secure() - adminPassword: string? - - @description('Optional. The resource ID of the subnet where the Virtual Machine resource should be deployed.') - subnetResourceId: string? -} - -@export() -import { deploymentType } from 'br/public:avm/res/cognitive-services/account:0.10.2' -@description('The type for the Multi-Agent Custom Automation Engine AI Services resource configuration.') -type aiServicesConfigurationType = { - @description('Optional. If the AI Services resource should be deployed or not.') - enabled: bool? - - @description('Optional. The name of the AI Services resource.') - @maxLength(90) - name: string? - - @description('Optional. Location for the AI Services resource.') - @metadata({ azd: { type: 'location' } }) - location: string? - - @description('Optional. The tags to set for the AI Services resource.') - tags: object? - - @description('Optional. The SKU of the AI Services resource. Use \'Get-AzCognitiveServicesAccountSku\' to determine a valid combinations of \'kind\' and \'SKU\' for your Azure region.') - sku: ( - | 'C2' - | 'C3' - | 'C4' - | 'F0' - | 'F1' - | 'S' - | 'S0' - | 'S1' - | 'S10' - | 'S2' - | 'S3' - | 'S4' - | 'S5' - | 'S6' - | 'S7' - | 'S8' - | 'S9')? - - @description('Optional. The resource Id of the subnet where the AI Services private endpoint should be created.') - subnetResourceId: string? - - @description('Optional. The model deployments to set for the AI Services resource.') - deployments: deploymentType[]? - - @description('Optional. The capacity to set for AI Services GTP model.') - modelCapacity: int? -} - -@export() -@description('The type for the Multi-Agent Custom Automation Engine AI Foundry AI Project resource configuration.') -type aiProjectConfigurationType = { - @description('Optional. If the AI Project resource should be deployed or not.') - enabled: bool? - - @description('Optional. The name of the AI Project resource.') - @maxLength(90) - name: string? - - @description('Optional. Location for the AI Project resource deployment.') - @metadata({ azd: { type: 'location' } }) - location: string? - - @description('Optional. The SKU of the AI Project resource.') - sku: ('Basic' | 'Free' | 'Standard' | 'Premium')? - - @description('Optional. The tags to set for the AI Project resource.') - tags: object? -} - -import { sqlDatabaseType } from 'br/public:avm/res/document-db/database-account:0.13.0' -@export() -@description('The type for the Multi-Agent Custom Automation Engine Cosmos DB Account resource configuration.') -type cosmosDbAccountConfigurationType = { - @description('Optional. If the Cosmos DB Account resource should be deployed or not.') - enabled: bool? - @description('Optional. The name of the Cosmos DB Account resource.') - @maxLength(60) - name: string? - - @description('Optional. Location for the Cosmos DB Account resource.') - @metadata({ azd: { type: 'location' } }) - location: string? - - @description('Optional. The tags to set for the Cosmos DB Account resource.') - tags: object? - - @description('Optional. The resource Id of the subnet where the Cosmos DB Account private endpoint should be created.') - subnetResourceId: string? - - @description('Optional. The SQL databases configuration for the Cosmos DB Account resource.') - sqlDatabases: sqlDatabaseType[]? -} - -@export() -@description('The type for the Multi-Agent Custom Automation Engine Container App Environment resource configuration.') -type containerAppEnvironmentConfigurationType = { - @description('Optional. If the Container App Environment resource should be deployed or not.') - enabled: bool? - - @description('Optional. The name of the Container App Environment resource.') - @maxLength(60) - name: string? - - @description('Optional. Location for the Container App Environment resource.') - @metadata({ azd: { type: 'location' } }) - location: string? - - @description('Optional. The tags to set for the Container App Environment resource.') - tags: object? - - @description('Optional. The resource Id of the subnet where the Container App Environment private endpoint should be created.') - subnetResourceId: string? -} - -@export() -@description('The type for the Multi-Agent Custom Automation Engine Container App resource configuration.') -type containerAppConfigurationType = { - @description('Optional. If the Container App resource should be deployed or not.') - enabled: bool? - - @description('Optional. The name of the Container App resource.') - @maxLength(60) - name: string? - - @description('Optional. Location for the Container App resource.') - @metadata({ azd: { type: 'location' } }) - location: string? - - @description('Optional. The tags to set for the Container App resource.') - tags: object? - - @description('Optional. The resource Id of the Container App Environment where the Container App should be created.') - environmentResourceId: string? - - @description('Optional. The maximum number of replicas of the Container App.') - maxReplicas: int? - - @description('Optional. The minimum number of replicas of the Container App.') - minReplicas: int? - - @description('Optional. The ingress target port of the Container App.') - ingressTargetPort: int? - - @description('Optional. The concurrent requests allowed for the Container App.') - concurrentRequests: string? - - @description('Optional. The name given to the Container App.') - containerName: string? - - @description('Optional. The container registry domain of the container image to be used by the Container App. Default to `biabcontainerreg.azurecr.io`') - containerImageRegistryDomain: string? - - @description('Optional. The name of the container image to be used by the Container App.') - containerImageName: string? - - @description('Optional. The tag of the container image to be used by the Container App.') - containerImageTag: string? - - @description('Optional. The CPU reserved for the Container App. Defaults to 2.0') - containerCpu: string? - - @description('Optional. The Memory reserved for the Container App. Defaults to 4.0Gi') - containerMemory: string? -} - -@export() -@description('The type for the Multi-Agent Custom Automation Engine Entra ID Application resource configuration.') -type entraIdApplicationConfigurationType = { - @description('Optional. If the Entra ID Application for website authentication should be deployed or not.') - enabled: bool? -} - -@export() -@description('The type for the Multi-Agent Custom Automation Engine Web Server Farm resource configuration.') -type webServerFarmConfigurationType = { - @description('Optional. If the Web Server Farm resource should be deployed or not.') - enabled: bool? - - @description('Optional. The name of the Web Server Farm resource.') - @maxLength(60) - name: string? - - @description('Optional. Location for the Web Server Farm resource.') - @metadata({ azd: { type: 'location' } }) - location: string? - - @description('Optional. The tags to set for the Web Server Farm resource.') - tags: object? - - @description('Optional. The name of th SKU that will determine the tier, size and family for the Web Server Farm resource. This defaults to P1v3 to leverage availability zones.') - skuName: string? - - @description('Optional. Number of workers associated with the App Service Plan. This defaults to 3, to leverage availability zones.') - skuCapacity: int? -} - -@export() -@description('The type for the Multi-Agent Custom Automation Engine Web Site resource configuration.') -type webSiteConfigurationType = { - @description('Optional. If the Web Site resource should be deployed or not.') - enabled: bool? - - @description('Optional. The name of the Web Site resource.') - @maxLength(60) - name: string? - - @description('Optional. Location for the Web Site resource deployment.') - @metadata({ azd: { type: 'location' } }) - location: string? - - @description('Optional. The tags to set for the Web Site resource.') - tags: object? - - @description('Optional. The resource Id of the Web Site Environment where the Web Site should be created.') - environmentResourceId: string? - - @description('Optional. The name given to the Container App.') - containerName: string? - - @description('Optional. The container registry domain of the container image to be used by the Web Site. Default to `biabcontainerreg.azurecr.io`') - containerImageRegistryDomain: string? - - @description('Optional. The name of the container image to be used by the Web Site.') - containerImageName: string? - - @description('Optional. The tag of the container image to be used by the Web Site.') - containerImageTag: string? -} - - output COSMOSDB_ENDPOINT string = 'https://${cosmosDbResourceName}.documents.azure.com:443/' output COSMOSDB_DATABASE string = cosmosDbDatabaseName output COSMOSDB_CONTAINER string = cosmosDbDatabaseMemoryContainerName @@ -1737,5 +1504,5 @@ output AZURE_AI_PROJECT_NAME string = aiFoundryAiProjectName output AZURE_AI_MODEL_DEPLOYMENT_NAME string = aiFoundryAiServicesModelDeployment.name // output APPLICATIONINSIGHTS_CONNECTION_STRING string = applicationInsights.outputs.connectionString output AZURE_AI_AGENT_MODEL_DEPLOYMENT_NAME string = aiFoundryAiServicesModelDeployment.name -output AZURE_AI_AGENT_ENDPOINT string = aiFoundryAiServices.outputs.aiProjectInfo.apiEndpoint +output AZURE_AI_AGENT_ENDPOINT string = aiFoundryAiProjectEndpoint output APP_ENV string = 'Prod' diff --git a/infra/main.parameters.json b/infra/main.parameters.json index 16b465617..14965085a 100644 --- a/infra/main.parameters.json +++ b/infra/main.parameters.json @@ -1,102 +1,42 @@ { - "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", - "contentVersion": "1.0.0.0", - "parameters": { - "aiModelDeployments": { - "value": [ - { - "name": "gpt", - "model": { - "name": "gpt-4o", - "version": "2024-08-06", - "format": "OpenAI" - }, - "sku": { - "name": "GlobalStandard", - "capacity": 140 - } - } - ] - }, - "environmentName": { - "value": "${AZURE_ENV_NAME}" - }, - "solutionLocation": { - "value": "${AZURE_LOCATION}" - }, - "aiDeploymentsLocation": { - "value": "${AZURE_ENV_OPENAI_LOCATION}" - }, - "modelDeploymentType": { - "value": "${AZURE_ENV_MODEL_DEPLOYMENT_TYPE}" - }, - "gptModelName": { - "value": "${AZURE_ENV_MODEL_NAME}" - }, - "gptModelVersion": { - "value": "${AZURE_ENV_MODEL_VERSION}" - }, - "gptModelCapacity": { - "value": "${AZURE_ENV_MODEL_CAPACITY}" - }, - "existingFoundryProjectResourceId": { - "value": "${AZURE_ENV_FOUNDRY_PROJECT_ID}" - }, - "imageTag": { - "value": "${AZURE_ENV_IMAGE_TAG}" - }, - "enableTelemetry": { - "value": "${AZURE_ENV_ENABLE_TELEMETRY}" - }, - "existingLogAnalyticsWorkspaceId": { + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "solutionName": { + "value": "${AZURE_ENV_NAME}" + }, + "location": { + "value": "${AZURE_LOCATION}" + }, + "azureAiServiceLocation": { + "value": "${AZURE_ENV_OPENAI_LOCATION}" + }, + "gptModelDeploymentType": { + "value": "${AZURE_ENV_MODEL_DEPLOYMENT_TYPE}" + }, + "gptModelName": { + "value": "${AZURE_ENV_MODEL_NAME}" + }, + "gptModelVersion": { + "value": "${AZURE_ENV_MODEL_VERSION}" + }, + "gptModelCapacity": { + "value": "${AZURE_ENV_MODEL_CAPACITY}" + }, + "backendContainerImageTag": { + "value": "${AZURE_ENV_IMAGE_TAG=latest}" + }, + "frontendContainerImageTag": { + "value": "${AZURE_ENV_IMAGE_TAG=latest}" + }, + "enableTelemetry": { + "value": "${AZURE_ENV_ENABLE_TELEMETRY}" + }, + "existingLogAnalyticsWorkspaceId": { "value": "${AZURE_ENV_LOG_ANALYTICS_WORKSPACE_ID}" - }, - "backendExists": { - "value": "${SERVICE_BACKEND_RESOURCE_EXISTS=false}" - }, - "backendDefinition": { - "value": { - "settings": [ - { - "name": "", - "value": "${VAR}", - "_comment_name": "The name of the environment variable when running in Azure. If empty, ignored.", - "_comment_value": "The value to provide. This can be a fixed literal, or an expression like ${VAR} to use the value of 'VAR' from the current environment." - }, - { - "name": "", - "value": "${VAR_S}", - "secret": true, - "_comment_name": "The name of the environment variable when running in Azure. If empty, ignored.", - "_comment_value": "The value to provide. This can be a fixed literal, or an expression like ${VAR_S} to use the value of 'VAR_S' from the current environment." - } - ] - } - }, - "frontendExists": { - "value": "${SERVICE_FRONTEND_RESOURCE_EXISTS=false}" - }, - "frontendDefinition": { - "value": { - "settings": [ - { - "name": "", - "value": "${VAR}", - "_comment_name": "The name of the environment variable when running in Azure. If empty, ignored.", - "_comment_value": "The value to provide. This can be a fixed literal, or an expression like ${VAR} to use the value of 'VAR' from the current environment." - }, - { - "name": "", - "value": "${VAR_S}", - "secret": true, - "_comment_name": "The name of the environment variable when running in Azure. If empty, ignored.", - "_comment_value": "The value to provide. This can be a fixed literal, or an expression like ${VAR_S} to use the value of 'VAR_S' from the current environment." - } - ] - } - }, - "principalId": { - "value": "${AZURE_PRINCIPAL_ID}" - } + }, + "existingAiFoundryAiProjectResourceId": { + "value": "${AZURE_ENV_FOUNDRY_PROJECT_ID}" } + } } \ No newline at end of file diff --git a/infra/main.waf.parameters.json b/infra/main.waf.parameters.json new file mode 100644 index 000000000..c6fd16c49 --- /dev/null +++ b/infra/main.waf.parameters.json @@ -0,0 +1,57 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "solutionName": { + "value": "${AZURE_ENV_NAME}" + }, + "location": { + "value": "${AZURE_LOCATION}" + }, + "azureAiServiceLocation": { + "value": "${AZURE_ENV_OPENAI_LOCATION}" + }, + "gptModelDeploymentType": { + "value": "${AZURE_ENV_MODEL_DEPLOYMENT_TYPE}" + }, + "gptModelName": { + "value": "${AZURE_ENV_MODEL_NAME}" + }, + "gptModelVersion": { + "value": "${AZURE_ENV_MODEL_VERSION}" + }, + "gptModelCapacity": { + "value": "${AZURE_ENV_MODEL_CAPACITY}" + }, + "backendContainerImageTag": { + "value": "${AZURE_ENV_IMAGE_TAG=latest}" + }, + "frontendContainerImageTag": { + "value": "${AZURE_ENV_IMAGE_TAG=latest}" + }, + "enableTelemetry": { + "value": "${AZURE_ENV_ENABLE_TELEMETRY}" + }, + "enableMonitoring": { + "value": true + }, + "enablePrivateNetworking": { + "value": true + }, + "enableScalability": { + "value": true + }, + "virtualMachineAdminUsername": { + "value": "${AZURE_ENV_VM_ADMIN_USERNAME}" + }, + "virtualMachineAdminPassword": { + "value": "${AZURE_ENV_VM_ADMIN_PASSWORD}" + }, + "existingLogAnalyticsWorkspaceId": { + "value": "${AZURE_ENV_LOG_ANALYTICS_WORKSPACE_ID}" + }, + "existingAiFoundryAiProjectResourceId": { + "value": "${AZURE_ENV_FOUNDRY_PROJECT_ID}" + } + } +} \ No newline at end of file diff --git a/infra/modules/ai-project.bicep b/infra/modules/ai-project.bicep new file mode 100644 index 000000000..bfed5eb02 --- /dev/null +++ b/infra/modules/ai-project.bicep @@ -0,0 +1,42 @@ +@description('Required. Name of the AI Services project.') +param name string + +@description('Required. The location of the Project resource.') +param location string = resourceGroup().location + +@description('Optional. The description of the AI Foundry project to create. Defaults to the project name.') +param desc string = name + +@description('Required. Name of the existing Cognitive Services resource to create the AI Foundry project in.') +param aiServicesName string + +@description('Optional. Tags to be applied to the resources.') +param tags object = {} + +// Reference to cognitive service in current resource group for new projects +resource cogServiceReference 'Microsoft.CognitiveServices/accounts@2025-06-01' existing = { + name: aiServicesName +} + +resource aiProject 'Microsoft.CognitiveServices/accounts/projects@2025-06-01' = { + parent: cogServiceReference + name: name + tags: tags + location: location + identity: { + type: 'SystemAssigned' + } + properties: { + description: desc + displayName: name + } +} + +@description('Required. Name of the AI project.') +output name string = aiProject.name + +@description('Required. Resource ID of the AI project.') +output resourceId string = aiProject.id + +@description('Required. API endpoint for the AI project.') +output apiEndpoint string = aiProject!.properties.endpoints['AI Foundry API'] diff --git a/infra/modules/ai-services-deployments.bicep b/infra/modules/ai-services-deployments.bicep new file mode 100644 index 000000000..8c32a0e73 --- /dev/null +++ b/infra/modules/ai-services-deployments.bicep @@ -0,0 +1,197 @@ +@description('Required. The name of Cognitive Services account.') +param name string + +@description('Optional. SKU of the Cognitive Services account. Use \'Get-AzCognitiveServicesAccountSku\' to determine a valid combinations of \'kind\' and \'SKU\' for your Azure region.') +@allowed([ + 'C2' + 'C3' + 'C4' + 'F0' + 'F1' + 'S' + 'S0' + 'S1' + 'S10' + 'S2' + 'S3' + 'S4' + 'S5' + 'S6' + 'S7' + 'S8' + 'S9' +]) +param sku string = 'S0' + +import { deploymentType } from 'br:mcr.microsoft.com/bicep/avm/res/cognitive-services/account:0.13.2' +@description('Optional. Array of deployments about cognitive service accounts to create.') +param deployments deploymentType[]? + +import { roleAssignmentType } from 'br/public:avm/utl/types/avm-common-types:0.5.1' +@description('Optional. Array of role assignments to create.') +param roleAssignments roleAssignmentType[]? + +var builtInRoleNames = { + 'Cognitive Services Contributor': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + '25fbc0a9-bd7c-42a3-aa1a-3b75d497ee68' + ) + 'Cognitive Services Custom Vision Contributor': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + 'c1ff6cc2-c111-46fe-8896-e0ef812ad9f3' + ) + 'Cognitive Services Custom Vision Deployment': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + '5c4089e1-6d96-4d2f-b296-c1bc7137275f' + ) + 'Cognitive Services Custom Vision Labeler': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + '88424f51-ebe7-446f-bc41-7fa16989e96c' + ) + 'Cognitive Services Custom Vision Reader': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + '93586559-c37d-4a6b-ba08-b9f0940c2d73' + ) + 'Cognitive Services Custom Vision Trainer': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + '0a5ae4ab-0d65-4eeb-be61-29fc9b54394b' + ) + 'Cognitive Services Data Reader (Preview)': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + 'b59867f0-fa02-499b-be73-45a86b5b3e1c' + ) + 'Cognitive Services Face Recognizer': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + '9894cab4-e18a-44aa-828b-cb588cd6f2d7' + ) + 'Cognitive Services Immersive Reader User': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + 'b2de6794-95db-4659-8781-7e080d3f2b9d' + ) + 'Cognitive Services Language Owner': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + 'f07febfe-79bc-46b1-8b37-790e26e6e498' + ) + 'Cognitive Services Language Reader': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + '7628b7b8-a8b2-4cdc-b46f-e9b35248918e' + ) + 'Cognitive Services Language Writer': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + 'f2310ca1-dc64-4889-bb49-c8e0fa3d47a8' + ) + 'Cognitive Services LUIS Owner': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + 'f72c8140-2111-481c-87ff-72b910f6e3f8' + ) + 'Cognitive Services LUIS Reader': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + '18e81cdc-4e98-4e29-a639-e7d10c5a6226' + ) + 'Cognitive Services LUIS Writer': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + '6322a993-d5c9-4bed-b113-e49bbea25b27' + ) + 'Cognitive Services Metrics Advisor Administrator': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + 'cb43c632-a144-4ec5-977c-e80c4affc34a' + ) + 'Cognitive Services Metrics Advisor User': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + '3b20f47b-3825-43cb-8114-4bd2201156a8' + ) + 'Cognitive Services OpenAI Contributor': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + 'a001fd3d-188f-4b5d-821b-7da978bf7442' + ) + 'Cognitive Services OpenAI User': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + '5e0bd9bd-7b93-4f28-af87-19fc36ad61bd' + ) + 'Cognitive Services QnA Maker Editor': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + 'f4cc2bf9-21be-47a1-bdf1-5c5804381025' + ) + 'Cognitive Services QnA Maker Reader': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + '466ccd10-b268-4a11-b098-b4849f024126' + ) + 'Cognitive Services Speech Contributor': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + '0e75ca1e-0464-4b4d-8b93-68208a576181' + ) + 'Cognitive Services Speech User': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + 'f2dc8367-1007-4938-bd23-fe263f013447' + ) + 'Cognitive Services User': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + 'a97b65f3-24c7-4388-baec-2e87135dc908' + ) + 'Azure AI Developer': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + '64702f94-c441-49e6-a78b-ef80e0188fee' + ) + Contributor: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'b24988ac-6180-42a0-ab88-20f7382dd24c') + Owner: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', '8e3af657-a8ff-443c-a75c-2fe8c4bcb635') + Reader: subscriptionResourceId('Microsoft.Authorization/roleDefinitions', 'acdd72a7-3385-48ef-bd42-f606fba81ae7') + 'Role Based Access Control Administrator': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + 'f58310d9-a9f6-439a-9e8d-f62e7b41a168' + ) + 'User Access Administrator': subscriptionResourceId( + 'Microsoft.Authorization/roleDefinitions', + '18d7d88d-d35e-4fb5-a5c3-7773c20a72d9' + ) +} + +var formattedRoleAssignments = [ + for (roleAssignment, index) in (roleAssignments ?? []): union(roleAssignment, { + roleDefinitionId: builtInRoleNames[?roleAssignment.roleDefinitionIdOrName] ?? (contains( + roleAssignment.roleDefinitionIdOrName, + '/providers/Microsoft.Authorization/roleDefinitions/' + ) + ? roleAssignment.roleDefinitionIdOrName + : subscriptionResourceId('Microsoft.Authorization/roleDefinitions', roleAssignment.roleDefinitionIdOrName)) + }) +] + +resource cognitiveService 'Microsoft.CognitiveServices/accounts@2025-06-01' existing = { + name: name +} + +@batchSize(1) +resource cognitiveService_deployments 'Microsoft.CognitiveServices/accounts/deployments@2024-10-01' = [ + for (deployment, index) in (deployments ?? []): { + parent: cognitiveService + name: deployment.?name ?? '${name}-deployments' + properties: { + model: deployment.model + raiPolicyName: deployment.?raiPolicyName + versionUpgradeOption: deployment.?versionUpgradeOption + } + sku: deployment.?sku ?? { + name: sku + capacity: sku.?capacity + tier: sku.?tier + size: sku.?size + family: sku.?family + } + } +] + +resource cognitiveService_roleAssignments 'Microsoft.Authorization/roleAssignments@2022-04-01' = [ + for (roleAssignment, index) in (formattedRoleAssignments ?? []): { + name: roleAssignment.?name ?? guid(cognitiveService.id, roleAssignment.principalId, roleAssignment.roleDefinitionId) + properties: { + roleDefinitionId: roleAssignment.roleDefinitionId + principalId: roleAssignment.principalId + description: roleAssignment.?description + principalType: roleAssignment.?principalType + condition: roleAssignment.?condition + conditionVersion: !empty(roleAssignment.?condition) ? (roleAssignment.?conditionVersion ?? '2.0') : null // Must only be set if condtion is set + delegatedManagedIdentityResourceId: roleAssignment.?delegatedManagedIdentityResourceId + } + scope: cognitiveService + } +] diff --git a/infra/modules/web-sites.bicep b/infra/modules/web-sites.bicep new file mode 100644 index 000000000..520f33669 --- /dev/null +++ b/infra/modules/web-sites.bicep @@ -0,0 +1,368 @@ +@description('Required. Name of the site.') +param name string + +@description('Optional. Location for all Resources.') +param location string = resourceGroup().location + +@description('Required. Type of site to deploy.') +@allowed([ + 'functionapp' // function app windows os + 'functionapp,linux' // function app linux os + 'functionapp,workflowapp' // logic app workflow + 'functionapp,workflowapp,linux' // logic app docker container + 'functionapp,linux,container' // function app linux container + 'functionapp,linux,container,azurecontainerapps' // function app linux container azure container apps + 'app,linux' // linux web app + 'app' // windows web app + 'linux,api' // linux api app + 'api' // windows api app + 'app,linux,container' // linux container app + 'app,container,windows' // windows container app +]) +param kind string + +@description('Required. The resource ID of the app service plan to use for the site.') +param serverFarmResourceId string + +@description('Optional. Azure Resource Manager ID of the customers selected Managed Environment on which to host this app.') +param managedEnvironmentId string? + +@description('Optional. Configures a site to accept only HTTPS requests. Issues redirect for HTTP requests.') +param httpsOnly bool = true + +@description('Optional. If client affinity is enabled.') +param clientAffinityEnabled bool = true + +@description('Optional. The resource ID of the app service environment to use for this resource.') +param appServiceEnvironmentResourceId string? + +import { managedIdentityAllType } from 'br/public:avm/utl/types/avm-common-types:0.5.1' +@description('Optional. The managed identity definition for this resource.') +param managedIdentities managedIdentityAllType? + +@description('Optional. The resource ID of the assigned identity to be used to access a key vault with.') +param keyVaultAccessIdentityResourceId string? + +@description('Optional. Checks if Customer provided storage account is required.') +param storageAccountRequired bool = false + +@description('Optional. Azure Resource Manager ID of the Virtual network and subnet to be joined by Regional VNET Integration. This must be of the form /subscriptions/{subscriptionName}/resourceGroups/{resourceGroupName}/providers/Microsoft.Network/virtualNetworks/{vnetName}/subnets/{subnetName}.') +param virtualNetworkSubnetId string? + +@description('Optional. To enable accessing content over virtual network.') +param vnetContentShareEnabled bool = false + +@description('Optional. To enable pulling image over Virtual Network.') +param vnetImagePullEnabled bool = false + +@description('Optional. Virtual Network Route All enabled. This causes all outbound traffic to have Virtual Network Security Groups and User Defined Routes applied.') +param vnetRouteAllEnabled bool = false + +@description('Optional. Stop SCM (KUDU) site when the app is stopped.') +param scmSiteAlsoStopped bool = false + +@description('Optional. The site config object. The defaults are set to the following values: alwaysOn: true, minTlsVersion: \'1.2\', ftpsState: \'FtpsOnly\'.') +param siteConfig resourceInput<'Microsoft.Web/sites@2024-04-01'>.properties.siteConfig = { + alwaysOn: true + minTlsVersion: '1.2' + ftpsState: 'FtpsOnly' +} + +@description('Optional. The web site config.') +param configs appSettingsConfigType[]? + +@description('Optional. The Function App configuration object.') +param functionAppConfig resourceInput<'Microsoft.Web/sites@2024-04-01'>.properties.functionAppConfig? + +import { privateEndpointSingleServiceType } from 'br/public:avm/utl/types/avm-common-types:0.5.1' +@description('Optional. Configuration details for private endpoints. For security reasons, it is recommended to use private endpoints whenever possible.') +param privateEndpoints privateEndpointSingleServiceType[]? + +@description('Optional. Tags of the resource.') +param tags object? + +import { diagnosticSettingFullType } from 'br/public:avm/utl/types/avm-common-types:0.5.1' +@description('Optional. The diagnostic settings of the service.') +param diagnosticSettings diagnosticSettingFullType[]? + +@description('Optional. To enable client certificate authentication (TLS mutual authentication).') +param clientCertEnabled bool = false + +@description('Optional. Client certificate authentication comma-separated exclusion paths.') +param clientCertExclusionPaths string? + +@description(''' +Optional. This composes with ClientCertEnabled setting. +- ClientCertEnabled=false means ClientCert is ignored. +- ClientCertEnabled=true and ClientCertMode=Required means ClientCert is required. +- ClientCertEnabled=true and ClientCertMode=Optional means ClientCert is optional or accepted. +''') +@allowed([ + 'Optional' + 'OptionalInteractiveUser' + 'Required' +]) +param clientCertMode string = 'Optional' + +@description('Optional. If specified during app creation, the app is cloned from a source app.') +param cloningInfo resourceInput<'Microsoft.Web/sites@2024-04-01'>.properties.cloningInfo? + +@description('Optional. Size of the function container.') +param containerSize int? + +@description('Optional. Maximum allowed daily memory-time quota (applicable on dynamic apps only).') +param dailyMemoryTimeQuota int? + +@description('Optional. Setting this value to false disables the app (takes the app offline).') +param enabled bool = true + +@description('Optional. Hostname SSL states are used to manage the SSL bindings for app\'s hostnames.') +param hostNameSslStates resourceInput<'Microsoft.Web/sites@2024-04-01'>.properties.hostNameSslStates? + +@description('Optional. Hyper-V sandbox.') +param hyperV bool = false + +@description('Optional. Site redundancy mode.') +@allowed([ + 'ActiveActive' + 'Failover' + 'GeoRedundant' + 'Manual' + 'None' +]) +param redundancyMode string = 'None' + +@description('Optional. Whether or not public network access is allowed for this resource. For security reasons it should be disabled. If not specified, it will be disabled by default if private endpoints are set.') +@allowed([ + 'Enabled' + 'Disabled' +]) +param publicNetworkAccess string? + +@description('Optional. End to End Encryption Setting.') +param e2eEncryptionEnabled bool? + +@description('Optional. Property to configure various DNS related settings for a site.') +param dnsConfiguration resourceInput<'Microsoft.Web/sites@2024-04-01'>.properties.dnsConfiguration? + +@description('Optional. Specifies the scope of uniqueness for the default hostname during resource creation.') +@allowed([ + 'NoReuse' + 'ResourceGroupReuse' + 'SubscriptionReuse' + 'TenantReuse' +]) +param autoGeneratedDomainNameLabelScope string? + +var formattedUserAssignedIdentities = reduce( + map((managedIdentities.?userAssignedResourceIds ?? []), (id) => { '${id}': {} }), + {}, + (cur, next) => union(cur, next) +) // Converts the flat array to an object like { '${id1}': {}, '${id2}': {} } + +var identity = !empty(managedIdentities) + ? { + type: (managedIdentities.?systemAssigned ?? false) + ? (!empty(managedIdentities.?userAssignedResourceIds ?? {}) ? 'SystemAssigned, UserAssigned' : 'SystemAssigned') + : (!empty(managedIdentities.?userAssignedResourceIds ?? {}) ? 'UserAssigned' : 'None') + userAssignedIdentities: !empty(formattedUserAssignedIdentities) ? formattedUserAssignedIdentities : null + } + : null + +resource app 'Microsoft.Web/sites@2024-04-01' = { + name: name + location: location + kind: kind + tags: tags + identity: identity + properties: { + managedEnvironmentId: !empty(managedEnvironmentId) ? managedEnvironmentId : null + serverFarmId: serverFarmResourceId + clientAffinityEnabled: clientAffinityEnabled + httpsOnly: httpsOnly + hostingEnvironmentProfile: !empty(appServiceEnvironmentResourceId) + ? { + id: appServiceEnvironmentResourceId + } + : null + storageAccountRequired: storageAccountRequired + keyVaultReferenceIdentity: keyVaultAccessIdentityResourceId + virtualNetworkSubnetId: virtualNetworkSubnetId + siteConfig: siteConfig + functionAppConfig: functionAppConfig + clientCertEnabled: clientCertEnabled + clientCertExclusionPaths: clientCertExclusionPaths + clientCertMode: clientCertMode + cloningInfo: cloningInfo + containerSize: containerSize + dailyMemoryTimeQuota: dailyMemoryTimeQuota + enabled: enabled + hostNameSslStates: hostNameSslStates + hyperV: hyperV + redundancyMode: redundancyMode + publicNetworkAccess: !empty(publicNetworkAccess) + ? any(publicNetworkAccess) + : (!empty(privateEndpoints) ? 'Disabled' : 'Enabled') + vnetContentShareEnabled: vnetContentShareEnabled + vnetImagePullEnabled: vnetImagePullEnabled + vnetRouteAllEnabled: vnetRouteAllEnabled + scmSiteAlsoStopped: scmSiteAlsoStopped + endToEndEncryptionEnabled: e2eEncryptionEnabled + dnsConfiguration: dnsConfiguration + autoGeneratedDomainNameLabelScope: autoGeneratedDomainNameLabelScope + } +} + +module app_config 'web-sites.config.bicep' = [ + for (config, index) in (configs ?? []): { + name: '${uniqueString(deployment().name, location)}-Site-Config-${index}' + params: { + appName: app.name + name: config.name + applicationInsightResourceId: config.?applicationInsightResourceId + storageAccountResourceId: config.?storageAccountResourceId + storageAccountUseIdentityAuthentication: config.?storageAccountUseIdentityAuthentication + properties: config.?properties + currentAppSettings: config.?retainCurrentAppSettings ?? true && config.name == 'appsettings' + ? list('${app.id}/config/appsettings', '2023-12-01').properties + : {} + } + } +] + +#disable-next-line use-recent-api-versions +resource app_diagnosticSettings 'Microsoft.Insights/diagnosticSettings@2021-05-01-preview' = [ + for (diagnosticSetting, index) in (diagnosticSettings ?? []): { + name: diagnosticSetting.?name ?? '${name}-diagnosticSettings' + properties: { + storageAccountId: diagnosticSetting.?storageAccountResourceId + workspaceId: diagnosticSetting.?workspaceResourceId + eventHubAuthorizationRuleId: diagnosticSetting.?eventHubAuthorizationRuleResourceId + eventHubName: diagnosticSetting.?eventHubName + metrics: [ + for group in (diagnosticSetting.?metricCategories ?? [{ category: 'AllMetrics' }]): { + category: group.category + enabled: group.?enabled ?? true + timeGrain: null + } + ] + logs: [ + for group in (diagnosticSetting.?logCategoriesAndGroups ?? [{ categoryGroup: 'allLogs' }]): { + categoryGroup: group.?categoryGroup + category: group.?category + enabled: group.?enabled ?? true + } + ] + marketplacePartnerId: diagnosticSetting.?marketplacePartnerResourceId + logAnalyticsDestinationType: diagnosticSetting.?logAnalyticsDestinationType + } + scope: app + } +] + +module app_privateEndpoints 'br/public:avm/res/network/private-endpoint:0.11.0' = [ + for (privateEndpoint, index) in (privateEndpoints ?? []): { + name: '${uniqueString(deployment().name, location)}-app-PrivateEndpoint-${index}' + scope: resourceGroup( + split(privateEndpoint.?resourceGroupResourceId ?? resourceGroup().id, '/')[2], + split(privateEndpoint.?resourceGroupResourceId ?? resourceGroup().id, '/')[4] + ) + params: { + name: privateEndpoint.?name ?? 'pep-${last(split(app.id, '/'))}-${privateEndpoint.?service ?? 'sites'}-${index}' + privateLinkServiceConnections: privateEndpoint.?isManualConnection != true + ? [ + { + name: privateEndpoint.?privateLinkServiceConnectionName ?? '${last(split(app.id, '/'))}-${privateEndpoint.?service ?? 'sites'}-${index}' + properties: { + privateLinkServiceId: app.id + groupIds: [ + privateEndpoint.?service ?? 'sites' + ] + } + } + ] + : null + manualPrivateLinkServiceConnections: privateEndpoint.?isManualConnection == true + ? [ + { + name: privateEndpoint.?privateLinkServiceConnectionName ?? '${last(split(app.id, '/'))}-${privateEndpoint.?service ?? 'sites'}-${index}' + properties: { + privateLinkServiceId: app.id + groupIds: [ + privateEndpoint.?service ?? 'sites' + ] + requestMessage: privateEndpoint.?manualConnectionRequestMessage ?? 'Manual approval required.' + } + } + ] + : null + subnetResourceId: privateEndpoint.subnetResourceId + enableTelemetry: false //As per https://azure.github.io/Azure-Verified-Modules/spec/BCPFR7/ + location: privateEndpoint.?location ?? reference( + split(privateEndpoint.subnetResourceId, '/subnets/')[0], + '2020-06-01', + 'Full' + ).location + lock: privateEndpoint.?lock ?? null + privateDnsZoneGroup: privateEndpoint.?privateDnsZoneGroup + roleAssignments: privateEndpoint.?roleAssignments + tags: privateEndpoint.?tags ?? tags + customDnsConfigs: privateEndpoint.?customDnsConfigs + ipConfigurations: privateEndpoint.?ipConfigurations + applicationSecurityGroupResourceIds: privateEndpoint.?applicationSecurityGroupResourceIds + customNetworkInterfaceName: privateEndpoint.?customNetworkInterfaceName + } + } +] + +@description('The name of the site.') +output name string = app.name + +@description('The resource ID of the site.') +output resourceId string = app.id + +@description('The resource group the site was deployed into.') +output resourceGroupName string = resourceGroup().name + +@description('The principal ID of the system assigned identity.') +output systemAssignedMIPrincipalId string? = app.?identity.?principalId + +@description('The location the resource was deployed into.') +output location string = app.location + +@description('Default hostname of the app.') +output defaultHostname string = app.properties.defaultHostName + +@description('Unique identifier that verifies the custom domains assigned to the app. Customer will add this ID to a txt record for verification.') +output customDomainVerificationId string = app.properties.customDomainVerificationId + +@description('The outbound IP addresses of the app.') +output outboundIpAddresses string = app.properties.outboundIpAddresses + +// ================ // +// Definitions // +// ================ // +@export() +@description('The type of an app settings configuration.') +type appSettingsConfigType = { + @description('Required. The type of config.') + name: 'appsettings' + + @description('Optional. If the provided storage account requires Identity based authentication (\'allowSharedKeyAccess\' is set to false). When set to true, the minimum role assignment required for the App Service Managed Identity to the storage account is \'Storage Blob Data Owner\'.') + storageAccountUseIdentityAuthentication: bool? + + @description('Optional. Required if app of kind functionapp. Resource ID of the storage account to manage triggers and logging function executions.') + storageAccountResourceId: string? + + @description('Optional. Resource ID of the application insight to leverage for this resource.') + applicationInsightResourceId: string? + + @description('Optional. The retain the current app settings. Defaults to true.') + retainCurrentAppSettings: bool? + + @description('Optional. The app settings key-value pairs except for AzureWebJobsStorage, AzureWebJobsDashboard, APPINSIGHTS_INSTRUMENTATIONKEY and APPLICATIONINSIGHTS_CONNECTION_STRING.') + properties: { + @description('Required. An app settings key-value pair.') + *: string + }? +} diff --git a/infra/modules/web-sites.config.bicep b/infra/modules/web-sites.config.bicep new file mode 100644 index 000000000..130a9806b --- /dev/null +++ b/infra/modules/web-sites.config.bicep @@ -0,0 +1,91 @@ +metadata name = 'Site App Settings' +metadata description = 'This module deploys a Site App Setting.' + +@description('Conditional. The name of the parent site resource. Required if the template is used in a standalone deployment.') +param appName string + +@description('Required. The name of the config.') +@allowed([ + 'appsettings' + 'authsettings' + 'authsettingsV2' + 'azurestorageaccounts' + 'backup' + 'connectionstrings' + 'logs' + 'metadata' + 'pushsettings' + 'slotConfigNames' + 'web' +]) +param name string + +@description('Optional. The properties of the config. Note: This parameter is highly dependent on the config type, defined by its name.') +param properties object = {} + +// Parameters only relevant for the config type 'appsettings' +@description('Optional. If the provided storage account requires Identity based authentication (\'allowSharedKeyAccess\' is set to false). When set to true, the minimum role assignment required for the App Service Managed Identity to the storage account is \'Storage Blob Data Owner\'.') +param storageAccountUseIdentityAuthentication bool = false + +@description('Optional. Required if app of kind functionapp. Resource ID of the storage account to manage triggers and logging function executions.') +param storageAccountResourceId string? + +@description('Optional. Resource ID of the application insight to leverage for this resource.') +param applicationInsightResourceId string? + +@description('Optional. The current app settings.') +param currentAppSettings { + @description('Required. The key-values pairs of the current app settings.') + *: string +} = {} + +var azureWebJobsValues = !empty(storageAccountResourceId) && !storageAccountUseIdentityAuthentication + ? { + AzureWebJobsStorage: 'DefaultEndpointsProtocol=https;AccountName=${storageAccount.name};AccountKey=${storageAccount!.listKeys().keys[0].value};EndpointSuffix=${environment().suffixes.storage}' + } + : !empty(storageAccountResourceId) && storageAccountUseIdentityAuthentication + ? { + AzureWebJobsStorage__accountName: storageAccount.name + AzureWebJobsStorage__blobServiceUri: storageAccount!.properties.primaryEndpoints.blob + AzureWebJobsStorage__queueServiceUri: storageAccount!.properties.primaryEndpoints.queue + AzureWebJobsStorage__tableServiceUri: storageAccount!.properties.primaryEndpoints.table + } + : {} + +var appInsightsValues = !empty(applicationInsightResourceId) + ? { + APPLICATIONINSIGHTS_CONNECTION_STRING: applicationInsights!.properties.ConnectionString + } + : {} + +var expandedProperties = union(currentAppSettings, properties, azureWebJobsValues, appInsightsValues) + +resource applicationInsights 'Microsoft.Insights/components@2020-02-02' existing = if (!empty(applicationInsightResourceId)) { + name: last(split(applicationInsightResourceId!, '/')) + scope: resourceGroup(split(applicationInsightResourceId!, '/')[2], split(applicationInsightResourceId!, '/')[4]) +} + +resource storageAccount 'Microsoft.Storage/storageAccounts@2024-01-01' existing = if (!empty(storageAccountResourceId)) { + name: last(split(storageAccountResourceId!, '/')) + scope: resourceGroup(split(storageAccountResourceId!, '/')[2], split(storageAccountResourceId!, '/')[4]) +} + +resource app 'Microsoft.Web/sites@2023-12-01' existing = { + name: appName +} + +resource config 'Microsoft.Web/sites/config@2024-04-01' = { + parent: app + #disable-next-line BCP225 + name: name + properties: expandedProperties +} + +@description('The name of the site config.') +output name string = config.name + +@description('The resource ID of the site config.') +output resourceId string = config.id + +@description('The resource group the site config was deployed into.') +output resourceGroupName string = resourceGroup().name diff --git a/infra/old/deploy_ai_foundry.bicep b/infra/old/00-older/deploy_ai_foundry.bicep similarity index 100% rename from infra/old/deploy_ai_foundry.bicep rename to infra/old/00-older/deploy_ai_foundry.bicep diff --git a/infra/old/deploy_keyvault.bicep b/infra/old/00-older/deploy_keyvault.bicep similarity index 100% rename from infra/old/deploy_keyvault.bicep rename to infra/old/00-older/deploy_keyvault.bicep diff --git a/infra/old/deploy_managed_identity.bicep b/infra/old/00-older/deploy_managed_identity.bicep similarity index 100% rename from infra/old/deploy_managed_identity.bicep rename to infra/old/00-older/deploy_managed_identity.bicep diff --git a/infra/old/macae-continer-oc.json b/infra/old/00-older/macae-continer-oc.json similarity index 100% rename from infra/old/macae-continer-oc.json rename to infra/old/00-older/macae-continer-oc.json diff --git a/infra/old/macae-continer.json b/infra/old/00-older/macae-continer.json similarity index 100% rename from infra/old/macae-continer.json rename to infra/old/00-older/macae-continer.json diff --git a/infra/old/macae-dev.bicep b/infra/old/00-older/macae-dev.bicep similarity index 100% rename from infra/old/macae-dev.bicep rename to infra/old/00-older/macae-dev.bicep diff --git a/infra/old/macae-large.bicepparam b/infra/old/00-older/macae-large.bicepparam similarity index 100% rename from infra/old/macae-large.bicepparam rename to infra/old/00-older/macae-large.bicepparam diff --git a/infra/old/macae-mini.bicepparam b/infra/old/00-older/macae-mini.bicepparam similarity index 100% rename from infra/old/macae-mini.bicepparam rename to infra/old/00-older/macae-mini.bicepparam diff --git a/infra/old/macae.bicep b/infra/old/00-older/macae.bicep similarity index 100% rename from infra/old/macae.bicep rename to infra/old/00-older/macae.bicep diff --git a/infra/old/main.bicep b/infra/old/00-older/main.bicep similarity index 100% rename from infra/old/main.bicep rename to infra/old/00-older/main.bicep diff --git a/infra/old/main2.bicep b/infra/old/00-older/main2.bicep similarity index 100% rename from infra/old/main2.bicep rename to infra/old/00-older/main2.bicep diff --git a/infra/old/resources.bicep b/infra/old/00-older/resources.bicep similarity index 100% rename from infra/old/resources.bicep rename to infra/old/00-older/resources.bicep diff --git a/infra/abbreviations.json b/infra/old/08-2025/abbreviations.json similarity index 100% rename from infra/abbreviations.json rename to infra/old/08-2025/abbreviations.json diff --git a/infra/bicepconfig.json b/infra/old/08-2025/bicepconfig.json similarity index 100% rename from infra/bicepconfig.json rename to infra/old/08-2025/bicepconfig.json diff --git a/infra/old/08-2025/main.bicep b/infra/old/08-2025/main.bicep new file mode 100644 index 000000000..8ee54772d --- /dev/null +++ b/infra/old/08-2025/main.bicep @@ -0,0 +1,1720 @@ +metadata name = 'Multi-Agent Custom Automation Engine' +metadata description = 'This module contains the resources required to deploy the Multi-Agent Custom Automation Engine solution accelerator for both Sandbox environments and WAF aligned environments.' + +@description('Set to true if you want to deploy WAF-aligned infrastructure.') +param useWafAlignedArchitecture bool + +@description('Use this parameter to use an existing AI project resource ID') +param existingFoundryProjectResourceId string = '' + +@description('Required. Name of the environment to deploy the solution into.') +param environmentName string + +@description('Required. Location for all Resources except AI Foundry.') +param solutionLocation string = resourceGroup().location + +@description('Optional. Enable/Disable usage telemetry for module.') +param enableTelemetry bool = true + +param existingLogAnalyticsWorkspaceId string = '' + +// Restricting deployment to only supported Azure OpenAI regions validated with GPT-4o model +@metadata({ + azd : { + type: 'location' + usageName : [ + 'OpenAI.GlobalStandard.gpt-4o, 150' + ] + } +}) +@allowed(['australiaeast', 'eastus2', 'francecentral', 'japaneast', 'norwayeast', 'swedencentral', 'uksouth', 'westus']) +@description('Azure OpenAI Location') +param aiDeploymentsLocation string + +@minLength(1) +@description('Name of the GPT model to deploy:') +param gptModelName string = 'gpt-4o' + +param gptModelVersion string = '2024-08-06' + +@minLength(1) +@description('GPT model deployment type:') +param modelDeploymentType string = 'GlobalStandard' + +@description('Optional. AI model deployment token capacity.') +param gptModelCapacity int = 150 + +@description('Set the image tag for the container images used in the solution. Default is "latest".') +param imageTag string = 'latest' + +param solutionPrefix string = 'macae-${padLeft(take(toLower(uniqueString(subscription().id, environmentName, resourceGroup().location, resourceGroup().name)), 12), 12, '0')}' + +@description('Optional. The tags to apply to all deployed Azure resources.') +param tags object = { + app: solutionPrefix + location: solutionLocation +} + +@description('Optional. The configuration to apply for the Multi-Agent Custom Automation Engine Log Analytics Workspace resource.') +param logAnalyticsWorkspaceConfiguration logAnalyticsWorkspaceConfigurationType = { + enabled: true + name: 'log-${solutionPrefix}' + location: solutionLocation + sku: 'PerGB2018' + tags: tags + dataRetentionInDays: useWafAlignedArchitecture ? 365 : 30 + existingWorkspaceResourceId: existingLogAnalyticsWorkspaceId +} + +@description('Optional. The configuration to apply for the Multi-Agent Custom Automation Engine Application Insights resource.') +param applicationInsightsConfiguration applicationInsightsConfigurationType = { + enabled: true + name: 'appi-${solutionPrefix}' + location: solutionLocation + tags: tags + retentionInDays: useWafAlignedArchitecture ? 365 : 30 +} + +@description('Optional. The configuration to apply for the Multi-Agent Custom Automation Engine Managed Identity resource.') +param userAssignedManagedIdentityConfiguration userAssignedManagedIdentityType = { + enabled: true + name: 'id-${solutionPrefix}' + location: solutionLocation + tags: tags +} + +@description('Optional. The configuration to apply for the Multi-Agent Custom Automation Engine Network Security Group resource for the backend subnet.') +param networkSecurityGroupBackendConfiguration networkSecurityGroupConfigurationType = { + enabled: true + name: 'nsg-backend-${solutionPrefix}' + location: solutionLocation + tags: tags + securityRules: null //Default value set on module configuration +} + +@description('Optional. The configuration to apply for the Multi-Agent Custom Automation Engine Network Security Group resource for the containers subnet.') +param networkSecurityGroupContainersConfiguration networkSecurityGroupConfigurationType = { + enabled: true + name: 'nsg-containers-${solutionPrefix}' + location: solutionLocation + tags: tags + securityRules: null //Default value set on module configuration +} + +@description('Optional. The configuration to apply for the Multi-Agent Custom Automation Engine Network Security Group resource for the Bastion subnet.') +param networkSecurityGroupBastionConfiguration networkSecurityGroupConfigurationType = { + enabled: true + name: 'nsg-bastion-${solutionPrefix}' + location: solutionLocation + tags: tags + securityRules: null //Default value set on module configuration +} + +@description('Optional. The configuration to apply for the Multi-Agent Custom Automation Engine Network Security Group resource for the administration subnet.') +param networkSecurityGroupAdministrationConfiguration networkSecurityGroupConfigurationType = { + enabled: true + name: 'nsg-administration-${solutionPrefix}' + location: solutionLocation + tags: tags + securityRules: null //Default value set on module configuration +} + +@description('Optional. The configuration to apply for the Multi-Agent Custom Automation Engine virtual network resource.') +param virtualNetworkConfiguration virtualNetworkConfigurationType = { + enabled: useWafAlignedArchitecture ? true : false + name: 'vnet-${solutionPrefix}' + location: solutionLocation + tags: tags + addressPrefixes: null //Default value set on module configuration + subnets: null //Default value set on module configuration +} + +@description('Optional. The configuration to apply for the Multi-Agent Custom Automation Engine bastion resource.') +param bastionConfiguration bastionConfigurationType = { + enabled: true + name: 'bas-${solutionPrefix}' + location: solutionLocation + tags: tags + sku: 'Standard' + virtualNetworkResourceId: null //Default value set on module configuration + publicIpResourceName: 'pip-bas${solutionPrefix}' +} + +@description('Optional. Configuration for the Windows virtual machine.') +param virtualMachineConfiguration virtualMachineConfigurationType = { + enabled: true + name: 'vm${solutionPrefix}' + location: solutionLocation + tags: tags + adminUsername: 'adminuser' + adminPassword: useWafAlignedArchitecture? 'P@ssw0rd1234' : guid(solutionPrefix, subscription().subscriptionId) + vmSize: 'Standard_D2s_v3' + subnetResourceId: null //Default value set on module configuration +} + +@description('Optional. The configuration to apply for the AI Foundry AI Services resource.') +param aiFoundryAiServicesConfiguration aiServicesConfigurationType = { + enabled: true + name: 'aisa-${solutionPrefix}' + location: aiDeploymentsLocation + sku: 'S0' + deployments: null //Default value set on module configuration + subnetResourceId: null //Default value set on module configuration + modelCapacity: gptModelCapacity +} + +@description('Optional. The configuration to apply for the AI Foundry AI Project resource.') +param aiFoundryAiProjectConfiguration aiProjectConfigurationType = { + enabled: true + name: 'aifp-${solutionPrefix}' + location: aiDeploymentsLocation + sku: 'Basic' + tags: tags +} + +@description('Optional. The configuration to apply for the Cosmos DB Account resource.') +param cosmosDbAccountConfiguration cosmosDbAccountConfigurationType = { + enabled: true + name: 'cosmos-${solutionPrefix}' + location: solutionLocation + tags: tags + subnetResourceId: null //Default value set on module configuration + sqlDatabases: null //Default value set on module configuration +} + +@description('Optional. The configuration to apply for the Container App Environment resource.') +param containerAppEnvironmentConfiguration containerAppEnvironmentConfigurationType = { + enabled: true + name: 'cae-${solutionPrefix}' + location: solutionLocation + tags: tags + subnetResourceId: null //Default value set on module configuration +} + +@description('Optional. The configuration to apply for the Container App resource.') +param containerAppConfiguration containerAppConfigurationType = { + enabled: true + name: 'ca-${solutionPrefix}' + location: solutionLocation + tags: tags + environmentResourceId: null //Default value set on module configuration + concurrentRequests: '100' + containerCpu: '2.0' + containerMemory: '4.0Gi' + containerImageRegistryDomain: 'biabcontainerreg.azurecr.io' + containerImageName: 'macaebackend' + containerImageTag: imageTag + containerName: 'backend' + ingressTargetPort: 8000 + maxReplicas: 1 + minReplicas: 1 +} + +@description('Optional. The configuration to apply for the Web Server Farm resource.') +param webServerFarmConfiguration webServerFarmConfigurationType = { + enabled: true + name: 'asp-${solutionPrefix}' + location: solutionLocation + skuName: useWafAlignedArchitecture? 'P1v3' : 'B2' + skuCapacity: useWafAlignedArchitecture ? 3 : 1 + tags: tags +} + +@description('Optional. The configuration to apply for the Web Server Farm resource.') +param webSiteConfiguration webSiteConfigurationType = { + enabled: true + name: 'app-${solutionPrefix}' + location: solutionLocation + containerImageRegistryDomain: 'biabcontainerreg.azurecr.io' + containerImageName: 'macaefrontend' + containerImageTag: imageTag + containerName: 'backend' + tags: tags + environmentResourceId: null //Default value set on module configuration +} + +// ========== Resource Group Tag ========== // +resource resourceGroupTags 'Microsoft.Resources/tags@2021-04-01' = { + name: 'default' + properties: { + tags: { + ...tags + TemplateName: 'Macae' + } + } +} + +// ========== Log Analytics Workspace ========== // +// WAF best practices for Log Analytics: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/azure-log-analytics +// Log Analytics configuration defaults +var logAnalyticsWorkspaceEnabled = logAnalyticsWorkspaceConfiguration.?enabled ?? true +var logAnalyticsWorkspaceResourceName = logAnalyticsWorkspaceConfiguration.?name ?? 'log-${solutionPrefix}' +var existingWorkspaceResourceId = logAnalyticsWorkspaceConfiguration.?existingWorkspaceResourceId ?? '' +var useExistingWorkspace = existingWorkspaceResourceId != '' + +module logAnalyticsWorkspace 'br/public:avm/res/operational-insights/workspace:0.11.2' = if (logAnalyticsWorkspaceEnabled && !useExistingWorkspace) { + name: take('avm.res.operational-insights.workspace.${logAnalyticsWorkspaceResourceName}', 64) + params: { + name: logAnalyticsWorkspaceResourceName + tags: logAnalyticsWorkspaceConfiguration.?tags ?? tags + location: logAnalyticsWorkspaceConfiguration.?location ?? solutionLocation + enableTelemetry: enableTelemetry + skuName: logAnalyticsWorkspaceConfiguration.?sku ?? 'PerGB2018' + dataRetention: logAnalyticsWorkspaceConfiguration.?dataRetentionInDays ?? 365 + diagnosticSettings: [{ useThisWorkspace: true }] + } +} + +var logAnalyticsWorkspaceId = useExistingWorkspace ? existingWorkspaceResourceId : logAnalyticsWorkspace.outputs.resourceId + +// ========== Application Insights ========== // +// WAF best practices for Application Insights: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/application-insights +// Application Insights configuration defaults +var applicationInsightsEnabled = applicationInsightsConfiguration.?enabled ?? true +var applicationInsightsResourceName = applicationInsightsConfiguration.?name ?? 'appi-${solutionPrefix}' +module applicationInsights 'br/public:avm/res/insights/component:0.6.0' = if (applicationInsightsEnabled) { + name: take('avm.res.insights.component.${applicationInsightsResourceName}', 64) + params: { + name: applicationInsightsResourceName + workspaceResourceId: logAnalyticsWorkspaceId + location: applicationInsightsConfiguration.?location ?? solutionLocation + enableTelemetry: enableTelemetry + tags: applicationInsightsConfiguration.?tags ?? tags + retentionInDays: applicationInsightsConfiguration.?retentionInDays ?? 365 + diagnosticSettings: [{ workspaceResourceId: logAnalyticsWorkspaceId }] + kind: 'web' + disableIpMasking: false + flowType: 'Bluefield' + } +} + +// ========== User assigned identity Web Site ========== // +// WAF best practices for identity and access management: https://learn.microsoft.com/en-us/azure/well-architected/security/identity-access +var userAssignedManagedIdentityEnabled = userAssignedManagedIdentityConfiguration.?enabled ?? true +var userAssignedManagedIdentityResourceName = userAssignedManagedIdentityConfiguration.?name ?? 'id-${solutionPrefix}' +module userAssignedIdentity 'br/public:avm/res/managed-identity/user-assigned-identity:0.4.1' = if (userAssignedManagedIdentityEnabled) { + name: take('avm.res.managed-identity.user-assigned-identity.${userAssignedManagedIdentityResourceName}', 64) + params: { + name: userAssignedManagedIdentityResourceName + tags: userAssignedManagedIdentityConfiguration.?tags ?? tags + location: userAssignedManagedIdentityConfiguration.?location ?? solutionLocation + enableTelemetry: enableTelemetry + } +} + +// ========== Network Security Groups ========== // +// WAF best practices for virtual networks: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/virtual-network +// WAF recommendations for networking and connectivity: https://learn.microsoft.com/en-us/azure/well-architected/security/networking +var networkSecurityGroupBackendEnabled = networkSecurityGroupBackendConfiguration.?enabled ?? true +var networkSecurityGroupBackendResourceName = networkSecurityGroupBackendConfiguration.?name ?? 'nsg-backend-${solutionPrefix}' +module networkSecurityGroupBackend 'br/public:avm/res/network/network-security-group:0.5.1' = if (virtualNetworkEnabled && networkSecurityGroupBackendEnabled) { + name: take('avm.res.network.network-security-group.${networkSecurityGroupBackendResourceName}', 64) + params: { + name: networkSecurityGroupBackendResourceName + location: networkSecurityGroupBackendConfiguration.?location ?? solutionLocation + tags: networkSecurityGroupBackendConfiguration.?tags ?? tags + enableTelemetry: enableTelemetry + diagnosticSettings: [{ workspaceResourceId: logAnalyticsWorkspaceId }] + securityRules: networkSecurityGroupBackendConfiguration.?securityRules ?? [ + // { + // name: 'DenySshRdpOutbound' //Azure Bastion + // properties: { + // priority: 200 + // access: 'Deny' + // protocol: '*' + // direction: 'Outbound' + // sourceAddressPrefix: 'VirtualNetwork' + // sourcePortRange: '*' + // destinationAddressPrefix: '*' + // destinationPortRanges: [ + // '3389' + // '22' + // ] + // } + // } + ] + } +} + +var networkSecurityGroupContainersEnabled = networkSecurityGroupContainersConfiguration.?enabled ?? true +var networkSecurityGroupContainersResourceName = networkSecurityGroupContainersConfiguration.?name ?? 'nsg-containers-${solutionPrefix}' +module networkSecurityGroupContainers 'br/public:avm/res/network/network-security-group:0.5.1' = if (virtualNetworkEnabled && networkSecurityGroupContainersEnabled) { + name: take('avm.res.network.network-security-group.${networkSecurityGroupContainersResourceName}', 64) + params: { + name: networkSecurityGroupContainersResourceName + location: networkSecurityGroupContainersConfiguration.?location ?? solutionLocation + tags: networkSecurityGroupContainersConfiguration.?tags ?? tags + enableTelemetry: enableTelemetry + diagnosticSettings: [{ workspaceResourceId: logAnalyticsWorkspaceId }] + securityRules: networkSecurityGroupContainersConfiguration.?securityRules ?? [ + // { + // name: 'DenySshRdpOutbound' //Azure Bastion + // properties: { + // priority: 200 + // access: 'Deny' + // protocol: '*' + // direction: 'Outbound' + // sourceAddressPrefix: 'VirtualNetwork' + // sourcePortRange: '*' + // destinationAddressPrefix: '*' + // destinationPortRanges: [ + // '3389' + // '22' + // ] + // } + // } + ] + } +} + +var networkSecurityGroupBastionEnabled = networkSecurityGroupBastionConfiguration.?enabled ?? true +var networkSecurityGroupBastionResourceName = networkSecurityGroupBastionConfiguration.?name ?? 'nsg-bastion-${solutionPrefix}' +module networkSecurityGroupBastion 'br/public:avm/res/network/network-security-group:0.5.1' = if (virtualNetworkEnabled && networkSecurityGroupBastionEnabled) { + name: take('avm.res.network.network-security-group.${networkSecurityGroupBastionResourceName}', 64) + params: { + name: networkSecurityGroupBastionResourceName + location: networkSecurityGroupBastionConfiguration.?location ?? solutionLocation + tags: networkSecurityGroupBastionConfiguration.?tags ?? tags + enableTelemetry: enableTelemetry + diagnosticSettings: [{ workspaceResourceId: logAnalyticsWorkspaceId }] + securityRules: networkSecurityGroupBastionConfiguration.?securityRules ?? [ + { + name: 'AllowHttpsInBound' + properties: { + protocol: 'Tcp' + sourcePortRange: '*' + sourceAddressPrefix: 'Internet' + destinationPortRange: '443' + destinationAddressPrefix: '*' + access: 'Allow' + priority: 100 + direction: 'Inbound' + } + } + { + name: 'AllowGatewayManagerInBound' + properties: { + protocol: 'Tcp' + sourcePortRange: '*' + sourceAddressPrefix: 'GatewayManager' + destinationPortRange: '443' + destinationAddressPrefix: '*' + access: 'Allow' + priority: 110 + direction: 'Inbound' + } + } + { + name: 'AllowLoadBalancerInBound' + properties: { + protocol: 'Tcp' + sourcePortRange: '*' + sourceAddressPrefix: 'AzureLoadBalancer' + destinationPortRange: '443' + destinationAddressPrefix: '*' + access: 'Allow' + priority: 120 + direction: 'Inbound' + } + } + { + name: 'AllowBastionHostCommunicationInBound' + properties: { + protocol: '*' + sourcePortRange: '*' + sourceAddressPrefix: 'VirtualNetwork' + destinationPortRanges: [ + '8080' + '5701' + ] + destinationAddressPrefix: 'VirtualNetwork' + access: 'Allow' + priority: 130 + direction: 'Inbound' + } + } + { + name: 'DenyAllInBound' + properties: { + protocol: '*' + sourcePortRange: '*' + sourceAddressPrefix: '*' + destinationPortRange: '*' + destinationAddressPrefix: '*' + access: 'Deny' + priority: 1000 + direction: 'Inbound' + } + } + { + name: 'AllowSshRdpOutBound' + properties: { + protocol: 'Tcp' + sourcePortRange: '*' + sourceAddressPrefix: '*' + destinationPortRanges: [ + '22' + '3389' + ] + destinationAddressPrefix: 'VirtualNetwork' + access: 'Allow' + priority: 100 + direction: 'Outbound' + } + } + { + name: 'AllowAzureCloudCommunicationOutBound' + properties: { + protocol: 'Tcp' + sourcePortRange: '*' + sourceAddressPrefix: '*' + destinationPortRange: '443' + destinationAddressPrefix: 'AzureCloud' + access: 'Allow' + priority: 110 + direction: 'Outbound' + } + } + { + name: 'AllowBastionHostCommunicationOutBound' + properties: { + protocol: '*' + sourcePortRange: '*' + sourceAddressPrefix: 'VirtualNetwork' + destinationPortRanges: [ + '8080' + '5701' + ] + destinationAddressPrefix: 'VirtualNetwork' + access: 'Allow' + priority: 120 + direction: 'Outbound' + } + } + { + name: 'AllowGetSessionInformationOutBound' + properties: { + protocol: '*' + sourcePortRange: '*' + sourceAddressPrefix: '*' + destinationAddressPrefix: 'Internet' + destinationPortRanges: [ + '80' + '443' + ] + access: 'Allow' + priority: 130 + direction: 'Outbound' + } + } + { + name: 'DenyAllOutBound' + properties: { + protocol: '*' + sourcePortRange: '*' + destinationPortRange: '*' + sourceAddressPrefix: '*' + destinationAddressPrefix: '*' + access: 'Deny' + priority: 1000 + direction: 'Outbound' + } + } + ] + } +} + +var networkSecurityGroupAdministrationEnabled = networkSecurityGroupAdministrationConfiguration.?enabled ?? true +var networkSecurityGroupAdministrationResourceName = networkSecurityGroupAdministrationConfiguration.?name ?? 'nsg-administration-${solutionPrefix}' +module networkSecurityGroupAdministration 'br/public:avm/res/network/network-security-group:0.5.1' = if (virtualNetworkEnabled && networkSecurityGroupAdministrationEnabled) { + name: take('avm.res.network.network-security-group.${networkSecurityGroupAdministrationResourceName}', 64) + params: { + name: networkSecurityGroupAdministrationResourceName + location: networkSecurityGroupAdministrationConfiguration.?location ?? solutionLocation + tags: networkSecurityGroupAdministrationConfiguration.?tags ?? tags + enableTelemetry: enableTelemetry + diagnosticSettings: [{ workspaceResourceId: logAnalyticsWorkspaceId }] + securityRules: networkSecurityGroupAdministrationConfiguration.?securityRules ?? [ + // { + // name: 'DenySshRdpOutbound' //Azure Bastion + // properties: { + // priority: 200 + // access: 'Deny' + // protocol: '*' + // direction: 'Outbound' + // sourceAddressPrefix: 'VirtualNetwork' + // sourcePortRange: '*' + // destinationAddressPrefix: '*' + // destinationPortRanges: [ + // '3389' + // '22' + // ] + // } + // } + ] + } +} + +// ========== Virtual Network ========== // +// WAF best practices for virtual networks: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/virtual-network +// WAF recommendations for networking and connectivity: https://learn.microsoft.com/en-us/azure/well-architected/security/networking +var virtualNetworkEnabled = virtualNetworkConfiguration.?enabled ?? true +var virtualNetworkResourceName = virtualNetworkConfiguration.?name ?? 'vnet-${solutionPrefix}' +module virtualNetwork 'br/public:avm/res/network/virtual-network:0.6.1' = if (virtualNetworkEnabled) { + name: take('avm.res.network.virtual-network.${virtualNetworkResourceName}', 64) + params: { + name: virtualNetworkResourceName + location: virtualNetworkConfiguration.?location ?? solutionLocation + tags: virtualNetworkConfiguration.?tags ?? tags + enableTelemetry: enableTelemetry + addressPrefixes: virtualNetworkConfiguration.?addressPrefixes ?? ['10.0.0.0/8'] + subnets: virtualNetworkConfiguration.?subnets ?? [ + { + name: 'backend' + addressPrefix: '10.0.0.0/27' + //defaultOutboundAccess: false TODO: check this configuration for a more restricted outbound access + networkSecurityGroupResourceId: networkSecurityGroupBackend.outputs.resourceId + } + { + name: 'administration' + addressPrefix: '10.0.0.32/27' + networkSecurityGroupResourceId: networkSecurityGroupAdministration.outputs.resourceId + } + { + // For Azure Bastion resources deployed on or after November 2, 2021, the minimum AzureBastionSubnet size is /26 or larger (/25, /24, etc.). + // https://learn.microsoft.com/en-us/azure/bastion/configuration-settings#subnet + name: 'AzureBastionSubnet' //This exact name is required for Azure Bastion + addressPrefix: '10.0.0.64/26' + networkSecurityGroupResourceId: networkSecurityGroupBastion.outputs.resourceId + } + { + // If you use your own vnw, you need to provide a subnet that is dedicated exclusively to the Container App environment you deploy. This subnet isn't available to other services + // https://learn.microsoft.com/en-us/azure/container-apps/networking?tabs=workload-profiles-env%2Cazure-cli#custom-vnw-configuration + name: 'containers' + addressPrefix: '10.0.2.0/23' //subnet of size /23 is required for container app + delegation: 'Microsoft.App/environments' + networkSecurityGroupResourceId: networkSecurityGroupContainers.outputs.resourceId + privateEndpointNetworkPolicies: 'Disabled' + privateLinkServiceNetworkPolicies: 'Enabled' + } + ] + } +} +var bastionEnabled = bastionConfiguration.?enabled ?? true +var bastionResourceName = bastionConfiguration.?name ?? 'bas-${solutionPrefix}' + +// ========== Bastion host ========== // +// WAF best practices for virtual networks: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/virtual-network +// WAF recommendations for networking and connectivity: https://learn.microsoft.com/en-us/azure/well-architected/security/networking +module bastionHost 'br/public:avm/res/network/bastion-host:0.6.1' = if (virtualNetworkEnabled && bastionEnabled) { + name: take('avm.res.network.bastion-host.${bastionResourceName}', 64) + params: { + name: bastionResourceName + location: bastionConfiguration.?location ?? solutionLocation + skuName: bastionConfiguration.?sku ?? 'Standard' + enableTelemetry: enableTelemetry + tags: bastionConfiguration.?tags ?? tags + virtualNetworkResourceId: bastionConfiguration.?virtualNetworkResourceId ?? virtualNetwork.?outputs.?resourceId + publicIPAddressObject: { + name: bastionConfiguration.?publicIpResourceName ?? 'pip-bas${solutionPrefix}' + zones: [] + } + disableCopyPaste: false + enableFileCopy: false + enableIpConnect: true + enableShareableLink: true + } +} + +// ========== Virtual machine ========== // +// WAF best practices for virtual machines: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/virtual-machines +var virtualMachineEnabled = virtualMachineConfiguration.?enabled ?? true +var virtualMachineResourceName = virtualMachineConfiguration.?name ?? 'vm${solutionPrefix}' +module virtualMachine 'br/public:avm/res/compute/virtual-machine:0.13.0' = if (virtualNetworkEnabled && virtualMachineEnabled) { + name: take('avm.res.compute.virtual-machine.${virtualMachineResourceName}', 64) + params: { + name: virtualMachineResourceName + computerName: take(virtualMachineResourceName, 15) + location: virtualMachineConfiguration.?location ?? solutionLocation + tags: virtualMachineConfiguration.?tags ?? tags + enableTelemetry: enableTelemetry + vmSize: virtualMachineConfiguration.?vmSize ?? 'Standard_D2s_v3' + adminUsername: virtualMachineConfiguration.?adminUsername ?? 'adminuser' + adminPassword: virtualMachineConfiguration.?adminPassword ?? guid(solutionPrefix, subscription().subscriptionId) + nicConfigurations: [ + { + name: 'nic-${virtualMachineResourceName}' + diagnosticSettings: [{ workspaceResourceId: logAnalyticsWorkspaceId }] + ipConfigurations: [ + { + name: '${virtualMachineResourceName}-nic01-ipconfig01' + subnetResourceId: virtualMachineConfiguration.?subnetResourceId ?? virtualNetwork.outputs.subnetResourceIds[1] + diagnosticSettings: [{ workspaceResourceId: logAnalyticsWorkspaceId }] + } + ] + } + ] + imageReference: { + publisher: 'microsoft-dsvm' + offer: 'dsvm-win-2022' + sku: 'winserver-2022' + version: 'latest' + } + osDisk: { + name: 'osdisk-${virtualMachineResourceName}' + createOption: 'FromImage' + managedDisk: { + storageAccountType: 'Standard_LRS' + } + diskSizeGB: 128 + caching: 'ReadWrite' + } + osType: 'Windows' + encryptionAtHost: false //The property 'securityProfile.encryptionAtHost' is not valid because the 'Microsoft.Compute/EncryptionAtHost' feature is not enabled for this subscription. + zone: 0 + extensionAadJoinConfig: { + enabled: true + typeHandlerVersion: '1.0' + } + } +} + +// ========== AI Foundry: AI Services ========== // +// WAF best practices for Open AI: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/azure-openai +var openAiSubResource = 'account' +var openAiPrivateDnsZones = { + 'privatelink.cognitiveservices.azure.com': openAiSubResource + 'privatelink.openai.azure.com': openAiSubResource + 'privatelink.services.ai.azure.com': openAiSubResource +} + +module privateDnsZonesAiServices 'br/public:avm/res/network/private-dns-zone:0.7.1' = [ + for zone in objectKeys(openAiPrivateDnsZones): if (virtualNetworkEnabled && aiFoundryAIservicesEnabled) { + name: take( + 'avm.res.network.private-dns-zone.ai-services.${uniqueString(aiFoundryAiServicesResourceName,zone)}.${solutionPrefix}', + 64 + ) + params: { + name: zone + tags: tags + enableTelemetry: enableTelemetry + virtualNetworkLinks: [ + { + name: 'vnetlink-${split(zone, '.')[1]}' + virtualNetworkResourceId: virtualNetwork.outputs.resourceId + } + ] + } + } +] + +// NOTE: Required version 'Microsoft.CognitiveServices/accounts@2024-04-01-preview' not available in AVM +var useExistingFoundryProject = !empty(existingFoundryProjectResourceId) +var existingAiFoundryName = useExistingFoundryProject?split( existingFoundryProjectResourceId,'/')[8]:'' +var aiFoundryAiServicesResourceName = useExistingFoundryProject? existingAiFoundryName : aiFoundryAiServicesConfiguration.?name ?? 'aisa-${solutionPrefix}' +var aiFoundryAIservicesEnabled = aiFoundryAiServicesConfiguration.?enabled ?? true +var aiFoundryAiServicesModelDeployment = { + format: 'OpenAI' + name: gptModelName + version: gptModelVersion + sku: { + name: modelDeploymentType + //Curently the capacity is set to 140 for opinanal performance. + capacity: aiFoundryAiServicesConfiguration.?modelCapacity ?? gptModelCapacity + } + raiPolicyName: 'Microsoft.Default' +} + +module aiFoundryAiServices 'modules/account/main.bicep' = if (aiFoundryAIservicesEnabled) { + name: take('avm.res.cognitive-services.account.${aiFoundryAiServicesResourceName}', 64) + params: { + name: aiFoundryAiServicesResourceName + tags: aiFoundryAiServicesConfiguration.?tags ?? tags + location: aiFoundryAiServicesConfiguration.?location ?? aiDeploymentsLocation + enableTelemetry: enableTelemetry + projectName: 'aifp-${solutionPrefix}' + projectDescription: 'aifp-${solutionPrefix}' + existingFoundryProjectResourceId: existingFoundryProjectResourceId + diagnosticSettings: [{ workspaceResourceId: logAnalyticsWorkspaceId }] + sku: aiFoundryAiServicesConfiguration.?sku ?? 'S0' + kind: 'AIServices' + disableLocalAuth: true //Should be set to true for WAF aligned configuration + customSubDomainName: aiFoundryAiServicesResourceName + apiProperties: { + //staticsEnabled: false + } + allowProjectManagement: true + managedIdentities: { + systemAssigned: true + } + publicNetworkAccess: virtualNetworkEnabled ? 'Disabled' : 'Enabled' + networkAcls: { + bypass: 'AzureServices' + defaultAction: (virtualNetworkEnabled) ? 'Deny' : 'Allow' + } + privateEndpoints: virtualNetworkEnabled && !useExistingFoundryProject + ? ([ + { + name: 'pep-${aiFoundryAiServicesResourceName}' + customNetworkInterfaceName: 'nic-${aiFoundryAiServicesResourceName}' + subnetResourceId: aiFoundryAiServicesConfiguration.?subnetResourceId ?? virtualNetwork.outputs.subnetResourceIds[0] + privateDnsZoneGroup: { + privateDnsZoneGroupConfigs: map(objectKeys(openAiPrivateDnsZones), zone => { + name: replace(zone, '.', '-') + privateDnsZoneResourceId: resourceId('Microsoft.Network/privateDnsZones', zone) + }) + } + } + ]) + : [] + deployments: aiFoundryAiServicesConfiguration.?deployments ?? [ + { + name: aiFoundryAiServicesModelDeployment.name + model: { + format: aiFoundryAiServicesModelDeployment.format + name: aiFoundryAiServicesModelDeployment.name + version: aiFoundryAiServicesModelDeployment.version + } + raiPolicyName: aiFoundryAiServicesModelDeployment.raiPolicyName + sku: { + name: aiFoundryAiServicesModelDeployment.sku.name + capacity: aiFoundryAiServicesModelDeployment.sku.capacity + } + } + ] + } +} + +// AI Foundry: AI Project +// WAF best practices for Open AI: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/azure-openai +var existingAiFounryProjectName = useExistingFoundryProject ? last(split( existingFoundryProjectResourceId,'/')) : '' +var aiFoundryAiProjectName = useExistingFoundryProject ? existingAiFounryProjectName : aiFoundryAiProjectConfiguration.?name ?? 'aifp-${solutionPrefix}' + +var useExistingResourceId = !empty(existingFoundryProjectResourceId) + +module cogServiceRoleAssignmentsNew './modules/role.bicep' = if(!useExistingResourceId) { + params: { + name: 'new-${guid(containerApp.name, aiFoundryAiServices.outputs.resourceId)}' + principalId: containerApp.outputs.?systemAssignedMIPrincipalId! + aiServiceName: aiFoundryAiServices.outputs.name + } + scope: resourceGroup(subscription().subscriptionId, resourceGroup().name) +} + +module cogServiceRoleAssignmentsExisting './modules/role.bicep' = if(useExistingResourceId) { + params: { + name: 'reuse-${guid(containerApp.name, aiFoundryAiServices.outputs.aiProjectInfo.resourceId)}' + principalId: containerApp.outputs.?systemAssignedMIPrincipalId! + aiServiceName: aiFoundryAiServices.outputs.name + } + scope: resourceGroup( split(existingFoundryProjectResourceId, '/')[2], split(existingFoundryProjectResourceId, '/')[4]) +} + +// ========== Cosmos DB ========== // +// WAF best practices for Cosmos DB: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/cosmos-db +module privateDnsZonesCosmosDb 'br/public:avm/res/network/private-dns-zone:0.7.0' = if (virtualNetworkEnabled) { + name: take('avm.res.network.private-dns-zone.cosmos-db.${solutionPrefix}', 64) + params: { + name: 'privatelink.documents.azure.com' + enableTelemetry: enableTelemetry + virtualNetworkLinks: [ + { + name: 'vnetlink-cosmosdb' + virtualNetworkResourceId: virtualNetwork.outputs.resourceId + } + ] + tags: tags + } +} + +var cosmosDbAccountEnabled = cosmosDbAccountConfiguration.?enabled ?? true +var cosmosDbResourceName = cosmosDbAccountConfiguration.?name ?? 'cosmos-${solutionPrefix}' +var cosmosDbDatabaseName = 'macae' +var cosmosDbDatabaseMemoryContainerName = 'memory' +module cosmosDb 'br/public:avm/res/document-db/database-account:0.12.0' = if (cosmosDbAccountEnabled) { + name: take('avm.res.document-db.database-account.${cosmosDbResourceName}', 64) + params: { + // Required parameters + name: cosmosDbAccountConfiguration.?name ?? 'cosmos-${solutionPrefix}' + location: cosmosDbAccountConfiguration.?location ?? solutionLocation + tags: cosmosDbAccountConfiguration.?tags ?? tags + enableTelemetry: enableTelemetry + diagnosticSettings: [{ workspaceResourceId: logAnalyticsWorkspaceId }] + databaseAccountOfferType: 'Standard' + enableFreeTier: false + networkRestrictions: { + networkAclBypass: 'None' + publicNetworkAccess: virtualNetworkEnabled ? 'Disabled' : 'Enabled' + } + privateEndpoints: virtualNetworkEnabled + ? [ + { + name: 'pep-${cosmosDbResourceName}' + customNetworkInterfaceName: 'nic-${cosmosDbResourceName}' + privateDnsZoneGroup: { + privateDnsZoneGroupConfigs: [{ privateDnsZoneResourceId: privateDnsZonesCosmosDb.outputs.resourceId }] + } + service: 'Sql' + subnetResourceId: cosmosDbAccountConfiguration.?subnetResourceId ?? virtualNetwork.outputs.subnetResourceIds[0] + } + ] + : [] + sqlDatabases: concat(cosmosDbAccountConfiguration.?sqlDatabases ?? [], [ + { + name: cosmosDbDatabaseName + containers: [ + { + name: cosmosDbDatabaseMemoryContainerName + paths: [ + '/session_id' + ] + kind: 'Hash' + version: 2 + } + ] + } + ]) + locations: [ + { + locationName: cosmosDbAccountConfiguration.?location ?? solutionLocation + failoverPriority: 0 + isZoneRedundant: false + } + ] + capabilitiesToAdd: [ + 'EnableServerless' + ] + sqlRoleAssignmentsPrincipalIds: [ + containerApp.outputs.?systemAssignedMIPrincipalId + ] + sqlRoleDefinitions: [ + { + // Replace this with built-in role definition Cosmos DB Built-in Data Contributor: https://docs.azure.cn/en-us/cosmos-db/nosql/security/reference-data-plane-roles#cosmos-db-built-in-data-contributor + roleType: 'CustomRole' + roleName: 'Cosmos DB SQL Data Contributor' + name: 'cosmos-db-sql-data-contributor' + dataAction: [ + 'Microsoft.DocumentDB/databaseAccounts/readMetadata' + 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/*' + 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers/items/*' + ] + } + ] + } +} + +// ========== Backend Container App Environment ========== // +// WAF best practices for container apps: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/azure-container-apps +var containerAppEnvironmentEnabled = containerAppEnvironmentConfiguration.?enabled ?? true +var containerAppEnvironmentResourceName = containerAppEnvironmentConfiguration.?name ?? 'cae-${solutionPrefix}' +module containerAppEnvironment 'modules/container-app-environment.bicep' = if (containerAppEnvironmentEnabled) { + name: take('module.container-app-environment.${containerAppEnvironmentResourceName}', 64) + params: { + name: containerAppEnvironmentResourceName + tags: containerAppEnvironmentConfiguration.?tags ?? tags + location: containerAppEnvironmentConfiguration.?location ?? solutionLocation + logAnalyticsResourceId: logAnalyticsWorkspaceId + publicNetworkAccess: 'Enabled' + zoneRedundant: false + applicationInsightsConnectionString: applicationInsights.outputs.connectionString + enableTelemetry: enableTelemetry + subnetResourceId: virtualNetworkEnabled + ? containerAppEnvironmentConfiguration.?subnetResourceId ?? virtualNetwork.?outputs.?subnetResourceIds[3] ?? '' + : '' + } +} + +// ========== Backend Container App Service ========== // +// WAF best practices for container apps: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/azure-container-apps +var containerAppEnabled = containerAppConfiguration.?enabled ?? true +var containerAppResourceName = containerAppConfiguration.?name ?? 'ca-${solutionPrefix}' +module containerApp 'br/public:avm/res/app/container-app:0.14.2' = if (containerAppEnabled) { + name: take('avm.res.app.container-app.${containerAppResourceName}', 64) + params: { + name: containerAppResourceName + tags: containerAppConfiguration.?tags ?? tags + location: containerAppConfiguration.?location ?? solutionLocation + enableTelemetry: enableTelemetry + environmentResourceId: containerAppConfiguration.?environmentResourceId ?? containerAppEnvironment.outputs.resourceId + managedIdentities: { + systemAssigned: true //Replace with user assigned identity + userAssignedResourceIds: [userAssignedIdentity.outputs.resourceId] + } + ingressTargetPort: containerAppConfiguration.?ingressTargetPort ?? 8000 + ingressExternal: true + activeRevisionsMode: 'Single' + corsPolicy: { + allowedOrigins: [ + 'https://${webSiteName}.azurewebsites.net' + 'http://${webSiteName}.azurewebsites.net' + ] + } + scaleSettings: { + //TODO: Make maxReplicas and minReplicas parameterized + maxReplicas: containerAppConfiguration.?maxReplicas ?? 1 + minReplicas: containerAppConfiguration.?minReplicas ?? 1 + rules: [ + { + name: 'http-scaler' + http: { + metadata: { + concurrentRequests: containerAppConfiguration.?concurrentRequests ?? '100' + } + } + } + ] + } + containers: [ + { + name: containerAppConfiguration.?containerName ?? 'backend' + image: '${containerAppConfiguration.?containerImageRegistryDomain ?? 'biabcontainerreg.azurecr.io'}/${containerAppConfiguration.?containerImageName ?? 'macaebackend'}:${containerAppConfiguration.?containerImageTag ?? 'latest'}' + resources: { + //TODO: Make cpu and memory parameterized + cpu: containerAppConfiguration.?containerCpu ?? '2.0' + memory: containerAppConfiguration.?containerMemory ?? '4.0Gi' + } + env: [ + { + name: 'COSMOSDB_ENDPOINT' + value: 'https://${cosmosDbResourceName}.documents.azure.com:443/' + } + { + name: 'COSMOSDB_DATABASE' + value: cosmosDbDatabaseName + } + { + name: 'COSMOSDB_CONTAINER' + value: cosmosDbDatabaseMemoryContainerName + } + { + name: 'AZURE_OPENAI_ENDPOINT' + value: 'https://${aiFoundryAiServicesResourceName}.openai.azure.com/' + } + { + name: 'AZURE_OPENAI_MODEL_NAME' + value: aiFoundryAiServicesModelDeployment.name + } + { + name: 'AZURE_OPENAI_DEPLOYMENT_NAME' + value: aiFoundryAiServicesModelDeployment.name + } + { + name: 'AZURE_OPENAI_API_VERSION' + value: '2025-01-01-preview' //TODO: set parameter/variable + } + { + name: 'APPLICATIONINSIGHTS_INSTRUMENTATION_KEY' + value: applicationInsights.outputs.instrumentationKey + } + { + name: 'APPLICATIONINSIGHTS_CONNECTION_STRING' + value: applicationInsights.outputs.connectionString + } + { + name: 'AZURE_AI_SUBSCRIPTION_ID' + value: subscription().subscriptionId + } + { + name: 'AZURE_AI_RESOURCE_GROUP' + value: resourceGroup().name + } + { + name: 'AZURE_AI_PROJECT_NAME' + value: aiFoundryAiProjectName + } + { + name: 'FRONTEND_SITE_NAME' + value: 'https://${webSiteName}.azurewebsites.net' + } + { + name: 'AZURE_AI_AGENT_ENDPOINT' + value: aiFoundryAiServices.outputs.aiProjectInfo.apiEndpoint + } + { + name: 'AZURE_AI_AGENT_MODEL_DEPLOYMENT_NAME' + value: aiFoundryAiServicesModelDeployment.name + } + { + name: 'APP_ENV' + value: 'Prod' + } + ] + } + ] + } +} + +var webServerFarmEnabled = webServerFarmConfiguration.?enabled ?? true +var webServerFarmResourceName = webServerFarmConfiguration.?name ?? 'asp-${solutionPrefix}' + +// ========== Frontend server farm ========== // +// WAF best practices for web app service: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/app-service-web-apps +module webServerFarm 'br/public:avm/res/web/serverfarm:0.4.1' = if (webServerFarmEnabled) { + name: take('avm.res.web.serverfarm.${webServerFarmResourceName}', 64) + params: { + name: webServerFarmResourceName + tags: tags + location: webServerFarmConfiguration.?location ?? solutionLocation + skuName: webServerFarmConfiguration.?skuName ?? 'P1v3' + skuCapacity: webServerFarmConfiguration.?skuCapacity ?? 3 + reserved: true + diagnosticSettings: [{ workspaceResourceId: logAnalyticsWorkspaceId }] + kind: 'linux' + zoneRedundant: false //TODO: make it zone redundant for waf aligned + } +} + +// ========== Frontend web site ========== // +// WAF best practices for web app service: https://learn.microsoft.com/en-us/azure/well-architected/service-guides/app-service-web-apps +var webSiteEnabled = webSiteConfiguration.?enabled ?? true + +var webSiteName = 'app-${solutionPrefix}' +module webSite 'br/public:avm/res/web/site:0.15.1' = if (webSiteEnabled) { + name: take('avm.res.web.site.${webSiteName}', 64) + params: { + name: webSiteName + tags: webSiteConfiguration.?tags ?? tags + location: webSiteConfiguration.?location ?? solutionLocation + kind: 'app,linux,container' + enableTelemetry: enableTelemetry + serverFarmResourceId: webSiteConfiguration.?environmentResourceId ?? webServerFarm.?outputs.resourceId + appInsightResourceId: applicationInsights.outputs.resourceId + diagnosticSettings: [{ workspaceResourceId: logAnalyticsWorkspaceId }] + publicNetworkAccess: 'Enabled' //TODO: use Azure Front Door WAF or Application Gateway WAF instead + siteConfig: { + linuxFxVersion: 'DOCKER|${webSiteConfiguration.?containerImageRegistryDomain ?? 'biabcontainerreg.azurecr.io'}/${webSiteConfiguration.?containerImageName ?? 'macaefrontend'}:${webSiteConfiguration.?containerImageTag ?? 'latest'}' + } + appSettingsKeyValuePairs: { + SCM_DO_BUILD_DURING_DEPLOYMENT: 'true' + DOCKER_REGISTRY_SERVER_URL: 'https://${webSiteConfiguration.?containerImageRegistryDomain ?? 'biabcontainerreg.azurecr.io'}' + WEBSITES_PORT: '3000' + WEBSITES_CONTAINER_START_TIME_LIMIT: '1800' // 30 minutes, adjust as needed + BACKEND_API_URL: 'https://${containerApp.outputs.fqdn}' + AUTH_ENABLED: 'false' + APP_ENV: 'Prod' + } + } +} + +// ============ // +// Outputs // +// ============ // + +// Add your outputs here + +@description('The default url of the website to connect to the Multi-Agent Custom Automation Engine solution.') +output webSiteDefaultHostname string = webSite.outputs.defaultHostname + +@export() +@description('The type for the Multi-Agent Custom Automation Engine Log Analytics Workspace resource configuration.') +type logAnalyticsWorkspaceConfigurationType = { + @description('Optional. If the Log Analytics Workspace resource should be deployed or not.') + enabled: bool? + + @description('Optional. The name of the Log Analytics Workspace resource.') + @maxLength(63) + name: string? + + @description('Optional. Location for the Log Analytics Workspace resource.') + @metadata({ azd: { type: 'location' } }) + location: string? + + @description('Optional. The tags to for the Log Analytics Workspace resource.') + tags: object? + + @description('Optional. The SKU for the Log Analytics Workspace resource.') + sku: ('CapacityReservation' | 'Free' | 'LACluster' | 'PerGB2018' | 'PerNode' | 'Premium' | 'Standalone' | 'Standard')? + + @description('Optional. The number of days to retain the data in the Log Analytics Workspace. If empty, it will be set to 365 days.') + @maxValue(730) + dataRetentionInDays: int? + + @description('Optional: Existing Log Analytics Workspace Resource ID') + existingWorkspaceResourceId: string? +} + +@export() +@description('The type for the Multi-Agent Custom Automation Engine Application Insights resource configuration.') +type applicationInsightsConfigurationType = { + @description('Optional. If the Application Insights resource should be deployed or not.') + enabled: bool? + + @description('Optional. The name of the Application Insights resource.') + @maxLength(90) + name: string? + + @description('Optional. Location for the Application Insights resource.') + @metadata({ azd: { type: 'location' } }) + location: string? + + @description('Optional. The tags to set for the Application Insights resource.') + tags: object? + + @description('Optional. The retention of Application Insights data in days. If empty, Standard will be used.') + retentionInDays: (120 | 180 | 270 | 30 | 365 | 550 | 60 | 730 | 90)? +} + +@export() +@description('The type for the Multi-Agent Custom Automation Engine Application User Assigned Managed Identity resource configuration.') +type userAssignedManagedIdentityType = { + @description('Optional. If the User Assigned Managed Identity resource should be deployed or not.') + enabled: bool? + + @description('Optional. The name of the User Assigned Managed Identity resource.') + @maxLength(128) + name: string? + + @description('Optional. Location for the User Assigned Managed Identity resource.') + @metadata({ azd: { type: 'location' } }) + location: string? + + @description('Optional. The tags to set for the User Assigned Managed Identity resource.') + tags: object? +} + +@export() +import { securityRuleType } from 'br/public:avm/res/network/network-security-group:0.5.1' +@description('The type for the Multi-Agent Custom Automation Engine Network Security Group resource configuration.') +type networkSecurityGroupConfigurationType = { + @description('Optional. If the Network Security Group resource should be deployed or not.') + enabled: bool? + + @description('Optional. The name of the Network Security Group resource.') + @maxLength(90) + name: string? + + @description('Optional. Location for the Network Security Group resource.') + @metadata({ azd: { type: 'location' } }) + location: string? + + @description('Optional. The tags to set for the Network Security Group resource.') + tags: object? + + @description('Optional. The security rules to set for the Network Security Group resource.') + securityRules: securityRuleType[]? +} + +@export() +@description('The type for the Multi-Agent Custom Automation virtual network resource configuration.') +type virtualNetworkConfigurationType = { + @description('Optional. If the Virtual Network resource should be deployed or not.') + enabled: bool? + + @description('Optional. The name of the Virtual Network resource.') + @maxLength(90) + name: string? + + @description('Optional. Location for the Virtual Network resource.') + @metadata({ azd: { type: 'location' } }) + location: string? + + @description('Optional. The tags to set for the Virtual Network resource.') + tags: object? + + @description('Optional. An array of 1 or more IP Addresses prefixes for the Virtual Network resource.') + addressPrefixes: string[]? + + @description('Optional. An array of 1 or more subnets for the Virtual Network resource.') + subnets: subnetType[]? +} + +import { roleAssignmentType } from 'br/public:avm/utl/types/avm-common-types:0.5.1' +type subnetType = { + @description('Optional. The Name of the subnet resource.') + name: string + + @description('Conditional. The address prefix for the subnet. Required if `addressPrefixes` is empty.') + addressPrefix: string? + + @description('Conditional. List of address prefixes for the subnet. Required if `addressPrefix` is empty.') + addressPrefixes: string[]? + + @description('Optional. Application gateway IP configurations of virtual network resource.') + applicationGatewayIPConfigurations: object[]? + + @description('Optional. The delegation to enable on the subnet.') + delegation: string? + + @description('Optional. The resource ID of the NAT Gateway to use for the subnet.') + natGatewayResourceId: string? + + @description('Optional. The resource ID of the network security group to assign to the subnet.') + networkSecurityGroupResourceId: string? + + @description('Optional. enable or disable apply network policies on private endpoint in the subnet.') + privateEndpointNetworkPolicies: ('Disabled' | 'Enabled' | 'NetworkSecurityGroupEnabled' | 'RouteTableEnabled')? + + @description('Optional. enable or disable apply network policies on private link service in the subnet.') + privateLinkServiceNetworkPolicies: ('Disabled' | 'Enabled')? + + @description('Optional. Array of role assignments to create.') + roleAssignments: roleAssignmentType[]? + + @description('Optional. The resource ID of the route table to assign to the subnet.') + routeTableResourceId: string? + + @description('Optional. An array of service endpoint policies.') + serviceEndpointPolicies: object[]? + + @description('Optional. The service endpoints to enable on the subnet.') + serviceEndpoints: string[]? + + @description('Optional. Set this property to false to disable default outbound connectivity for all VMs in the subnet. This property can only be set at the time of subnet creation and cannot be updated for an existing subnet.') + defaultOutboundAccess: bool? + + @description('Optional. Set this property to Tenant to allow sharing subnet with other subscriptions in your AAD tenant. This property can only be set if defaultOutboundAccess is set to false, both properties can only be set if subnet is empty.') + sharingScope: ('DelegatedServices' | 'Tenant')? +} + +@export() +@description('The type for the Multi-Agent Custom Automation Engine Bastion resource configuration.') +type bastionConfigurationType = { + @description('Optional. If the Bastion resource should be deployed or not.') + enabled: bool? + + @description('Optional. The name of the Bastion resource.') + @maxLength(90) + name: string? + + @description('Optional. Location for the Bastion resource.') + @metadata({ azd: { type: 'location' } }) + location: string? + + @description('Optional. The tags to set for the Bastion resource.') + tags: object? + + @description('Optional. The SKU for the Bastion resource.') + sku: ('Basic' | 'Developer' | 'Premium' | 'Standard')? + + @description('Optional. The Virtual Network resource id where the Bastion resource should be deployed.') + virtualNetworkResourceId: string? + + @description('Optional. The name of the Public Ip resource created to connect to Bastion.') + publicIpResourceName: string? +} + +@export() +@description('The type for the Multi-Agent Custom Automation Engine virtual machine resource configuration.') +type virtualMachineConfigurationType = { + @description('Optional. If the Virtual Machine resource should be deployed or not.') + enabled: bool? + + @description('Optional. The name of the Virtual Machine resource.') + @maxLength(90) + name: string? + + @description('Optional. Location for the Virtual Machine resource.') + @metadata({ azd: { type: 'location' } }) + location: string? + + @description('Optional. The tags to set for the Virtual Machine resource.') + tags: object? + + @description('Optional. Specifies the size for the Virtual Machine resource.') + vmSize: ( + | 'Basic_A0' + | 'Basic_A1' + | 'Basic_A2' + | 'Basic_A3' + | 'Basic_A4' + | 'Standard_A0' + | 'Standard_A1' + | 'Standard_A2' + | 'Standard_A3' + | 'Standard_A4' + | 'Standard_A5' + | 'Standard_A6' + | 'Standard_A7' + | 'Standard_A8' + | 'Standard_A9' + | 'Standard_A10' + | 'Standard_A11' + | 'Standard_A1_v2' + | 'Standard_A2_v2' + | 'Standard_A4_v2' + | 'Standard_A8_v2' + | 'Standard_A2m_v2' + | 'Standard_A4m_v2' + | 'Standard_A8m_v2' + | 'Standard_B1s' + | 'Standard_B1ms' + | 'Standard_B2s' + | 'Standard_B2ms' + | 'Standard_B4ms' + | 'Standard_B8ms' + | 'Standard_D1' + | 'Standard_D2' + | 'Standard_D3' + | 'Standard_D4' + | 'Standard_D11' + | 'Standard_D12' + | 'Standard_D13' + | 'Standard_D14' + | 'Standard_D1_v2' + | 'Standard_D2_v2' + | 'Standard_D3_v2' + | 'Standard_D4_v2' + | 'Standard_D5_v2' + | 'Standard_D2_v3' + | 'Standard_D4_v3' + | 'Standard_D8_v3' + | 'Standard_D16_v3' + | 'Standard_D32_v3' + | 'Standard_D64_v3' + | 'Standard_D2s_v3' + | 'Standard_D4s_v3' + | 'Standard_D8s_v3' + | 'Standard_D16s_v3' + | 'Standard_D32s_v3' + | 'Standard_D64s_v3' + | 'Standard_D11_v2' + | 'Standard_D12_v2' + | 'Standard_D13_v2' + | 'Standard_D14_v2' + | 'Standard_D15_v2' + | 'Standard_DS1' + | 'Standard_DS2' + | 'Standard_DS3' + | 'Standard_DS4' + | 'Standard_DS11' + | 'Standard_DS12' + | 'Standard_DS13' + | 'Standard_DS14' + | 'Standard_DS1_v2' + | 'Standard_DS2_v2' + | 'Standard_DS3_v2' + | 'Standard_DS4_v2' + | 'Standard_DS5_v2' + | 'Standard_DS11_v2' + | 'Standard_DS12_v2' + | 'Standard_DS13_v2' + | 'Standard_DS14_v2' + | 'Standard_DS15_v2' + | 'Standard_DS13-4_v2' + | 'Standard_DS13-2_v2' + | 'Standard_DS14-8_v2' + | 'Standard_DS14-4_v2' + | 'Standard_E2_v3' + | 'Standard_E4_v3' + | 'Standard_E8_v3' + | 'Standard_E16_v3' + | 'Standard_E32_v3' + | 'Standard_E64_v3' + | 'Standard_E2s_v3' + | 'Standard_E4s_v3' + | 'Standard_E8s_v3' + | 'Standard_E16s_v3' + | 'Standard_E32s_v3' + | 'Standard_E64s_v3' + | 'Standard_E32-16_v3' + | 'Standard_E32-8s_v3' + | 'Standard_E64-32s_v3' + | 'Standard_E64-16s_v3' + | 'Standard_F1' + | 'Standard_F2' + | 'Standard_F4' + | 'Standard_F8' + | 'Standard_F16' + | 'Standard_F1s' + | 'Standard_F2s' + | 'Standard_F4s' + | 'Standard_F8s' + | 'Standard_F16s' + | 'Standard_F2s_v2' + | 'Standard_F4s_v2' + | 'Standard_F8s_v2' + | 'Standard_F16s_v2' + | 'Standard_F32s_v2' + | 'Standard_F64s_v2' + | 'Standard_F72s_v2' + | 'Standard_G1' + | 'Standard_G2' + | 'Standard_G3' + | 'Standard_G4' + | 'Standard_G5' + | 'Standard_GS1' + | 'Standard_GS2' + | 'Standard_GS3' + | 'Standard_GS4' + | 'Standard_GS5' + | 'Standard_GS4-8' + | 'Standard_GS4-4' + | 'Standard_GS5-16' + | 'Standard_GS5-8' + | 'Standard_H8' + | 'Standard_H16' + | 'Standard_H8m' + | 'Standard_H16m' + | 'Standard_H16r' + | 'Standard_H16mr' + | 'Standard_L4s' + | 'Standard_L8s' + | 'Standard_L16s' + | 'Standard_L32s' + | 'Standard_M64s' + | 'Standard_M64ms' + | 'Standard_M128s' + | 'Standard_M128ms' + | 'Standard_M64-32ms' + | 'Standard_M64-16ms' + | 'Standard_M128-64ms' + | 'Standard_M128-32ms' + | 'Standard_NC6' + | 'Standard_NC12' + | 'Standard_NC24' + | 'Standard_NC24r' + | 'Standard_NC6s_v2' + | 'Standard_NC12s_v2' + | 'Standard_NC24s_v2' + | 'Standard_NC24rs_v2' + | 'Standard_NC6s_v3' + | 'Standard_NC12s_v3' + | 'Standard_NC24s_v3' + | 'Standard_NC24rs_v3' + | 'Standard_ND6s' + | 'Standard_ND12s' + | 'Standard_ND24s' + | 'Standard_ND24rs' + | 'Standard_NV6' + | 'Standard_NV12' + | 'Standard_NV24')? + + @description('Optional. The username for the administrator account on the virtual machine. Required if a virtual machine is created as part of the module.') + adminUsername: string? + + @description('Optional. The password for the administrator account on the virtual machine. Required if a virtual machine is created as part of the module.') + @secure() + adminPassword: string? + + @description('Optional. The resource ID of the subnet where the Virtual Machine resource should be deployed.') + subnetResourceId: string? +} + +@export() +import { deploymentType } from 'br/public:avm/res/cognitive-services/account:0.10.2' +@description('The type for the Multi-Agent Custom Automation Engine AI Services resource configuration.') +type aiServicesConfigurationType = { + @description('Optional. If the AI Services resource should be deployed or not.') + enabled: bool? + + @description('Optional. The name of the AI Services resource.') + @maxLength(90) + name: string? + + @description('Optional. Location for the AI Services resource.') + @metadata({ azd: { type: 'location' } }) + location: string? + + @description('Optional. The tags to set for the AI Services resource.') + tags: object? + + @description('Optional. The SKU of the AI Services resource. Use \'Get-AzCognitiveServicesAccountSku\' to determine a valid combinations of \'kind\' and \'SKU\' for your Azure region.') + sku: ( + | 'C2' + | 'C3' + | 'C4' + | 'F0' + | 'F1' + | 'S' + | 'S0' + | 'S1' + | 'S10' + | 'S2' + | 'S3' + | 'S4' + | 'S5' + | 'S6' + | 'S7' + | 'S8' + | 'S9')? + + @description('Optional. The resource Id of the subnet where the AI Services private endpoint should be created.') + subnetResourceId: string? + + @description('Optional. The model deployments to set for the AI Services resource.') + deployments: deploymentType[]? + + @description('Optional. The capacity to set for AI Services GTP model.') + modelCapacity: int? +} + +@export() +@description('The type for the Multi-Agent Custom Automation Engine AI Foundry AI Project resource configuration.') +type aiProjectConfigurationType = { + @description('Optional. If the AI Project resource should be deployed or not.') + enabled: bool? + + @description('Optional. The name of the AI Project resource.') + @maxLength(90) + name: string? + + @description('Optional. Location for the AI Project resource deployment.') + @metadata({ azd: { type: 'location' } }) + location: string? + + @description('Optional. The SKU of the AI Project resource.') + sku: ('Basic' | 'Free' | 'Standard' | 'Premium')? + + @description('Optional. The tags to set for the AI Project resource.') + tags: object? +} + +import { sqlDatabaseType } from 'br/public:avm/res/document-db/database-account:0.13.0' +@export() +@description('The type for the Multi-Agent Custom Automation Engine Cosmos DB Account resource configuration.') +type cosmosDbAccountConfigurationType = { + @description('Optional. If the Cosmos DB Account resource should be deployed or not.') + enabled: bool? + @description('Optional. The name of the Cosmos DB Account resource.') + @maxLength(60) + name: string? + + @description('Optional. Location for the Cosmos DB Account resource.') + @metadata({ azd: { type: 'location' } }) + location: string? + + @description('Optional. The tags to set for the Cosmos DB Account resource.') + tags: object? + + @description('Optional. The resource Id of the subnet where the Cosmos DB Account private endpoint should be created.') + subnetResourceId: string? + + @description('Optional. The SQL databases configuration for the Cosmos DB Account resource.') + sqlDatabases: sqlDatabaseType[]? +} + +@export() +@description('The type for the Multi-Agent Custom Automation Engine Container App Environment resource configuration.') +type containerAppEnvironmentConfigurationType = { + @description('Optional. If the Container App Environment resource should be deployed or not.') + enabled: bool? + + @description('Optional. The name of the Container App Environment resource.') + @maxLength(60) + name: string? + + @description('Optional. Location for the Container App Environment resource.') + @metadata({ azd: { type: 'location' } }) + location: string? + + @description('Optional. The tags to set for the Container App Environment resource.') + tags: object? + + @description('Optional. The resource Id of the subnet where the Container App Environment private endpoint should be created.') + subnetResourceId: string? +} + +@export() +@description('The type for the Multi-Agent Custom Automation Engine Container App resource configuration.') +type containerAppConfigurationType = { + @description('Optional. If the Container App resource should be deployed or not.') + enabled: bool? + + @description('Optional. The name of the Container App resource.') + @maxLength(60) + name: string? + + @description('Optional. Location for the Container App resource.') + @metadata({ azd: { type: 'location' } }) + location: string? + + @description('Optional. The tags to set for the Container App resource.') + tags: object? + + @description('Optional. The resource Id of the Container App Environment where the Container App should be created.') + environmentResourceId: string? + + @description('Optional. The maximum number of replicas of the Container App.') + maxReplicas: int? + + @description('Optional. The minimum number of replicas of the Container App.') + minReplicas: int? + + @description('Optional. The ingress target port of the Container App.') + ingressTargetPort: int? + + @description('Optional. The concurrent requests allowed for the Container App.') + concurrentRequests: string? + + @description('Optional. The name given to the Container App.') + containerName: string? + + @description('Optional. The container registry domain of the container image to be used by the Container App. Default to `biabcontainerreg.azurecr.io`') + containerImageRegistryDomain: string? + + @description('Optional. The name of the container image to be used by the Container App.') + containerImageName: string? + + @description('Optional. The tag of the container image to be used by the Container App.') + containerImageTag: string? + + @description('Optional. The CPU reserved for the Container App. Defaults to 2.0') + containerCpu: string? + + @description('Optional. The Memory reserved for the Container App. Defaults to 4.0Gi') + containerMemory: string? +} + +@export() +@description('The type for the Multi-Agent Custom Automation Engine Entra ID Application resource configuration.') +type entraIdApplicationConfigurationType = { + @description('Optional. If the Entra ID Application for website authentication should be deployed or not.') + enabled: bool? +} + +@export() +@description('The type for the Multi-Agent Custom Automation Engine Web Server Farm resource configuration.') +type webServerFarmConfigurationType = { + @description('Optional. If the Web Server Farm resource should be deployed or not.') + enabled: bool? + + @description('Optional. The name of the Web Server Farm resource.') + @maxLength(60) + name: string? + + @description('Optional. Location for the Web Server Farm resource.') + @metadata({ azd: { type: 'location' } }) + location: string? + + @description('Optional. The tags to set for the Web Server Farm resource.') + tags: object? + + @description('Optional. The name of th SKU that will determine the tier, size and family for the Web Server Farm resource. This defaults to P1v3 to leverage availability zones.') + skuName: string? + + @description('Optional. Number of workers associated with the App Service Plan. This defaults to 3, to leverage availability zones.') + skuCapacity: int? +} + +@export() +@description('The type for the Multi-Agent Custom Automation Engine Web Site resource configuration.') +type webSiteConfigurationType = { + @description('Optional. If the Web Site resource should be deployed or not.') + enabled: bool? + + @description('Optional. The name of the Web Site resource.') + @maxLength(60) + name: string? + + @description('Optional. Location for the Web Site resource deployment.') + @metadata({ azd: { type: 'location' } }) + location: string? + + @description('Optional. The tags to set for the Web Site resource.') + tags: object? + + @description('Optional. The resource Id of the Web Site Environment where the Web Site should be created.') + environmentResourceId: string? + + @description('Optional. The name given to the Container App.') + containerName: string? + + @description('Optional. The container registry domain of the container image to be used by the Web Site. Default to `biabcontainerreg.azurecr.io`') + containerImageRegistryDomain: string? + + @description('Optional. The name of the container image to be used by the Web Site.') + containerImageName: string? + + @description('Optional. The tag of the container image to be used by the Web Site.') + containerImageTag: string? +} diff --git a/infra/old/08-2025/main.parameters.json b/infra/old/08-2025/main.parameters.json new file mode 100644 index 000000000..16b465617 --- /dev/null +++ b/infra/old/08-2025/main.parameters.json @@ -0,0 +1,102 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "aiModelDeployments": { + "value": [ + { + "name": "gpt", + "model": { + "name": "gpt-4o", + "version": "2024-08-06", + "format": "OpenAI" + }, + "sku": { + "name": "GlobalStandard", + "capacity": 140 + } + } + ] + }, + "environmentName": { + "value": "${AZURE_ENV_NAME}" + }, + "solutionLocation": { + "value": "${AZURE_LOCATION}" + }, + "aiDeploymentsLocation": { + "value": "${AZURE_ENV_OPENAI_LOCATION}" + }, + "modelDeploymentType": { + "value": "${AZURE_ENV_MODEL_DEPLOYMENT_TYPE}" + }, + "gptModelName": { + "value": "${AZURE_ENV_MODEL_NAME}" + }, + "gptModelVersion": { + "value": "${AZURE_ENV_MODEL_VERSION}" + }, + "gptModelCapacity": { + "value": "${AZURE_ENV_MODEL_CAPACITY}" + }, + "existingFoundryProjectResourceId": { + "value": "${AZURE_ENV_FOUNDRY_PROJECT_ID}" + }, + "imageTag": { + "value": "${AZURE_ENV_IMAGE_TAG}" + }, + "enableTelemetry": { + "value": "${AZURE_ENV_ENABLE_TELEMETRY}" + }, + "existingLogAnalyticsWorkspaceId": { + "value": "${AZURE_ENV_LOG_ANALYTICS_WORKSPACE_ID}" + }, + "backendExists": { + "value": "${SERVICE_BACKEND_RESOURCE_EXISTS=false}" + }, + "backendDefinition": { + "value": { + "settings": [ + { + "name": "", + "value": "${VAR}", + "_comment_name": "The name of the environment variable when running in Azure. If empty, ignored.", + "_comment_value": "The value to provide. This can be a fixed literal, or an expression like ${VAR} to use the value of 'VAR' from the current environment." + }, + { + "name": "", + "value": "${VAR_S}", + "secret": true, + "_comment_name": "The name of the environment variable when running in Azure. If empty, ignored.", + "_comment_value": "The value to provide. This can be a fixed literal, or an expression like ${VAR_S} to use the value of 'VAR_S' from the current environment." + } + ] + } + }, + "frontendExists": { + "value": "${SERVICE_FRONTEND_RESOURCE_EXISTS=false}" + }, + "frontendDefinition": { + "value": { + "settings": [ + { + "name": "", + "value": "${VAR}", + "_comment_name": "The name of the environment variable when running in Azure. If empty, ignored.", + "_comment_value": "The value to provide. This can be a fixed literal, or an expression like ${VAR} to use the value of 'VAR' from the current environment." + }, + { + "name": "", + "value": "${VAR_S}", + "secret": true, + "_comment_name": "The name of the environment variable when running in Azure. If empty, ignored.", + "_comment_value": "The value to provide. This can be a fixed literal, or an expression like ${VAR_S} to use the value of 'VAR_S' from the current environment." + } + ] + } + }, + "principalId": { + "value": "${AZURE_PRINCIPAL_ID}" + } + } +} \ No newline at end of file diff --git a/infra/modules/account/main.bicep b/infra/old/08-2025/modules/account/main.bicep similarity index 100% rename from infra/modules/account/main.bicep rename to infra/old/08-2025/modules/account/main.bicep diff --git a/infra/modules/account/modules/dependencies.bicep b/infra/old/08-2025/modules/account/modules/dependencies.bicep similarity index 100% rename from infra/modules/account/modules/dependencies.bicep rename to infra/old/08-2025/modules/account/modules/dependencies.bicep diff --git a/infra/modules/account/modules/keyVaultExport.bicep b/infra/old/08-2025/modules/account/modules/keyVaultExport.bicep similarity index 100% rename from infra/modules/account/modules/keyVaultExport.bicep rename to infra/old/08-2025/modules/account/modules/keyVaultExport.bicep diff --git a/infra/modules/account/modules/project.bicep b/infra/old/08-2025/modules/account/modules/project.bicep similarity index 100% rename from infra/modules/account/modules/project.bicep rename to infra/old/08-2025/modules/account/modules/project.bicep diff --git a/infra/modules/ai-hub.bicep b/infra/old/08-2025/modules/ai-hub.bicep similarity index 100% rename from infra/modules/ai-hub.bicep rename to infra/old/08-2025/modules/ai-hub.bicep diff --git a/infra/modules/container-app-environment.bicep b/infra/old/08-2025/modules/container-app-environment.bicep similarity index 100% rename from infra/modules/container-app-environment.bicep rename to infra/old/08-2025/modules/container-app-environment.bicep diff --git a/infra/modules/fetch-container-image.bicep b/infra/old/08-2025/modules/fetch-container-image.bicep similarity index 100% rename from infra/modules/fetch-container-image.bicep rename to infra/old/08-2025/modules/fetch-container-image.bicep diff --git a/infra/modules/role.bicep b/infra/old/08-2025/modules/role.bicep similarity index 100% rename from infra/modules/role.bicep rename to infra/old/08-2025/modules/role.bicep diff --git a/src/backend/app_config.py b/src/backend/app_config.py index fe2b9f90c..0f2871967 100644 --- a/src/backend/app_config.py +++ b/src/backend/app_config.py @@ -115,7 +115,7 @@ def get_cosmos_database_client(self): try: if self._cosmos_client is None: self._cosmos_client = CosmosClient( - self.COSMOSDB_ENDPOINT, credential=get_azure_credential() + self.COSMOSDB_ENDPOINT, credential=get_azure_credential(self.AZURE_CLIENT_ID) ) if self._cosmos_database is None: @@ -152,7 +152,7 @@ def get_ai_project_client(self): return self._ai_project_client try: - credential = get_azure_credential() + credential = get_azure_credential(self.AZURE_CLIENT_ID) if credential is None: raise RuntimeError( "Unable to acquire Azure credentials; ensure Managed Identity is configured" diff --git a/src/backend/config_kernel.py b/src/backend/config_kernel.py index 598a88dc5..3fb92c1f0 100644 --- a/src/backend/config_kernel.py +++ b/src/backend/config_kernel.py @@ -32,7 +32,7 @@ class Config: @staticmethod def GetAzureCredentials(): """Get Azure credentials using the AppConfig implementation.""" - return get_azure_credential() + return get_azure_credential(config.AZURE_CLIENT_ID) @staticmethod def GetCosmosDatabaseClient(): diff --git a/src/backend/context/cosmos_memory_kernel.py b/src/backend/context/cosmos_memory_kernel.py index d547979da..e20cae00a 100644 --- a/src/backend/context/cosmos_memory_kernel.py +++ b/src/backend/context/cosmos_memory_kernel.py @@ -73,7 +73,7 @@ async def initialize(self): if not self._database: # Create Cosmos client cosmos_client = CosmosClient( - self._cosmos_endpoint, credential=get_azure_credential() + self._cosmos_endpoint, credential=get_azure_credential(config.AZURE_CLIENT_ID) ) self._database = cosmos_client.get_database_client( self._cosmos_database diff --git a/src/backend/tests/context/test_cosmos_memory.py b/src/backend/tests/context/test_cosmos_memory.py index 0467d9907..55cf263ce 100644 --- a/src/backend/tests/context/test_cosmos_memory.py +++ b/src/backend/tests/context/test_cosmos_memory.py @@ -25,6 +25,7 @@ def _fake_get_azure_credential(*_a, **_k): COSMOSDB_CONTAINER="mock-container", COSMOSDB_ENDPOINT="https://mock-endpoint", COSMOSDB_DATABASE="mock-database", + AZURE_CLIENT_ID="mock-client-id", ) sys.modules.setdefault("app_config", app_config_mod) diff --git a/src/backend/utils_kernel.py b/src/backend/utils_kernel.py index b6398ae2c..37753d171 100644 --- a/src/backend/utils_kernel.py +++ b/src/backend/utils_kernel.py @@ -172,7 +172,7 @@ async def rai_success(description: str, is_task_creation: bool) -> bool: """ try: # Use managed identity for authentication to Azure OpenAI - credential = get_azure_credential() + credential = get_azure_credential(config.AZURE_CLIENT_ID) access_token = credential.get_token( "https://cognitiveservices.azure.com/.default" ).token