diff --git a/README.md b/README.md index 6c273f7f..1b80ab1c 100644 --- a/README.md +++ b/README.md @@ -37,7 +37,7 @@ Each sample is a self-contained project with its own README, Azure CLI scripts a | Function App with Managed Identities ([Python](./samples/function-app-managed-identity/python/README.md), [.NET](./samples/function-app-managed-identity/dotnet/README.md)) | A serverless text processor: an Azure Functions app reads text blobs from an `input` container, converts them to uppercase and writes the result to an `output` container, authenticating to the storage account with a managed identity instead of keys. | | Function App with Service Bus ([.NET](./samples/function-app-service-bus/dotnet/README.md)) | An Azure Functions app on an App Service plan that exchanges messages through Service Bus queues: an HTTP trigger sends greetings and a queue trigger consumes them, connecting with either a connection string or a managed identity. | | Web App with Cosmos DB for MongoDB API ([Python](./samples/web-app-cosmosdb-mongodb-api/python/README.md), [.NET](./samples/web-app-cosmosdb-mongodb-api/dotnet/README.md)) | The *Vacation Planner* single-page web app on an Azure Web App with regional VNet integration, storing activities in the `activities` collection of an Azure Cosmos DB for MongoDB account reached through a private endpoint. | -| Web App with CosmosDB for NoSQL API ([Python](./samples/web-app-cosmosdb-nosql-api/python/README.md), [.NET](./samples/web-app-cosmosdb-nosql-api/dotnet/README.md)) | The *Vacation Planner* single-page web app on an Azure Web App, storing activities as JSON items in the `activities` container of an Azure Cosmos DB for NoSQL database partitioned by user; deployed with Azure CLI scripts. | +| Web App with CosmosDB for NoSQL API ([Python](./samples/web-app-cosmosdb-nosql-api/python/README.md), [.NET](./samples/web-app-cosmosdb-nosql-api/dotnet/README.md)) | The *Vacation Planner* single-page web app on an Azure Web App, storing activities as JSON items in the `activities` container of an Azure Cosmos DB for NoSQL database partitioned by user, and reaching the account with its key or with a system-assigned or user-assigned managed identity through Microsoft Entra ID; deployed with Azure CLI scripts, Bicep or Terraform. | | Web App with Managed Identities ([Python](./samples/web-app-managed-identity/python/README.md), [.NET](./samples/web-app-managed-identity/dotnet/README.md)) | The *Vacation Planner* single-page web app on an Azure Web App, storing each activity as a blob in an `activities` container and accessing Blob Storage through a user-assigned or system-assigned managed identity rather than connection strings. | | Web App with SQL Database ([Python](./samples/web-app-sql-database/python/README.md), [.NET](./samples/web-app-sql-database/dotnet/README.md)) | The *Vacation Planner* single-page web app on an Azure Web App, storing activities in an Azure SQL Database. The connection string and the HTTPS certificate are read from Azure Key Vault, and an API endpoint verifies the Key Vault certificate. | | Web App with PostgreSQL Database ([Python](./samples/web-app-postgresql-flexible-server/python/README.md), [.NET](./samples/web-app-postgresql-flexible-server/dotnet/README.md)) | The *Vacation Planner* single-page web app on an Azure Web App, storing activities in an Azure Database for PostgreSQL flexible server injected into a virtual network (delegated subnet and private DNS zone), with the database and application user created by the deploy scripts. | diff --git a/run-samples.sh b/run-samples.sh index 7d11fa5a..9def2a59 100755 --- a/run-samples.sh +++ b/run-samples.sh @@ -42,6 +42,10 @@ SAMPLES=( "samples/web-app-cosmosdb-mongodb-api/dotnet|bash scripts/deploy.sh|bash scripts/validate.sh && bash scripts/call-web-app.sh && bash scripts/query-telemetry.sh && bash scripts/query-logs-and-metrics.sh" "samples/web-app-cosmosdb-nosql-api/python|bash scripts/deploy.sh|bash scripts/validate.sh && bash scripts/call-web-app.sh && bash scripts/query-telemetry.sh && bash scripts/query-logs-and-metrics.sh" "samples/web-app-cosmosdb-nosql-api/dotnet|bash scripts/deploy.sh|bash scripts/validate.sh && bash scripts/call-web-app.sh && bash scripts/query-telemetry.sh && bash scripts/query-logs-and-metrics.sh" + "samples/web-app-cosmosdb-nosql-api/python|MANAGED_IDENTITY_TYPE=SystemAssigned bash scripts/deploy.sh|MANAGED_IDENTITY_TYPE=SystemAssigned bash scripts/validate.sh" + "samples/web-app-cosmosdb-nosql-api/python|MANAGED_IDENTITY_TYPE=UserAssigned bash scripts/deploy.sh|MANAGED_IDENTITY_TYPE=UserAssigned bash scripts/validate.sh" + "samples/web-app-cosmosdb-nosql-api/dotnet|MANAGED_IDENTITY_TYPE=SystemAssigned bash scripts/deploy.sh|MANAGED_IDENTITY_TYPE=SystemAssigned bash scripts/validate.sh" + "samples/web-app-cosmosdb-nosql-api/dotnet|MANAGED_IDENTITY_TYPE=UserAssigned bash scripts/deploy.sh|MANAGED_IDENTITY_TYPE=UserAssigned bash scripts/validate.sh" "samples/web-app-managed-identity/python|bash scripts/user-assigned.sh|bash scripts/validate.sh && bash scripts/call-web-app.sh && bash scripts/query-telemetry.sh && bash scripts/query-logs-and-metrics.sh" "samples/web-app-managed-identity/dotnet|bash scripts/user-assigned.sh|bash scripts/validate.sh && bash scripts/call-web-app.sh && bash scripts/query-telemetry.sh && bash scripts/query-logs-and-metrics.sh" "samples/web-app-sql-database/python|bash scripts/deploy.sh|bash scripts/validate.sh && bash scripts/call-web-app.sh && bash scripts/query-telemetry.sh && bash scripts/query-logs-and-metrics.sh" @@ -74,6 +78,10 @@ TERRAFORM_SAMPLES=( "samples/function-app-storage-http/python/terraform|bash deploy.sh|bash ../scripts/query-telemetry.sh && bash ../scripts/query-logs-and-metrics.sh" "samples/web-app-cosmosdb-mongodb-api/python/terraform|bash deploy.sh|bash ../scripts/query-telemetry.sh && bash ../scripts/query-logs-and-metrics.sh" "samples/web-app-cosmosdb-mongodb-api/dotnet/terraform|bash deploy.sh|bash ../scripts/query-telemetry.sh && bash ../scripts/query-logs-and-metrics.sh" + "samples/web-app-cosmosdb-nosql-api/python/terraform|MANAGED_IDENTITY_TYPE=SystemAssigned bash deploy.sh|MANAGED_IDENTITY_TYPE=SystemAssigned bash ../scripts/validate.sh && bash ../scripts/query-telemetry.sh && bash ../scripts/query-logs-and-metrics.sh" + "samples/web-app-cosmosdb-nosql-api/python/terraform|MANAGED_IDENTITY_TYPE=UserAssigned bash deploy.sh|MANAGED_IDENTITY_TYPE=UserAssigned bash ../scripts/validate.sh && bash ../scripts/query-telemetry.sh && bash ../scripts/query-logs-and-metrics.sh" + "samples/web-app-cosmosdb-nosql-api/dotnet/terraform|MANAGED_IDENTITY_TYPE=SystemAssigned bash deploy.sh|MANAGED_IDENTITY_TYPE=SystemAssigned bash ../scripts/validate.sh && bash ../scripts/query-telemetry.sh && bash ../scripts/query-logs-and-metrics.sh" + "samples/web-app-cosmosdb-nosql-api/dotnet/terraform|MANAGED_IDENTITY_TYPE=UserAssigned bash deploy.sh|MANAGED_IDENTITY_TYPE=UserAssigned bash ../scripts/validate.sh && bash ../scripts/query-telemetry.sh && bash ../scripts/query-logs-and-metrics.sh" "samples/web-app-managed-identity/python/terraform|bash deploy.sh|bash ../scripts/query-telemetry.sh && bash ../scripts/query-logs-and-metrics.sh" "samples/web-app-managed-identity/dotnet/terraform|bash deploy.sh|bash ../scripts/query-telemetry.sh && bash ../scripts/query-logs-and-metrics.sh" "samples/web-app-sql-database/python/terraform|bash deploy.sh|bash ../scripts/validate.sh && bash ../scripts/query-telemetry.sh && bash ../scripts/query-logs-and-metrics.sh" @@ -108,6 +116,10 @@ BICEP_SAMPLES=( "samples/function-app-storage-http/python/bicep|bash deploy.sh|bash ../scripts/query-telemetry.sh && bash ../scripts/query-logs-and-metrics.sh" "samples/web-app-cosmosdb-mongodb-api/python/bicep|bash deploy.sh|bash ../scripts/query-telemetry.sh && bash ../scripts/query-logs-and-metrics.sh" "samples/web-app-cosmosdb-mongodb-api/dotnet/bicep|bash deploy.sh|bash ../scripts/query-telemetry.sh && bash ../scripts/query-logs-and-metrics.sh" + "samples/web-app-cosmosdb-nosql-api/python/bicep|MANAGED_IDENTITY_TYPE=SystemAssigned bash deploy.sh|MANAGED_IDENTITY_TYPE=SystemAssigned bash ../scripts/validate.sh && bash ../scripts/query-telemetry.sh && bash ../scripts/query-logs-and-metrics.sh" + "samples/web-app-cosmosdb-nosql-api/python/bicep|MANAGED_IDENTITY_TYPE=UserAssigned bash deploy.sh|MANAGED_IDENTITY_TYPE=UserAssigned bash ../scripts/validate.sh && bash ../scripts/query-telemetry.sh && bash ../scripts/query-logs-and-metrics.sh" + "samples/web-app-cosmosdb-nosql-api/dotnet/bicep|MANAGED_IDENTITY_TYPE=SystemAssigned bash deploy.sh|MANAGED_IDENTITY_TYPE=SystemAssigned bash ../scripts/validate.sh && bash ../scripts/query-telemetry.sh && bash ../scripts/query-logs-and-metrics.sh" + "samples/web-app-cosmosdb-nosql-api/dotnet/bicep|MANAGED_IDENTITY_TYPE=UserAssigned bash deploy.sh|MANAGED_IDENTITY_TYPE=UserAssigned bash ../scripts/validate.sh && bash ../scripts/query-telemetry.sh && bash ../scripts/query-logs-and-metrics.sh" "samples/web-app-managed-identity/python/bicep|bash deploy.sh|bash ../scripts/query-telemetry.sh && bash ../scripts/query-logs-and-metrics.sh" "samples/web-app-managed-identity/dotnet/bicep|bash deploy.sh|bash ../scripts/query-telemetry.sh && bash ../scripts/query-logs-and-metrics.sh" "samples/web-app-mysql-flexible-server/python/bicep|bash deploy.sh|bash ../scripts/query-telemetry.sh && bash ../scripts/query-logs-and-metrics.sh" diff --git a/samples/aci-blob-storage/python/terraform/deploy.sh b/samples/aci-blob-storage/python/terraform/deploy.sh index 75db23d1..0bcd3595 100755 --- a/samples/aci-blob-storage/python/terraform/deploy.sh +++ b/samples/aci-blob-storage/python/terraform/deploy.sh @@ -17,13 +17,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" # The emulator applies role assignments immediately, so the role needs no propagation wait. diff --git a/samples/api-management-function-app/python/bicep/main.bicep b/samples/api-management-function-app/python/bicep/main.bicep index c91d6f43..4d24170f 100644 --- a/samples/api-management-function-app/python/bicep/main.bicep +++ b/samples/api-management-function-app/python/bicep/main.bicep @@ -60,7 +60,7 @@ param applicationInsightsName string = '' @description('Specifies the service tier of the workspace.') @allowed(['Free','Standalone','PerNode','PerGB2018']) -param logAnalyticsSku string = 'PerNode' +param logAnalyticsSku string = 'PerGB2018' @description('Specifies the workspace data retention in days.') param logAnalyticsRetentionInDays int = 60 diff --git a/samples/api-management-function-app/python/bicep/modules/log-analytics.bicep b/samples/api-management-function-app/python/bicep/modules/log-analytics.bicep index 0f9ca50d..2096fc03 100644 --- a/samples/api-management-function-app/python/bicep/modules/log-analytics.bicep +++ b/samples/api-management-function-app/python/bicep/modules/log-analytics.bicep @@ -14,7 +14,7 @@ param location string = resourceGroup().location 'PerNode' 'PerGB2018' ]) -param sku string = 'PerNode' +param sku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param retentionInDays int = 60 diff --git a/samples/api-management-function-app/python/scripts/deploy.sh b/samples/api-management-function-app/python/scripts/deploy.sh index 410c473f..b25bbc68 100755 --- a/samples/api-management-function-app/python/scripts/deploy.sh +++ b/samples/api-management-function-app/python/scripts/deploy.sh @@ -99,7 +99,7 @@ if [[ $? != 0 ]]; then --location "$LOCATION" \ --query-access "Enabled" \ --retention-time 30 \ - --sku "PerNode" \ + --sku "PerGB2018" \ --tags environment=test iac=az-cli \ --only-show-errors 1>/dev/null diff --git a/samples/container-apps-blob-storage/python/terraform/deploy.sh b/samples/container-apps-blob-storage/python/terraform/deploy.sh index ff861d66..83f2e4e0 100755 --- a/samples/container-apps-blob-storage/python/terraform/deploy.sh +++ b/samples/container-apps-blob-storage/python/terraform/deploy.sh @@ -17,13 +17,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets the emulator at [$RESOURCE_MANAGER_ENDPOINT]" diff --git a/samples/eventhubs-eventgrid/python/bicep/modules/log-analytics.bicep b/samples/eventhubs-eventgrid/python/bicep/modules/log-analytics.bicep index 0f9ca50d..2096fc03 100644 --- a/samples/eventhubs-eventgrid/python/bicep/modules/log-analytics.bicep +++ b/samples/eventhubs-eventgrid/python/bicep/modules/log-analytics.bicep @@ -14,7 +14,7 @@ param location string = resourceGroup().location 'PerNode' 'PerGB2018' ]) -param sku string = 'PerNode' +param sku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param retentionInDays int = 60 diff --git a/samples/eventhubs-eventgrid/python/terraform/deploy.sh b/samples/eventhubs-eventgrid/python/terraform/deploy.sh index 2b80bb65..66c7dc91 100755 --- a/samples/eventhubs-eventgrid/python/terraform/deploy.sh +++ b/samples/eventhubs-eventgrid/python/terraform/deploy.sh @@ -30,13 +30,13 @@ cd "$CURRENT_DIR" || exit 1 # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets the emulator at [$RESOURCE_MANAGER_ENDPOINT]" diff --git a/samples/eventhubs/python/terraform/deploy.sh b/samples/eventhubs/python/terraform/deploy.sh index 0c35079e..41b8b155 100755 --- a/samples/eventhubs/python/terraform/deploy.sh +++ b/samples/eventhubs/python/terraform/deploy.sh @@ -31,13 +31,13 @@ cd "$CURRENT_DIR" || exit 1 # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets the emulator at [$RESOURCE_MANAGER_ENDPOINT]" diff --git a/samples/function-app-front-door/python/scripts/deploy.sh b/samples/function-app-front-door/python/scripts/deploy.sh index 69fbd3c8..005a65a8 100755 --- a/samples/function-app-front-door/python/scripts/deploy.sh +++ b/samples/function-app-front-door/python/scripts/deploy.sh @@ -124,7 +124,7 @@ if [[ $? != 0 ]]; then --location "$LOCATION" \ --query-access "Enabled" \ --retention-time 30 \ - --sku "PerNode" \ + --sku "PerGB2018" \ --tags environment=test iac=az-cli \ --only-show-errors 1>/dev/null diff --git a/samples/function-app-managed-identity/dotnet/bicep/modules/log-analytics.bicep b/samples/function-app-managed-identity/dotnet/bicep/modules/log-analytics.bicep index 0f9ca50d..2096fc03 100644 --- a/samples/function-app-managed-identity/dotnet/bicep/modules/log-analytics.bicep +++ b/samples/function-app-managed-identity/dotnet/bicep/modules/log-analytics.bicep @@ -14,7 +14,7 @@ param location string = resourceGroup().location 'PerNode' 'PerGB2018' ]) -param sku string = 'PerNode' +param sku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param retentionInDays int = 60 diff --git a/samples/function-app-managed-identity/dotnet/terraform/deploy.sh b/samples/function-app-managed-identity/dotnet/terraform/deploy.sh index e86d8b73..f9d9c31c 100755 --- a/samples/function-app-managed-identity/dotnet/terraform/deploy.sh +++ b/samples/function-app-managed-identity/dotnet/terraform/deploy.sh @@ -18,13 +18,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets the emulator at [$RESOURCE_MANAGER_ENDPOINT]" diff --git a/samples/function-app-managed-identity/python/bicep/modules/log-analytics.bicep b/samples/function-app-managed-identity/python/bicep/modules/log-analytics.bicep index 0f9ca50d..2096fc03 100644 --- a/samples/function-app-managed-identity/python/bicep/modules/log-analytics.bicep +++ b/samples/function-app-managed-identity/python/bicep/modules/log-analytics.bicep @@ -14,7 +14,7 @@ param location string = resourceGroup().location 'PerNode' 'PerGB2018' ]) -param sku string = 'PerNode' +param sku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param retentionInDays int = 60 diff --git a/samples/function-app-managed-identity/python/terraform/deploy.sh b/samples/function-app-managed-identity/python/terraform/deploy.sh index 6749585c..264204d8 100755 --- a/samples/function-app-managed-identity/python/terraform/deploy.sh +++ b/samples/function-app-managed-identity/python/terraform/deploy.sh @@ -18,13 +18,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets the emulator at [$RESOURCE_MANAGER_ENDPOINT]" diff --git a/samples/function-app-service-bus/dotnet/bicep/main.bicep b/samples/function-app-service-bus/dotnet/bicep/main.bicep index 885fdca9..8bb9be1f 100644 --- a/samples/function-app-service-bus/dotnet/bicep/main.bicep +++ b/samples/function-app-service-bus/dotnet/bicep/main.bicep @@ -260,7 +260,7 @@ param logAnalyticsName string = '' 'PerNode' 'PerGB2018' ]) -param logAnalyticsSku string = 'PerNode' +param logAnalyticsSku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param logAnalyticsRetentionInDays int = 60 diff --git a/samples/function-app-service-bus/dotnet/bicep/modules/log-analytics.bicep b/samples/function-app-service-bus/dotnet/bicep/modules/log-analytics.bicep index 0f9ca50d..2096fc03 100644 --- a/samples/function-app-service-bus/dotnet/bicep/modules/log-analytics.bicep +++ b/samples/function-app-service-bus/dotnet/bicep/modules/log-analytics.bicep @@ -14,7 +14,7 @@ param location string = resourceGroup().location 'PerNode' 'PerGB2018' ]) -param sku string = 'PerNode' +param sku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param retentionInDays int = 60 diff --git a/samples/function-app-service-bus/dotnet/scripts/deploy.sh b/samples/function-app-service-bus/dotnet/scripts/deploy.sh index b74a8636..53d37bcf 100755 --- a/samples/function-app-service-bus/dotnet/scripts/deploy.sh +++ b/samples/function-app-service-bus/dotnet/scripts/deploy.sh @@ -806,7 +806,7 @@ if [[ $? != 0 ]]; then --location "$LOCATION" \ --query-access "Enabled" \ --retention-time 30 \ - --sku "PerNode" \ + --sku "PerGB2018" \ --tags $TAGS \ --only-show-errors 1>/dev/null diff --git a/samples/function-app-service-bus/dotnet/terraform/deploy.sh b/samples/function-app-service-bus/dotnet/terraform/deploy.sh index 3c2e6486..35175ecf 100755 --- a/samples/function-app-service-bus/dotnet/terraform/deploy.sh +++ b/samples/function-app-service-bus/dotnet/terraform/deploy.sh @@ -17,13 +17,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets the emulator at [$RESOURCE_MANAGER_ENDPOINT]" diff --git a/samples/function-app-storage-http/dotnet/bicep/modules/log-analytics.bicep b/samples/function-app-storage-http/dotnet/bicep/modules/log-analytics.bicep index 0f9ca50d..2096fc03 100644 --- a/samples/function-app-storage-http/dotnet/bicep/modules/log-analytics.bicep +++ b/samples/function-app-storage-http/dotnet/bicep/modules/log-analytics.bicep @@ -14,7 +14,7 @@ param location string = resourceGroup().location 'PerNode' 'PerGB2018' ]) -param sku string = 'PerNode' +param sku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param retentionInDays int = 60 diff --git a/samples/function-app-storage-http/dotnet/terraform/deploy.sh b/samples/function-app-storage-http/dotnet/terraform/deploy.sh index d0083dcd..fcda711c 100755 --- a/samples/function-app-storage-http/dotnet/terraform/deploy.sh +++ b/samples/function-app-storage-http/dotnet/terraform/deploy.sh @@ -17,13 +17,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets the emulator at [$RESOURCE_MANAGER_ENDPOINT]" diff --git a/samples/function-app-storage-http/python/bicep/modules/log-analytics.bicep b/samples/function-app-storage-http/python/bicep/modules/log-analytics.bicep index 0f9ca50d..2096fc03 100644 --- a/samples/function-app-storage-http/python/bicep/modules/log-analytics.bicep +++ b/samples/function-app-storage-http/python/bicep/modules/log-analytics.bicep @@ -14,7 +14,7 @@ param location string = resourceGroup().location 'PerNode' 'PerGB2018' ]) -param sku string = 'PerNode' +param sku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param retentionInDays int = 60 diff --git a/samples/function-app-storage-http/python/terraform/deploy.sh b/samples/function-app-storage-http/python/terraform/deploy.sh index dc968d3a..9bb56241 100755 --- a/samples/function-app-storage-http/python/terraform/deploy.sh +++ b/samples/function-app-storage-http/python/terraform/deploy.sh @@ -17,13 +17,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets the emulator at [$RESOURCE_MANAGER_ENDPOINT]" diff --git a/samples/servicebus/java/terraform/deploy.sh b/samples/servicebus/java/terraform/deploy.sh index 50e0d8e2..49add4a4 100755 --- a/samples/servicebus/java/terraform/deploy.sh +++ b/samples/servicebus/java/terraform/deploy.sh @@ -15,13 +15,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets the emulator at [$RESOURCE_MANAGER_ENDPOINT]" diff --git a/samples/url-shortener/python/bicep/modules/log-analytics.bicep b/samples/url-shortener/python/bicep/modules/log-analytics.bicep index 0f9ca50d..2096fc03 100644 --- a/samples/url-shortener/python/bicep/modules/log-analytics.bicep +++ b/samples/url-shortener/python/bicep/modules/log-analytics.bicep @@ -14,7 +14,7 @@ param location string = resourceGroup().location 'PerNode' 'PerGB2018' ]) -param sku string = 'PerNode' +param sku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param retentionInDays int = 60 diff --git a/samples/url-shortener/python/terraform/deploy.sh b/samples/url-shortener/python/terraform/deploy.sh index b61dd9c4..c51eb105 100755 --- a/samples/url-shortener/python/terraform/deploy.sh +++ b/samples/url-shortener/python/terraform/deploy.sh @@ -18,13 +18,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets the emulator at [$RESOURCE_MANAGER_ENDPOINT]" diff --git a/samples/web-app-app-configuration/dotnet/bicep/main.bicep b/samples/web-app-app-configuration/dotnet/bicep/main.bicep index 70689012..b530f81a 100644 --- a/samples/web-app-app-configuration/dotnet/bicep/main.bicep +++ b/samples/web-app-app-configuration/dotnet/bicep/main.bicep @@ -255,7 +255,7 @@ param applicationInsightsName string = '' @description('Specifies the service tier of the workspace.') @allowed(['Free','Standalone','PerNode','PerGB2018']) -param logAnalyticsSku string = 'PerNode' +param logAnalyticsSku string = 'PerGB2018' @description('Specifies the workspace data retention in days.') param logAnalyticsRetentionInDays int = 60 diff --git a/samples/web-app-app-configuration/dotnet/bicep/modules/log-analytics.bicep b/samples/web-app-app-configuration/dotnet/bicep/modules/log-analytics.bicep index 0f9ca50d..2096fc03 100644 --- a/samples/web-app-app-configuration/dotnet/bicep/modules/log-analytics.bicep +++ b/samples/web-app-app-configuration/dotnet/bicep/modules/log-analytics.bicep @@ -14,7 +14,7 @@ param location string = resourceGroup().location 'PerNode' 'PerGB2018' ]) -param sku string = 'PerNode' +param sku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param retentionInDays int = 60 diff --git a/samples/web-app-app-configuration/dotnet/scripts/deploy.sh b/samples/web-app-app-configuration/dotnet/scripts/deploy.sh index 1394b019..6e9d3512 100755 --- a/samples/web-app-app-configuration/dotnet/scripts/deploy.sh +++ b/samples/web-app-app-configuration/dotnet/scripts/deploy.sh @@ -1550,7 +1550,7 @@ if [[ $? != 0 ]]; then --location "$LOCATION" \ --query-access "Enabled" \ --retention-time 30 \ - --sku "PerNode" \ + --sku "PerGB2018" \ --tags environment=test iac=az-cli \ --only-show-errors 1>/dev/null diff --git a/samples/web-app-app-configuration/dotnet/terraform/deploy.sh b/samples/web-app-app-configuration/dotnet/terraform/deploy.sh index ad60d3eb..77853615 100755 --- a/samples/web-app-app-configuration/dotnet/terraform/deploy.sh +++ b/samples/web-app-app-configuration/dotnet/terraform/deploy.sh @@ -25,13 +25,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator endpoints, taken from the az cloud # registration that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" export ARM_RESOURCE_MANAGER_ENDPOINT="$RESOURCE_MANAGER_ENDPOINT" diff --git a/samples/web-app-app-configuration/python/bicep/main.bicep b/samples/web-app-app-configuration/python/bicep/main.bicep index 70689012..b530f81a 100644 --- a/samples/web-app-app-configuration/python/bicep/main.bicep +++ b/samples/web-app-app-configuration/python/bicep/main.bicep @@ -255,7 +255,7 @@ param applicationInsightsName string = '' @description('Specifies the service tier of the workspace.') @allowed(['Free','Standalone','PerNode','PerGB2018']) -param logAnalyticsSku string = 'PerNode' +param logAnalyticsSku string = 'PerGB2018' @description('Specifies the workspace data retention in days.') param logAnalyticsRetentionInDays int = 60 diff --git a/samples/web-app-app-configuration/python/bicep/modules/log-analytics.bicep b/samples/web-app-app-configuration/python/bicep/modules/log-analytics.bicep index 0f9ca50d..2096fc03 100644 --- a/samples/web-app-app-configuration/python/bicep/modules/log-analytics.bicep +++ b/samples/web-app-app-configuration/python/bicep/modules/log-analytics.bicep @@ -14,7 +14,7 @@ param location string = resourceGroup().location 'PerNode' 'PerGB2018' ]) -param sku string = 'PerNode' +param sku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param retentionInDays int = 60 diff --git a/samples/web-app-app-configuration/python/scripts/deploy.sh b/samples/web-app-app-configuration/python/scripts/deploy.sh index c3d87690..a2172a17 100755 --- a/samples/web-app-app-configuration/python/scripts/deploy.sh +++ b/samples/web-app-app-configuration/python/scripts/deploy.sh @@ -1550,7 +1550,7 @@ if [[ $? != 0 ]]; then --location "$LOCATION" \ --query-access "Enabled" \ --retention-time 30 \ - --sku "PerNode" \ + --sku "PerGB2018" \ --tags environment=test iac=az-cli \ --only-show-errors 1>/dev/null diff --git a/samples/web-app-app-configuration/python/terraform/deploy.sh b/samples/web-app-app-configuration/python/terraform/deploy.sh index ea88a7a6..d754e7f0 100755 --- a/samples/web-app-app-configuration/python/terraform/deploy.sh +++ b/samples/web-app-app-configuration/python/terraform/deploy.sh @@ -25,13 +25,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator endpoints, taken from the az cloud # registration that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" export ARM_RESOURCE_MANAGER_ENDPOINT="$RESOURCE_MANAGER_ENDPOINT" diff --git a/samples/web-app-cosmosdb-mongodb-api/dotnet/bicep/main.bicep b/samples/web-app-cosmosdb-mongodb-api/dotnet/bicep/main.bicep index 52291e55..cc2e913b 100644 --- a/samples/web-app-cosmosdb-mongodb-api/dotnet/bicep/main.bicep +++ b/samples/web-app-cosmosdb-mongodb-api/dotnet/bicep/main.bicep @@ -256,7 +256,7 @@ param applicationInsightsName string = '' 'PerNode' 'PerGB2018' ]) -param logAnalyticsSku string = 'PerNode' +param logAnalyticsSku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param logAnalyticsRetentionInDays int = 60 diff --git a/samples/web-app-cosmosdb-mongodb-api/dotnet/bicep/modules/log-analytics.bicep b/samples/web-app-cosmosdb-mongodb-api/dotnet/bicep/modules/log-analytics.bicep index 0f9ca50d..2096fc03 100644 --- a/samples/web-app-cosmosdb-mongodb-api/dotnet/bicep/modules/log-analytics.bicep +++ b/samples/web-app-cosmosdb-mongodb-api/dotnet/bicep/modules/log-analytics.bicep @@ -14,7 +14,7 @@ param location string = resourceGroup().location 'PerNode' 'PerGB2018' ]) -param sku string = 'PerNode' +param sku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param retentionInDays int = 60 diff --git a/samples/web-app-cosmosdb-mongodb-api/dotnet/scripts/deploy.sh b/samples/web-app-cosmosdb-mongodb-api/dotnet/scripts/deploy.sh index 8e21e28e..58073f61 100755 --- a/samples/web-app-cosmosdb-mongodb-api/dotnet/scripts/deploy.sh +++ b/samples/web-app-cosmosdb-mongodb-api/dotnet/scripts/deploy.sh @@ -769,7 +769,7 @@ if [[ $? != 0 ]]; then --location "$LOCATION" \ --query-access "Enabled" \ --retention-time 30 \ - --sku "PerNode" \ + --sku "PerGB2018" \ --only-show-errors 1>/dev/null if [[ $? == 0 ]]; then diff --git a/samples/web-app-cosmosdb-mongodb-api/dotnet/terraform/deploy.sh b/samples/web-app-cosmosdb-mongodb-api/dotnet/terraform/deploy.sh index 660961fa..382e205d 100755 --- a/samples/web-app-cosmosdb-mongodb-api/dotnet/terraform/deploy.sh +++ b/samples/web-app-cosmosdb-mongodb-api/dotnet/terraform/deploy.sh @@ -15,13 +15,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets the emulator at [$RESOURCE_MANAGER_ENDPOINT]" diff --git a/samples/web-app-cosmosdb-mongodb-api/python/bicep/main.bicep b/samples/web-app-cosmosdb-mongodb-api/python/bicep/main.bicep index 9681ac6a..11baec1a 100644 --- a/samples/web-app-cosmosdb-mongodb-api/python/bicep/main.bicep +++ b/samples/web-app-cosmosdb-mongodb-api/python/bicep/main.bicep @@ -255,7 +255,7 @@ param applicationInsightsName string = '' 'PerNode' 'PerGB2018' ]) -param logAnalyticsSku string = 'PerNode' +param logAnalyticsSku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param logAnalyticsRetentionInDays int = 60 diff --git a/samples/web-app-cosmosdb-mongodb-api/python/bicep/modules/log-analytics.bicep b/samples/web-app-cosmosdb-mongodb-api/python/bicep/modules/log-analytics.bicep index 0f9ca50d..2096fc03 100644 --- a/samples/web-app-cosmosdb-mongodb-api/python/bicep/modules/log-analytics.bicep +++ b/samples/web-app-cosmosdb-mongodb-api/python/bicep/modules/log-analytics.bicep @@ -14,7 +14,7 @@ param location string = resourceGroup().location 'PerNode' 'PerGB2018' ]) -param sku string = 'PerNode' +param sku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param retentionInDays int = 60 diff --git a/samples/web-app-cosmosdb-mongodb-api/python/scripts/deploy.sh b/samples/web-app-cosmosdb-mongodb-api/python/scripts/deploy.sh index be13bbca..ae0db02c 100755 --- a/samples/web-app-cosmosdb-mongodb-api/python/scripts/deploy.sh +++ b/samples/web-app-cosmosdb-mongodb-api/python/scripts/deploy.sh @@ -769,7 +769,7 @@ if [[ $? != 0 ]]; then --location "$LOCATION" \ --query-access "Enabled" \ --retention-time 30 \ - --sku "PerNode" \ + --sku "PerGB2018" \ --only-show-errors 1>/dev/null if [[ $? == 0 ]]; then diff --git a/samples/web-app-cosmosdb-mongodb-api/python/terraform/deploy.sh b/samples/web-app-cosmosdb-mongodb-api/python/terraform/deploy.sh index c1a7a729..a1426625 100755 --- a/samples/web-app-cosmosdb-mongodb-api/python/terraform/deploy.sh +++ b/samples/web-app-cosmosdb-mongodb-api/python/terraform/deploy.sh @@ -15,13 +15,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets the emulator at [$RESOURCE_MANAGER_ENDPOINT]" diff --git a/samples/web-app-cosmosdb-mongodb-api/python/terraform/variables.tf b/samples/web-app-cosmosdb-mongodb-api/python/terraform/variables.tf index 059e5483..83dcbf0c 100644 --- a/samples/web-app-cosmosdb-mongodb-api/python/terraform/variables.tf +++ b/samples/web-app-cosmosdb-mongodb-api/python/terraform/variables.tf @@ -167,7 +167,7 @@ variable "sku_name" { variable "python_version" { description = "(Optional) Specifies the version of Python to run. Possible values include 3.13, 3.12, 3.11, 3.10, 3.9, 3.8 and 3.7." type = string - default = "3.12" + default = "3.13" validation { condition = contains([ diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/README.md b/samples/web-app-cosmosdb-nosql-api/dotnet/README.md index 0260dfca..2436d525 100644 --- a/samples/web-app-cosmosdb-nosql-api/dotnet/README.md +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/README.md @@ -11,6 +11,7 @@ The following diagram illustrates the architecture of the solution: - **Azure Web App**: Hosts the ASP.NET Core application - **Azure App Service Plan**: Provides compute resources for the web app - **Azure CosmosDB for NoSQL API**: Stores activity data in a CosmosDB container +- **Managed identity**: The web app authenticates to the CosmosDB account with Microsoft Entra ID, as a system-assigned or user-assigned managed identity that has the Cosmos DB Built-in Data Contributor role on the account, instead of the account key. The Bicep and Terraform deployments always use one, the Azure CLI scripts with `MANAGED_IDENTITY_TYPE=SystemAssigned` or `UserAssigned`. See [Microsoft Entra ID authentication](#microsoft-entra-id-authentication) - **Azure Log Analytics workspace**: Centralizes the diagnostic logs and metrics of the web app, its plan and the CosmosDB account, the telemetry of Application Insights, and the audit records of the queries run on it - **Azure Application Insights**: A workspace-based resource that collects the requests, the calls to Azure Cosmos DB, the log records, the exceptions, the custom events and the custom metric of the web app, which the Microsoft OpenTelemetry Distro sends to the connection string of the `APPLICATIONINSIGHTS_CONNECTION_STRING` app setting. See [Application Insights](#application-insights) @@ -19,6 +20,7 @@ The following diagram illustrates the architecture of the solution: - [lstk CLI](https://docs.localstack.cloud/aws/developer-tools/running-localstack/lstk/) - [Azure Subscription](https://azure.microsoft.com/free/) - [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli) +- [Terraform](https://developer.hashicorp.com/terraform/downloads), if you plan to install the sample via Terraform. - [.NET SDK 10.0](https://dotnet.microsoft.com/en-us/download/dotnet/10.0) - [ASP.NET Core](https://learn.microsoft.com/en-us/aspnet/core/) @@ -52,10 +54,44 @@ lstk az start-interception Deploy the application to LocalStack for Azure using: - [Azure CLI Deployment](./scripts/README.md) +- [Bicep Deployment](./bicep/README.md) +- [Terraform Deployment](./terraform/README.md) > [!NOTE] > When you deploy the application to LocalStack for Azure for the first time, the initialization process involves downloading and building Docker images. This is a one-time operation—subsequent deployments will be significantly faster. Depending on your internet connection and system resources, this initial setup may take several minutes. +### Microsoft Entra ID authentication + +The web app reaches the CosmosDB account either with the account's primary key, in the `AZURECOSMOSDB_PRIMARY_KEY` app setting, or with Microsoft Entra ID, as a managed identity that has the [Cosmos DB Built-in Data Contributor](https://learn.microsoft.com/en-us/azure/cosmos-db/reference-data-plane-security#built-in-roles) role on the whole account, with no key anywhere. `MANAGED_IDENTITY_TYPE` picks one: + +| Deployment | `MANAGED_IDENTITY_TYPE` | Default | +| --- | --- | --- | +| [Azure CLI](./scripts/README.md) | `None` (the account key), `SystemAssigned` or `UserAssigned` | `None` | +| [Bicep](./bicep/README.md) | `SystemAssigned` or `UserAssigned` | `UserAssigned` | +| [Terraform](./terraform/README.md) | `SystemAssigned` or `UserAssigned` | `UserAssigned` | + +The three deployments give the resources the same names, so the validation script checks any of them. Pass it the same `MANAGED_IDENTITY_TYPE`: + +```bash +# Azure CLI, with the web app's system-assigned identity +MANAGED_IDENTITY_TYPE=SystemAssigned bash scripts/deploy.sh +MANAGED_IDENTITY_TYPE=SystemAssigned bash scripts/validate.sh + +# Bicep, with a user-assigned identity (for Terraform, run terraform/deploy.sh) +MANAGED_IDENTITY_TYPE=UserAssigned bash bicep/deploy.sh +MANAGED_IDENTITY_TYPE=UserAssigned bash scripts/validate.sh +``` + +With a managed identity, each deployment: + +- gives the web app a system-assigned managed identity, or creates a user-assigned managed identity, assigns it to the web app, and passes its client id in the `AZURE_CLIENT_ID` app setting +- assigns the identity the Cosmos DB Built-in Data Contributor role on the whole account. It's a role of the CosmosDB account itself (a SQL role assignment), not an Azure RBAC role: the Azure CLI scripts run `az cosmosdb sql role assignment create`, the Bicep template deploys a `Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments` resource ([cosmos-db-sql-role-assignment.bicep](./bicep/modules/cosmos-db-sql-role-assignment.bicep)), and the Terraform configuration an `azurerm_cosmosdb_sql_role_assignment` resource ([main.tf](./terraform/main.tf)) +- creates the database and the container through Azure Resource Manager, because CosmosDB refuses to let a Microsoft Entra identity create them, whatever its roles + +Without a key, the app passes `DefaultAzureCredential` to `CosmosClient` (see [CosmosActivityStore.cs](./src/Services/CosmosActivityStore.cs)), which gets a token for the web app's managed identity, on Azure and in the emulator alike. With the managed identity, the validation script also checks the role assignment and adds an activity through the web app, finds it on its page and deletes it. On Azure, a new role assignment can take a few minutes to take effect: the app retries its first access to the container for two minutes, and the validation script retries meanwhile. + +By default, the emulator serves the web app's requests whatever role its identity has. Start it with `LS_AZURE_ENFORCE_RBAC=1` to have it authorize each request against the account's role assignments, as Azure does. + ## Test 1. Retrieve the host port Docker maps to the port the Web App listens on in its container, for example with `docker port ` (the container's name starts with `ls-`). Do not assume port 80: the app listens on the port its `WEBSITES_PORT` app setting names, when it has one. diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/README.md b/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/README.md new file mode 100644 index 00000000..68470838 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/README.md @@ -0,0 +1,149 @@ +# Bicep Deployment + +This directory contains the Bicep template and a deployment script for provisioning the sample in LocalStack for Azure or in Azure. Refer to the [Azure Web App with Azure CosmosDB for NoSQL API](../README.md) guide for details about the sample application. + +## Prerequisites + +Before deploying this solution, ensure you have the following tools installed: + +- [LocalStack for Azure](https://docs.localstack.cloud/azure/): Local Azure cloud emulator for development and testing +- [Visual Studio Code](https://code.visualstudio.com/): Code editor installed on one of the [supported platforms](https://code.visualstudio.com/docs/supporting/requirements#_platforms) +- [Bicep extension](https://learn.microsoft.com/en-us/azure/azure-resource-manager/bicep/install#visual-studio-code-and-bicep-extension): VS Code extension for Bicep language support and IntelliSense +- [Docker](https://docs.docker.com/get-docker/): Container runtime required for LocalStack +- [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli): Azure command-line interface, which installs the [Bicep CLI](https://learn.microsoft.com/en-us/azure/azure-resource-manager/bicep/install) on first use +- [lstk CLI](https://docs.localstack.cloud/aws/developer-tools/running-localstack/lstk/): LocalStack command-line interface (proxies the Azure CLI via `lstk az`) +- [.NET SDK 10.0](https://dotnet.microsoft.com/en-us/download/dotnet/10.0): .NET software development kit +- [jq](https://jqlang.org/): JSON processor for scripting and parsing command outputs + +### Installing lstk CLI + +Deploying to LocalStack requires the `lstk` CLI, which routes Azure CLI commands to the emulator (run `lstk az start-interception` before deploying). Install it using Homebrew: + +```bash +brew install localstack/tap/lstk +``` + +or npm: + +```bash +npm install -g @localstack/lstk +``` + +Alternatively, download a pre-built binary from the [lstk releases page](https://github.com/localstack/lstk/releases). For more information, see the [lstk CLI documentation](https://docs.localstack.cloud/aws/developer-tools/running-localstack/lstk/) and the [lstk GitHub repository](https://github.com/localstack/lstk). + +## Architecture Overview + +The [deploy.sh](deploy.sh) script creates the [resource group](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/manage-resource-groups-cli), while [main.bicep](main.bicep) creates the following resources, each through a module in the [modules](modules) folder: + +1. [Azure Cosmos DB for NoSQL account](https://learn.microsoft.com/en-us/azure/cosmos-db/overview) ([cosmos-db.bicep](modules/cosmos-db.bicep)): the account, the `vacationplanner` database, and the `activities` container, partitioned by `/username`, with 400 request units per second. +2. [Managed identity](https://learn.microsoft.com/en-us/entra/identity/managed-identities-azure-resources/overview) ([managed-identity.bicep](modules/managed-identity.bicep)): with `MANAGED_IDENTITY_TYPE=UserAssigned`, the default, a user-assigned identity assigned to the web app. With `MANAGED_IDENTITY_TYPE=SystemAssigned`, the web app's own identity instead, which the web app module enables. +3. [Cosmos DB SQL role assignment](https://learn.microsoft.com/en-us/azure/templates/microsoft.documentdb/databaseaccounts/sqlroleassignments) ([cosmos-db-sql-role-assignment.bicep](modules/cosmos-db-sql-role-assignment.bicep)): grants the identity the [Cosmos DB Built-in Data Contributor](https://learn.microsoft.com/en-us/azure/cosmos-db/reference-data-plane-security#built-in-roles) role on the whole account. It's a role of the Cosmos DB account itself, not an Azure RBAC role. +4. [Azure App Service plan](https://learn.microsoft.com/en-us/azure/app-service/overview-hosting-plans) ([app-service-plan.bicep](modules/app-service-plan.bicep)): a B1 Linux plan that hosts the web app. +5. [Azure Web App](https://learn.microsoft.com/en-us/azure/app-service/overview) ([web-app.bicep](modules/web-app.bicep)): hosts the ASP.NET Core Razor Pages *Vacation Planner* application. Its app settings hold the endpoint of the account and the names of the database and the container, and, for a user-assigned identity, its client id in `AZURE_CLIENT_ID`. They hold no key: the app passes `DefaultAzureCredential` to `CosmosClient`, which gets a token for the web app's managed identity. +6. [Log Analytics workspace](https://learn.microsoft.com/en-us/azure/azure-monitor/logs/log-analytics-workspace-overview) ([log-analytics.bicep](modules/log-analytics.bicep)): stores the telemetry of Application Insights, the logs and metrics that the diagnostic settings send to it, and the audit records of the queries run on it. +7. [Application Insights](https://learn.microsoft.com/en-us/azure/azure-monitor/app/app-insights-overview) ([application-insights.bicep](modules/application-insights.bicep)): a workspace-based resource that collects the requests, the calls to Azure Cosmos DB, the log records, the exceptions, the custom events and the custom metric of the web app. +8. [Diagnostic settings](https://learn.microsoft.com/en-us/azure/azure-monitor/data-collection/diagnostic-settings): send the logs and metrics of the web app, the metrics of the App Service plan, the `DataPlaneRequests` and `ControlPlaneRequests` logs and the `Requests` metrics of the Cosmos DB account (in the resource-specific tables `CDBDataPlaneRequests` and `CDBControlPlaneRequests`), and the query audit of the workspace to the Log Analytics workspace. + +The resources get the same names as with the [Azure CLI scripts](../scripts/README.md), so the scripts in the [scripts](../scripts) folder validate this deployment and query its telemetry, logs and metrics too. + +## Provisioning Scripts + +See [deploy.sh](deploy.sh) for the complete deployment script. The script performs the following operations: + +- Creates the resource group if it doesn't exist +- Validates the Bicep template, or previews its changes with a what-if operation when `USE_WHAT_IF` is set to `1` in the script +- Deploys the Bicep template, with the managed identity type in `MANAGED_IDENTITY_TYPE`: `UserAssigned` (the default) or `SystemAssigned` +- Extracts the deployment outputs (resource names, URLs) using jq +- Packages the web application code into a zip file and deploys it to the web app, which builds it +- Removes the zip file + +## Deployment + +You can set up the Azure emulator by utilizing LocalStack for Azure Docker image. Before starting, ensure you have a valid `LOCALSTACK_AUTH_TOKEN` to access the Azure emulator. Refer to the [Auth Token guide](https://docs.localstack.cloud/getting-started/auth-token/) to obtain your Auth Token and specify it in the `LOCALSTACK_AUTH_TOKEN` environment variable. The Azure Docker image is available on the [LocalStack Docker Hub](https://hub.docker.com/r/localstack/localstack-azure). To pull the Azure Docker image, execute the following command: + +```bash +docker pull localstack/localstack-azure +``` + +Start the LocalStack Azure emulator with the lstk CLI: + +```bash +# Set the authentication token +export LOCALSTACK_AUTH_TOKEN= + +# Start the LocalStack Azure emulator +lstk start --type azure + +# Route all Azure CLI calls to the LocalStack Azure emulator +lstk az start-interception +``` + +Navigate to the `bicep` folder: + +```bash +cd samples/web-app-cosmosdb-nosql-api/dotnet/bicep +``` + +Make the script executable: + +```bash +chmod +x deploy.sh +``` + +Run the deployment script, which gives the web app a user-assigned managed identity: + +```bash +./deploy.sh +``` + +To use the web app's system-assigned managed identity instead, set `MANAGED_IDENTITY_TYPE`: + +```bash +MANAGED_IDENTITY_TYPE=SystemAssigned ./deploy.sh +``` + +The same script deploys the sample to Azure: run `lstk az stop-interception` to route the Azure CLI back to Azure, sign in with `az login`, and run it again. See [Microsoft Entra ID authentication](../README.md#microsoft-entra-id-authentication). + +## Validation + +After deployment, run the validation script of the [scripts](../scripts) folder with the same `MANAGED_IDENTITY_TYPE`: + +```bash +MANAGED_IDENTITY_TYPE=UserAssigned ../scripts/validate.sh +``` + +It shows the resource group, the App Service plan, the web app, the Cosmos DB account, the Log Analytics workspace, the Application Insights component and the resources of the group. It then checks that the managed identity has the Cosmos DB Built-in Data Contributor role on the account, adds an activity through the web app, finds it on the page, and deletes it. On Azure, a new role assignment can take a few minutes to take effect, and the script retries meanwhile. + +## Telemetry, logs and metrics + +Read the telemetry the web app sent to Application Insights and the logs and metrics the diagnostic settings sent to the workspace: + +```bash +../scripts/query-telemetry.sh +../scripts/query-logs-and-metrics.sh +``` + +See [Application Insights](../README.md#application-insights) and [Logs and metrics](../README.md#logs-and-metrics) for what they read. + +## Cleanup + +To destroy all created resources: + +```bash +# Delete resource group and all contained resources +az group delete --name local-rg --yes --no-wait + +# Verify deletion +az group list --output table +``` + +This will remove all Azure resources created by the Bicep template. + +## Related Documentation + +- [Azure Bicep Documentation](https://learn.microsoft.com/en-us/azure/azure-resource-manager/bicep/) +- [Bicep reference for Cosmos DB SQL role assignments](https://learn.microsoft.com/en-us/azure/templates/microsoft.documentdb/databaseaccounts/sqlroleassignments) +- [Connect to Azure Cosmos DB for NoSQL with role-based access control and Microsoft Entra ID](https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-connect-role-based-access-control) +- [LocalStack for Azure Documentation](https://docs.localstack.cloud/azure/) +- [lstk CLI](https://docs.localstack.cloud/aws/developer-tools/running-localstack/lstk/) +- [lstk GitHub repository](https://github.com/localstack/lstk) diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/deploy.sh b/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/deploy.sh new file mode 100755 index 00000000..c4f2159d --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/deploy.sh @@ -0,0 +1,188 @@ +#!/bin/bash + +# Variables +PREFIX="${PREFIX:-local}" +SUFFIX="${SUFFIX:-test}" +TEMPLATE="main.bicep" +PARAMETERS="main.bicepparam" +RESOURCE_GROUP_NAME="$PREFIX-rg" +LOCATION="westeurope" +VALIDATE_TEMPLATE=1 +USE_WHAT_IF=0 +SUBSCRIPTION_NAME=$(az account show --query name --output tsv) +CURRENT_DIR="$(cd "$(dirname "$0")" && pwd)" + +# The web app reaches the Cosmos DB account with Microsoft Entra ID, as a managed identity granted the Cosmos DB +# Built-in Data Contributor role on the account: no key appears anywhere. UserAssigned (the default) creates a +# user-assigned identity and assigns it to the web app; SystemAssigned enables the web app's own identity. +MANAGED_IDENTITY_TYPE="${MANAGED_IDENTITY_TYPE:-UserAssigned}" + +case "$MANAGED_IDENTITY_TYPE" in +SystemAssigned | UserAssigned) ;; +*) + echo "MANAGED_IDENTITY_TYPE must be SystemAssigned or UserAssigned, not [$MANAGED_IDENTITY_TYPE]." + exit 1 + ;; +esac + +# Change the current directory to the script's directory +cd "$CURRENT_DIR" || exit + +# Validates if the resource group exists in the subscription, if not creates it +echo "Checking if resource group [$RESOURCE_GROUP_NAME] exists in the subscription [$SUBSCRIPTION_NAME]..." +az group show --name $RESOURCE_GROUP_NAME &>/dev/null + +if [[ $? != 0 ]]; then + echo "No resource group [$RESOURCE_GROUP_NAME] exists in the subscription [$SUBSCRIPTION_NAME]" + echo "Creating resource group [$RESOURCE_GROUP_NAME] in the subscription [$SUBSCRIPTION_NAME]..." + + # Create the resource group + az group create \ + --name $RESOURCE_GROUP_NAME \ + --location $LOCATION \ + --only-show-errors 1>/dev/null + + if [[ $? == 0 ]]; then + echo "Resource group [$RESOURCE_GROUP_NAME] successfully created in the subscription [$SUBSCRIPTION_NAME]" + else + echo "Failed to create resource group [$RESOURCE_GROUP_NAME] in the subscription [$SUBSCRIPTION_NAME]" + exit 1 + fi +else + echo "Resource group [$RESOURCE_GROUP_NAME] already exists in the subscription [$SUBSCRIPTION_NAME]" +fi + +# Validates the Bicep template +if [[ $VALIDATE_TEMPLATE == 1 ]]; then + if [[ $USE_WHAT_IF == 1 ]]; then + # Execute a deployment What-If operation at resource group scope. + echo "Previewing changes deployed by Bicep template [$TEMPLATE]..." + az deployment group what-if \ + --resource-group $RESOURCE_GROUP_NAME \ + --template-file $TEMPLATE \ + --parameters $PARAMETERS \ + --parameters location=$LOCATION \ + prefix=$PREFIX \ + suffix=$SUFFIX \ + managedIdentityType=$MANAGED_IDENTITY_TYPE \ + --only-show-errors + + if [[ $? == 0 ]]; then + echo "Bicep template [$TEMPLATE] validation succeeded" + else + echo "Failed to validate Bicep template [$TEMPLATE]" + exit 1 + fi + else + # Validate the Bicep template + echo "Validating Bicep template [$TEMPLATE]..." + output=$(az deployment group validate \ + --resource-group $RESOURCE_GROUP_NAME \ + --template-file $TEMPLATE \ + --parameters $PARAMETERS \ + --parameters location=$LOCATION \ + prefix=$PREFIX \ + suffix=$SUFFIX \ + managedIdentityType=$MANAGED_IDENTITY_TYPE \ + --only-show-errors) + + if [[ $? == 0 ]]; then + echo "Bicep template [$TEMPLATE] validation succeeded" + else + echo "Failed to validate Bicep template [$TEMPLATE]" + echo "$output" + exit 1 + fi + fi +fi + +# Deploy the Bicep template +echo "Deploying Bicep template [$TEMPLATE] with a [$MANAGED_IDENTITY_TYPE] managed identity..." +if DEPLOYMENT_OUTPUTS=$(az deployment group create \ + --resource-group $RESOURCE_GROUP_NAME \ + --only-show-errors \ + --template-file $TEMPLATE \ + --parameters $PARAMETERS \ + --parameters location=$LOCATION \ + prefix=$PREFIX \ + suffix=$SUFFIX \ + managedIdentityType=$MANAGED_IDENTITY_TYPE \ + --query 'properties.outputs' -o json); then + echo "Bicep template [$TEMPLATE] deployed successfully. Outputs:" + echo "$DEPLOYMENT_OUTPUTS" | jq . + APP_SERVICE_PLAN_NAME=$(echo "$DEPLOYMENT_OUTPUTS" | jq -r '.appServicePlanName.value') + WEB_APP_NAME=$(echo "$DEPLOYMENT_OUTPUTS" | jq -r '.webAppName.value') + WEB_APP_URL=$(echo "$DEPLOYMENT_OUTPUTS" | jq -r '.webAppUrl.value') + COSMOSDB_ACCOUNT_NAME=$(echo "$DEPLOYMENT_OUTPUTS" | jq -r '.cosmosDbAccountName.value') + COSMOSDB_ENDPOINT=$(echo "$DEPLOYMENT_OUTPUTS" | jq -r '.cosmosDbEndpoint.value') + PRINCIPAL_ID=$(echo "$DEPLOYMENT_OUTPUTS" | jq -r '.principalId.value') + echo "Deployment details:" + echo "- appServicePlanName: $APP_SERVICE_PLAN_NAME" + echo "- webAppName: $WEB_APP_NAME" + echo "- webAppUrl: $WEB_APP_URL" + echo "- cosmosDbAccountName: $COSMOSDB_ACCOUNT_NAME" + echo "- cosmosDbEndpoint: $COSMOSDB_ENDPOINT" + echo "- principalId of the [$MANAGED_IDENTITY_TYPE] managed identity: $PRINCIPAL_ID" +else + echo "Failed to deploy Bicep template [$TEMPLATE]" + exit 1 +fi + +# Validation before deploying the web app +if [[ -z "$WEB_APP_NAME" || "$WEB_APP_NAME" == "null" ]]; then + echo "Web App Name is empty. Exiting." + exit 1 +fi + +# The zip package is named after the web app, so deployments with different prefixes don't overwrite each other's +ZIPFILE="${WEB_APP_NAME}.zip" + +# CD into the web app directory +cd ../src || exit + +# Remove any existing zip package of the web app +if [ -f "$ZIPFILE" ]; then + rm "$ZIPFILE" +fi + +# Create the zip package of the web app +echo "Creating zip package of the web app..." +zip -r "$ZIPFILE" . -x "bin/*" "obj/*" "publish/*" "*.zip" + +# Deploy the web app +echo "Deploying web app [$WEB_APP_NAME] with zip file [$ZIPFILE]..." +# On Azure the deployment service can answer 504 Gateway Timeout while it warms up, or DeploymentInProgress while +# the build of the previous deployment still runs: the upload is tried again. The startup of the site isn't +# tracked: the tracking counted a failed start of the container that ran before the code was deployed, and +# reported a running site as failed after ten minutes; what calls the web app afterwards waits for it instead. +WEBAPP_DEPLOY_RETRY_COUNT="${WEBAPP_DEPLOY_RETRY_COUNT:-10}" +WEBAPP_DEPLOY_RETRY_SLEEP="${WEBAPP_DEPLOY_RETRY_SLEEP:-30}" +WEBAPP_DEPLOYED=0 +for ATTEMPT in $(seq 1 "$WEBAPP_DEPLOY_RETRY_COUNT"); do + if az webapp deploy \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --name "$WEB_APP_NAME" \ + --src-path "$ZIPFILE" \ + --type zip \ + --async true \ + --track-status false 1>/dev/null; then + WEBAPP_DEPLOYED=1 + break + fi + if [ "$ATTEMPT" -lt "$WEBAPP_DEPLOY_RETRY_COUNT" ]; then + echo "Attempt $ATTEMPT of $WEBAPP_DEPLOY_RETRY_COUNT to deploy web app [$WEB_APP_NAME] failed. Waiting [$WEBAPP_DEPLOY_RETRY_SLEEP] seconds before retry..." + sleep "$WEBAPP_DEPLOY_RETRY_SLEEP" + fi +done + +if [ $WEBAPP_DEPLOYED -eq 1 ]; then + echo "Web app [$WEB_APP_NAME] deployed successfully." +else + echo "Failed to deploy web app [$WEB_APP_NAME]." + exit 1 +fi + +# Remove the zip package of the web app +if [ -f "$ZIPFILE" ]; then + rm "$ZIPFILE" +fi diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/main.bicep b/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/main.bicep new file mode 100644 index 00000000..620fe0e8 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/main.bicep @@ -0,0 +1,325 @@ +@description('Specifies the prefix for the name of the Azure resources.') +@minLength(2) +param prefix string = take(uniqueString(resourceGroup().id), 4) + +@description('Specifies the suffix for the name of the Azure resources.') +@minLength(2) +param suffix string = take(uniqueString(resourceGroup().id), 4) + +@description('Specifies the location for all resources.') +param location string = resourceGroup().location + +@description('Specifies the tier name for the hosting plan.') +@allowed([ + 'Basic' + 'Standard' + 'ElasticPremium' + 'Premium' + 'PremiumV2' + 'Premium0V3' + 'PremiumV3' + 'PremiumMV3' + 'Isolated' + 'IsolatedV2' + 'WorkflowStandard' + 'FlexConsumption' +]) +param skuTier string = 'Basic' + +@description('Specifies the SKU name for the hosting plan.') +@allowed([ + 'B1' + 'B2' + 'B3' + 'S1' + 'S2' + 'S3' + 'EP1' + 'EP2' + 'EP3' + 'P1' + 'P2' + 'P3' + 'P1V2' + 'P2V2' + 'P3V2' + 'P0V3' + 'P1V3' + 'P2V3' + 'P3V3' + 'P1MV3' + 'P2MV3' + 'P3MV3' + 'P4MV3' + 'P5MV3' + 'I1' + 'I2' + 'I3' + 'I1V2' + 'I2V2' + 'I3V2' + 'I4V2' + 'I5V2' + 'I6V2' + 'WS1' + 'WS2' + 'WS3' + 'FC1' +]) +param skuName string = 'B1' + +@description('Specifies the kind of the hosting plan.') +@allowed([ + 'app' + 'elastic' + 'functionapp' + 'windows' + 'linux' +]) +param appServicePlanKind string = 'linux' + +@description('Specifies whether the hosting plan is reserved.') +param reserved bool = true + +@description('Specifies whether the hosting plan is zone redundant.') +param appServicePlanZoneRedundant bool = false + +@description('Specifies the language runtime used by the Azure Web App.') +@allowed([ + 'dotnet' + 'dotnetcore' + 'dotnet-isolated' + 'python' + 'java' + 'node' + 'powerShell' + 'custom' +]) +param runtimeName string + +@description('Specifies the target language version used by the Azure Web App.') +param runtimeVersion string + +@description('Specifies the kind of the hosting plan.') +@allowed([ + 'app' // Windows Web app + 'app,linux' // Linux Web app + 'app,linux,container' // Linux Container Web app + 'hyperV' // Windows Container Web App + 'app,container,windows' // Windows Container Web App + 'app,linux,kubernetes' // Linux Web App on ARC + 'app,linux,container,kubernetes' // Linux Container Web App on ARC + 'functionapp' // Function Code App + 'functionapp,linux' // Linux Consumption Function app + 'functionapp,linux,container,kubernetes' // Function Container App on ARC + 'functionapp,linux,kubernetes' // Function Code App on ARC +]) +param webAppKind string = 'app,linux' + +@description('Specifies whether HTTPS is enforced for the Azure Web App.') +param httpsOnly bool = false + +@description('Specifies the minimum TLS version for the Azure Web App.') +@allowed([ + '1.0' + '1.1' + '1.2' + '1.3' +]) +param minTlsVersion string = '1.2' + +@description('Specifies whether the public network access is enabled or disabled') +@allowed([ + 'Enabled' + 'Disabled' +]) +param publicNetworkAccess string = 'Enabled' + +@description('Specifies the optional Git Repo URL.') +param repoUrl string = '' + +@description('Specifies the tags to be applied to the resources.') +param tags object = { + environment: 'test' + iac: 'bicep' +} + +@description('Specifies the name of the Cosmos DB for NoSQL database.') +param databaseName string = 'vacationplanner' + +@description('Specifies the name of the container that holds the activities.') +param containerName string = 'activities' + +@description('Specifies the partition key path of the container.') +param partitionKeyPath string = '/username' + +@description('Specifies the throughput of the container, in request units per second.') +param containerThroughput int = 400 + +@description('Specifies the type of managed identity the web app reaches the Cosmos DB account with, through Microsoft Entra ID.') +@allowed([ + 'SystemAssigned' + 'UserAssigned' +]) +param managedIdentityType string = 'UserAssigned' + +@description('Specifies the name of the diagnostic settings of the web app and of the App Service plan.') +param diagnosticSettingsName string = 'default' + +@description('Specifies the log categories that the diagnostic settings of the web app send to the Log Analytics workspace.') +param logCategories array = [ + 'AppServiceHTTPLogs' + 'AppServiceConsoleLogs' + 'AppServiceAppLogs' + 'AppServiceAuditLogs' + 'AppServiceIPSecAuditLogs' + 'AppServicePlatformLogs' + 'AppServiceAuthenticationLogs' +] + +@description('Specifies the metric categories that the diagnostic settings of the web app and of the App Service plan send to the Log Analytics workspace.') +param metricCategories array = [ + 'AllMetrics' +] + +//******************************************** +// Variables +//******************************************** +// The names the Azure CLI scripts of this sample give the same resources, so the scripts in ../scripts that validate +// the deployment and query its telemetry, logs and metrics work on this deployment too +var webAppName = '${prefix}-webapp-nosql-${suffix}' +var appServicePlanName = webAppName +var cosmosDbAccountName = webAppName +var managedIdentityName = '${prefix}-webapp-nosql-identity-${suffix}' +var logAnalyticsName = '${prefix}-log-analytics-${suffix}' +var applicationInsightsName = '${prefix}-insights-${suffix}' + +// The id of the Cosmos DB Built-in Data Contributor role, a data-plane role every Cosmos DB for NoSQL account has +// under this id. It is a role of the account (a SQL role definition), not an Azure RBAC role. +var cosmosDbDataContributorRoleDefinitionId = '00000000-0000-0000-0000-000000000002' + +//******************************************** +// Modules +//******************************************** +module workspace 'modules/log-analytics.bicep' = { + name: 'workspace' + params: { + name: logAnalyticsName + location: location + tags: tags + } +} + +module applicationInsights 'modules/application-insights.bicep' = { + name: 'applicationInsights' + params: { + name: applicationInsightsName + location: location + workspaceId: workspace.outputs.id + tags: tags + } +} + +module cosmosDb 'modules/cosmos-db.bicep' = { + name: 'cosmosDb' + params: { + name: cosmosDbAccountName + location: location + databaseName: databaseName + containerName: containerName + partitionKeyPath: partitionKeyPath + throughput: containerThroughput + diagnosticSettingsName: diagnosticSettingsName + workspaceId: workspace.outputs.id + tags: tags + } +} + +module managedIdentity 'modules/managed-identity.bicep' = if (managedIdentityType == 'UserAssigned') { + name: 'managedIdentity' + params: { + name: managedIdentityName + location: location + tags: tags + } +} + +module appServicePlan 'modules/app-service-plan.bicep' = { + name: 'appServicePlan' + params: { + name: appServicePlanName + location: location + skuTier: skuTier + skuName: skuName + kind: appServicePlanKind + reserved: reserved + zoneRedundant: appServicePlanZoneRedundant + maximumElasticWorkerCount: skuTier == 'FlexConsumption' ? 1 : 20 + diagnosticSettingsName: diagnosticSettingsName + metricCategories: metricCategories + workspaceId: workspace.outputs.id + tags: tags + } +} + +// The package holds the source code, so the deployment builds it. The web app reaches the Cosmos DB account with +// DefaultAzureCredential as its managed identity, so no key is set anywhere: for a user-assigned identity, +// AZURE_CLIENT_ID tells DefaultAzureCredential which identity to use. +module webApp 'modules/web-app.bicep' = { + name: 'webApp' + params: { + name: webAppName + location: location + kind: webAppKind + runtimeName: runtimeName + runtimeVersion: runtimeVersion + httpsOnly: httpsOnly + minTlsVersion: minTlsVersion + publicNetworkAccess: publicNetworkAccess + identityType: managedIdentityType + managedIdentityId: managedIdentityType == 'UserAssigned' ? managedIdentity!.outputs.id : '' + hostingPlanName: appServicePlan.outputs.name + appSettings: union( + { + SCM_DO_BUILD_DURING_DEPLOYMENT: 'true' + ENABLE_ORYX_BUILD: 'true' + AZURECOSMOSDB_ENDPOINT: cosmosDb.outputs.documentEndpoint + AZURECOSMOSDB_DATABASENAME: cosmosDb.outputs.databaseName + AZURECOSMOSDB_CONTAINERNAME: cosmosDb.outputs.containerName + APPLICATIONINSIGHTS_CONNECTION_STRING: applicationInsights.outputs.connectionString + }, + managedIdentityType == 'UserAssigned' ? { AZURE_CLIENT_ID: managedIdentity!.outputs.clientId } : {} + ) + repoUrl: repoUrl + diagnosticSettingsName: diagnosticSettingsName + logCategories: logCategories + metricCategories: metricCategories + workspaceId: workspace.outputs.id + tags: tags + } +} + +// The web app's identity reads and writes the activities in the container: the system-assigned identity exists only +// once the web app does, so the role is assigned after the web app is created. +module cosmosDbDataContributorRoleAssignment 'modules/cosmos-db-sql-role-assignment.bicep' = { + name: 'cosmosDbDataContributorRoleAssignment' + params: { + cosmosDbAccountName: cosmosDb.outputs.name + roleDefinitionId: cosmosDbDataContributorRoleDefinitionId + principalId: managedIdentityType == 'SystemAssigned' ? webApp.outputs.principalId : managedIdentity!.outputs.principalId + } +} + +//******************************************** +// Outputs +//******************************************** +output appServicePlanName string = appServicePlan.outputs.name +output webAppName string = webApp.outputs.name +output webAppUrl string = webApp.outputs.defaultHostName +output cosmosDbAccountName string = cosmosDb.outputs.name +output cosmosDbEndpoint string = cosmosDb.outputs.documentEndpoint +output databaseName string = cosmosDb.outputs.databaseName +output containerName string = cosmosDb.outputs.containerName +output principalId string = managedIdentityType == 'SystemAssigned' ? webApp.outputs.principalId : managedIdentity!.outputs.principalId +output logAnalyticsName string = workspace.outputs.name +output applicationInsightsName string = applicationInsights.outputs.name diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/main.bicepparam b/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/main.bicepparam new file mode 100644 index 00000000..d86b0215 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/main.bicepparam @@ -0,0 +1,6 @@ +using 'main.bicep' + +param prefix = 'local' +param suffix = 'test' +param runtimeName = 'dotnetcore' +param runtimeVersion = '10.0' diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/modules/app-service-plan.bicep b/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/modules/app-service-plan.bicep new file mode 100644 index 00000000..3fab18c1 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/modules/app-service-plan.bicep @@ -0,0 +1,155 @@ +//******************************************** +// Parameters +//******************************************** +@description('Specifies the name of the App Service Plan.') +param name string + +@description('Specifies the location.') +param location string = resourceGroup().location + +@description('Specifies the tier name for the hosting plan.') +@allowed([ + 'Basic' + 'Standard' + 'ElasticPremium' + 'Premium' + 'PremiumV2' + 'Premium0V3' + 'PremiumV3' + 'PremiumMV3' + 'Isolated' + 'IsolatedV2' + 'WorkflowStandard' + 'FlexConsumption' +]) +param skuTier string = 'Standard' + +@description('Specifies the SKU name for the hosting plan.') +@allowed([ + 'B1' + 'B2' + 'B3' + 'S1' + 'S2' + 'S3' + 'EP1' + 'EP2' + 'EP3' + 'P1' + 'P2' + 'P3' + 'P1V2' + 'P2V2' + 'P3V2' + 'P0V3' + 'P1V3' + 'P2V3' + 'P3V3' + 'P1MV3' + 'P2MV3' + 'P3MV3' + 'P4MV3' + 'P5MV3' + 'I1' + 'I2' + 'I3' + 'I1V2' + 'I2V2' + 'I3V2' + 'I4V2' + 'I5V2' + 'I6V2' + 'WS1' + 'WS2' + 'WS3' + 'FC1' +]) +param skuName string = 'S1' + +@description('Specifies the kind of the hosting plan.') +@allowed([ + 'app' + 'elastic' + 'functionapp' + 'windows' + 'linux' +]) +param kind string = 'linux' + +@description('Specifies whether the hosting plan is reserved.') +param reserved bool = true + +@description('Specifies whether the hosting plan is zone redundant.') +param zoneRedundant bool = false + +@description('Specifies the maximum number of elastic workers of the hosting plan.') +param maximumElasticWorkerCount int = 20 + +@description('Specifies the name of the diagnostic settings.') +param diagnosticSettingsName string = 'default' + +@description('Specifies the log categories enabled by the diagnostic settings.') +param logCategories array = [] + +@description('Specifies the metric categories enabled by the diagnostic settings.') +param metricCategories array = [ + 'AllMetrics' +] + +@description('Specifies the resource id of the Log Analytics workspace.') +param workspaceId string + +@description('Specifies the tags to be applied to the resources.') +param tags object = {} + +//******************************************** +// Variables +//******************************************** + +var logs = [ + for category in logCategories: { + category: category + enabled: true + } +] +var metrics = [ + for category in metricCategories: { + category: category + enabled: true + } +] + +//******************************************** +// Resources +//******************************************** +resource appServicePlan 'Microsoft.Web/serverfarms@2024-11-01' = { + name: name + location: location + tags: tags + kind: kind + sku: { + tier: skuTier + name: skuName + } + properties: { + reserved: reserved + zoneRedundant: zoneRedundant + maximumElasticWorkerCount: maximumElasticWorkerCount + } +} + +resource diagnosticSettings 'Microsoft.Insights/diagnosticSettings@2021-05-01-preview' = if(!empty(workspaceId)) { + name: diagnosticSettingsName + scope: appServicePlan + properties: { + workspaceId: workspaceId + logs: logs + metrics: metrics + } +} + +//******************************************** +// Outputs +//******************************************** +output id string = appServicePlan.id +output name string = appServicePlan.name diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/modules/application-insights.bicep b/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/modules/application-insights.bicep new file mode 100644 index 00000000..9fe2907f --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/modules/application-insights.bicep @@ -0,0 +1,79 @@ +//******************************************** +// Parameters +//******************************************** + +@description('Specifies the name of the Azure Application Insights.') +param name string + +@description('Specifies the location.') +param location string = resourceGroup().location + +@description('Specifies the type of application being monitored.') +@allowed([ + 'web' + 'other' +]) +param applicationType string = 'web' + +@description('Specifies whether IP masking is enabled.') +param disableIpMasking bool = false + +@description('Specifies whether the application is enabled for local authentication.') +param disableLocalAuth bool = false + +@description('Specifies whether purging data immediately after 30 days.') +param immediatePurgeDataOn30Days bool = true + +@description('Specifies the network access type for accessing Application Insights ingestion.') +@allowed([ + 'Enabled' + 'Disabled' +]) +param publicNetworkAccessForIngestion string = 'Enabled' + +@description('Specifies the network access type for accessing Application Insights query.') +@allowed([ + 'Enabled' + 'Disabled' +]) +param publicNetworkAccessForQuery string = 'Enabled' + +@description('Specifies the Azure Log Analytics workspace ID.') +param workspaceId string + +@description('Specifies the resource tags.') +param tags object + +//******************************************** +// Resources +//******************************************** + +// The component has no diagnostic settings: its telemetry is already stored in the workspace it's based on, and a +// diagnostic setting of a workspace-based component can't send to that workspace. +resource applicationInsights 'Microsoft.Insights/components@2020-02-02' = { + name: name + location: location + tags: tags + kind: 'web' + properties: { + Application_Type: applicationType + DisableIpMasking: disableIpMasking + DisableLocalAuth: disableLocalAuth + Flow_Type: 'Bluefield' + ImmediatePurgeDataOn30Days: immediatePurgeDataOn30Days + IngestionMode: 'LogAnalytics' + publicNetworkAccessForIngestion: publicNetworkAccessForIngestion + publicNetworkAccessForQuery: publicNetworkAccessForQuery + Request_Source: 'rest' + WorkspaceResourceId: workspaceId + } +} + +//******************************************** +// Outputs +//******************************************** + +output id string = applicationInsights.id +output name string = applicationInsights.name +output connectionString string = applicationInsights.properties.ConnectionString +output instrumentationKey string = applicationInsights.properties.InstrumentationKey diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/modules/cosmos-db-sql-role-assignment.bicep b/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/modules/cosmos-db-sql-role-assignment.bicep new file mode 100644 index 00000000..f34a691b --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/modules/cosmos-db-sql-role-assignment.bicep @@ -0,0 +1,42 @@ +//******************************************** +// Parameters +//******************************************** +@description('Specifies the name of the Azure Cosmos DB for NoSQL account the role is assigned on.') +param cosmosDbAccountName string + +@description('Specifies the id of the SQL role definition to assign: 00000000-0000-0000-0000-000000000001 for Cosmos DB Built-in Data Reader, 00000000-0000-0000-0000-000000000002 for Cosmos DB Built-in Data Contributor.') +param roleDefinitionId string + +@description('Specifies the principal (object) id the role is assigned to. For a managed identity, this is its principal id, never its client id.') +param principalId string + +//******************************************** +// Resources +//******************************************** +resource account 'Microsoft.DocumentDB/databaseAccounts@2025-04-15' existing = { + name: cosmosDbAccountName +} + +resource roleDefinition 'Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions@2025-04-15' existing = { + parent: account + name: roleDefinitionId +} + +// A Cosmos DB data role is assigned with a SQL role assignment of the account, not with an Azure RBAC role assignment. +// The name is derived from the account, the principal and the role, so a second deployment updates the same +// assignment instead of creating a duplicate. The scope is the whole account: every database and container in it. +resource roleAssignment 'Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments@2025-04-15' = { + parent: account + name: guid(account.id, principalId, roleDefinition.id) + properties: { + roleDefinitionId: roleDefinition.id + principalId: principalId + scope: account.id + } +} + +//******************************************** +// Outputs +//******************************************** +output id string = roleAssignment.id +output name string = roleAssignment.name diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/modules/cosmos-db.bicep b/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/modules/cosmos-db.bicep new file mode 100644 index 00000000..cc3c7d8e --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/modules/cosmos-db.bicep @@ -0,0 +1,128 @@ +//******************************************** +// Parameters +//******************************************** +@description('Specifies the name of the Azure Cosmos DB for NoSQL account.') +param name string + +@description('Specifies the location of the Azure Cosmos DB account.') +param location string = resourceGroup().location + +@description('Specifies the name of the Cosmos DB for NoSQL database.') +param databaseName string + +@description('Specifies the name of the container.') +param containerName string + +@description('Specifies the partition key path of the container.') +param partitionKeyPath string + +@description('Specifies the throughput of the container, in request units per second.') +param throughput int = 400 + +@description('Specifies the resource id of the Log Analytics workspace.') +param workspaceId string + +@description('Specifies the name of the diagnostic settings of the Azure Cosmos DB account.') +param diagnosticSettingsName string = 'default' + +@description('Specifies the log categories that the diagnostic settings send to the Log Analytics workspace: the requests of the web app (DataPlaneRequests) and the requests Azure Resource Manager sends to the account (ControlPlaneRequests).') +param logCategories array = [ + 'DataPlaneRequests' + 'ControlPlaneRequests' +] + +@description('Specifies the metric categories that the diagnostic settings send to the Log Analytics workspace.') +param metricCategories array = [ + 'Requests' +] + +@description('Specifies the resource tags.') +param tags object + +//******************************************** +// Resources +//******************************************** +resource account 'Microsoft.DocumentDB/databaseAccounts@2025-04-15' = { + name: name + location: location + kind: 'GlobalDocumentDB' + tags: tags + properties: { + databaseAccountOfferType: 'Standard' + consistencyPolicy: { + defaultConsistencyLevel: 'Session' + } + locations: [ + { + locationName: location + failoverPriority: 0 + isZoneRedundant: false + } + ] + } +} + +// Created after the diagnostic settings, so the ControlPlaneRequests log records the creation of the database and of +// the container +resource database 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases@2025-04-15' = { + parent: account + name: databaseName + dependsOn: [ + diagnosticSettings + ] + properties: { + resource: { + id: databaseName + } + } +} + +resource container 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers@2025-04-15' = { + parent: database + name: containerName + properties: { + resource: { + id: containerName + partitionKey: { + paths: [ + partitionKeyPath + ] + kind: 'Hash' + } + } + options: { + throughput: throughput + } + } +} + +// The logs go to resource-specific tables (CDBDataPlaneRequests, CDBControlPlaneRequests) rather than AzureDiagnostics +resource diagnosticSettings 'Microsoft.Insights/diagnosticSettings@2021-05-01-preview' = { + name: diagnosticSettingsName + scope: account + properties: { + workspaceId: workspaceId + logAnalyticsDestinationType: 'Dedicated' + logs: [ + for category in logCategories: { + category: category + enabled: true + } + ] + metrics: [ + for category in metricCategories: { + category: category + enabled: true + } + ] + } +} + +//******************************************** +// Outputs +//******************************************** +output id string = account.id +output name string = account.name +output documentEndpoint string = account.properties.documentEndpoint +output databaseName string = database.name +output containerName string = container.name diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/modules/log-analytics.bicep b/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/modules/log-analytics.bicep new file mode 100644 index 00000000..2096fc03 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/modules/log-analytics.bicep @@ -0,0 +1,85 @@ +//******************************************** +// Parameters +//******************************************** +@description('Specifies the name of the Log Analytics workspace.') +param name string + +@description('Specifies the location.') +param location string = resourceGroup().location + +@description('Specifies the service tier of the workspace: Free, Standalone, PerNode, Per-GB.') +@allowed([ + 'Free' + 'Standalone' + 'PerNode' + 'PerGB2018' +]) +param sku string = 'PerGB2018' + +@description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') +param retentionInDays int = 60 + +@description('Specifies the name of the diagnostic settings of the workspace.') +param diagnosticSettingsName string = 'default' + +@description('Specifies the log categories that the diagnostic settings of the workspace send to the workspace itself. Audit records the queries run on the workspace in the LAQueryLogs table.') +param logCategories array = [ + 'Audit' +] + +@description('Specifies the metric categories that the diagnostic settings of the workspace send to the workspace itself.') +param metricCategories array = [ + 'AllMetrics' +] + +@description('Specifies the resource tags.') +param tags object + +//******************************************** +// Variables +//******************************************** +var logs = [ + for category in logCategories: { + category: category + enabled: true + } +] +var metrics = [ + for category in metricCategories: { + category: category + enabled: true + } +] + +//******************************************** +// Resources +//******************************************** +resource workspace 'Microsoft.OperationalInsights/workspaces@2025-07-01' = { + name: name + tags: tags + location: location + properties: { + sku: { + name: sku + } + retentionInDays: retentionInDays + } +} + +// Query auditing: the diagnostic settings of a workspace can send its audit records to the workspace itself. +resource diagnosticSettings 'Microsoft.Insights/diagnosticSettings@2021-05-01-preview' = { + name: diagnosticSettingsName + scope: workspace + properties: { + workspaceId: workspace.id + logs: logs + metrics: metrics + } +} + +//******************************************** +// Outputs +//******************************************** +output id string = workspace.id +output name string = workspace.name +output customerId string = workspace.properties.customerId diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/modules/managed-identity.bicep b/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/modules/managed-identity.bicep new file mode 100644 index 00000000..7663dd52 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/modules/managed-identity.bicep @@ -0,0 +1,31 @@ +//******************************************** +// Parameters +//******************************************** +@description('Specifies the name of the user-assigned managed identity.') +param name string + +@description('Specifies the location.') +param location string = resourceGroup().location + +@description('Specifies the resource tags.') +param tags object + +//******************************************** +// Resources +//******************************************** + +// The identity the web app uses to access the storage account. The role assignment lives in the +// storage-account-role-assignment module. +resource managedIdentity 'Microsoft.ManagedIdentity/userAssignedIdentities@2023-01-31' = { + name: name + location: location + tags: tags +} + +//******************************************** +// Outputs +//******************************************** +output id string = managedIdentity.id +output name string = managedIdentity.name +output clientId string = managedIdentity.properties.clientId +output principalId string = managedIdentity.properties.principalId diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/modules/web-app.bicep b/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/modules/web-app.bicep new file mode 100644 index 00000000..6c1f0028 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/bicep/modules/web-app.bicep @@ -0,0 +1,193 @@ +//******************************************** +// Parameters +//******************************************** + +@description('Specifies a globally unique name the Azure Web App.') +param name string + +@description('Specifies the location.') +param location string = resourceGroup().location + +@description('Specifies the kind of the Azure Web App.') +@allowed([ + 'app' // Windows Web app + 'app,linux' // Linux Web app + 'app,linux,container' // Linux Container Web app + 'hyperV' // Windows Container Web App + 'app,container,windows' // Windows Container Web App + 'app,linux,kubernetes' // Linux Web App on ARC + 'app,linux,container,kubernetes' // Linux Container Web App on ARC + 'functionapp' // Function Code App + 'functionapp,linux' // Linux Consumption Function app + 'functionapp,linux,container,kubernetes' // Function Container App on ARC + 'functionapp,linux,kubernetes' // Function Code App on ARC +]) +param kind string = 'app,linux' + +@description('Specifies the language runtime used by the Azure Web App.') +@allowed([ + 'dotnet' + 'dotnetcore' + 'dotnet-isolated' + 'python' + 'java' + 'node' + 'powerShell' + 'custom' +]) +param runtimeName string + +@description('Specifies the target language version used by the Azure Web App.') +param runtimeVersion string + +@description('Specifies the minimum TLS version for the Azure Web App.') +@allowed([ + '1.0' + '1.1' + '1.2' + '1.3' +]) +param minTlsVersion string = '1.2' + +@description('Specifies whether the public network access is enabled or disabled') +@allowed([ + 'Enabled' + 'Disabled' +]) +param publicNetworkAccess string = 'Enabled' + +@description('Specifies whether HTTPS is enforced for the Azure Web App.') +param httpsOnly bool = false + +@description('Specifies the type of managed identity of the Azure Web App.') +@allowed([ + 'SystemAssigned' + 'UserAssigned' +]) +param identityType string = 'SystemAssigned' + +@description('Specifies the resource id of the user-assigned managed identity of the Azure Web App. Used only when identityType is UserAssigned.') +param managedIdentityId string = '' + +@description('Specifies the name of the hosting plan.') +param hostingPlanName string + +@description('Specifies the app settings of the Azure Web App.') +param appSettings object = {} + +@description('Specifies the optional Git Repo URL.') +param repoUrl string = '' + +@description('Specifies the branch of the optional Git repository.') +param repoBranch string = 'master' + +@description('Specifies whether the optional Git repository is integrated manually.') +param isManualIntegration bool = true + +@description('Specifies the resource id of the Log Analytics workspace.') +param workspaceId string + +@description('Specifies the name of the diagnostic settings.') +param diagnosticSettingsName string = 'default' + +@description('Specifies the log categories that the diagnostic settings of the Azure Web App send to the Log Analytics workspace.') +param logCategories array = [ + 'AppServiceHTTPLogs' + 'AppServiceConsoleLogs' + 'AppServiceAppLogs' + 'AppServiceAuditLogs' + 'AppServiceIPSecAuditLogs' + 'AppServicePlatformLogs' + 'AppServiceAuthenticationLogs' +] + +@description('Specifies the metric categories that the diagnostic settings of the Azure Web App send to the Log Analytics workspace.') +param metricCategories array = [ + 'AllMetrics' +] + +@description('Specifies the resource tags.') +param tags object + +//******************************************** +// Variables +//******************************************** + +var logs = [ + for category in logCategories: { + category: category + enabled: true + } +] +var metrics = [ + for category in metricCategories: { + category: category + enabled: true + } +] + +//******************************************** +// Resources +//******************************************** + +resource hostingPlan 'Microsoft.Web/serverfarms@2024-11-01' existing = { + name: hostingPlanName +} + +resource webApp 'Microsoft.Web/sites@2024-11-01' = { + name: name + location: location + tags: tags + kind: kind + properties: { + httpsOnly: httpsOnly + serverFarmId: hostingPlan.id + siteConfig: { + linuxFxVersion: toUpper('${runtimeName}|${runtimeVersion}') + minTlsVersion: minTlsVersion + publicNetworkAccess: publicNetworkAccess + } + } + identity: { + type: identityType + userAssignedIdentities: identityType == 'UserAssigned' ? { + '${managedIdentityId}': {} + } : null + } +} + +resource configAppSettings 'Microsoft.Web/sites/config@2024-11-01' = { + parent: webApp + name: 'appsettings' + properties: appSettings +} + +resource webAppSourceControl 'Microsoft.Web/sites/sourcecontrols@2024-11-01' = if (contains(repoUrl, 'http')) { + name: 'web' + parent: webApp + properties: { + repoUrl: repoUrl + branch: repoBranch + isManualIntegration: isManualIntegration + } +} + +resource diagnosticSettings 'Microsoft.Insights/diagnosticSettings@2021-05-01-preview' = if (!empty(workspaceId)) { + name: diagnosticSettingsName + scope: webApp + properties: { + workspaceId: workspaceId + logs: logs + metrics: metrics + } +} + +//******************************************** +// Outputs +//******************************************** +output id string = webApp.id +output name string = webApp.name +output defaultHostName string = webApp.properties.defaultHostName +// The principal id of the system-assigned identity, the value its role assignments are keyed on; empty for a +// user-assigned identity, whose principal id comes from the managed identity module. +output principalId string = identityType == 'SystemAssigned' ? webApp.identity.principalId : '' diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/scripts/README.md b/samples/web-app-cosmosdb-nosql-api/dotnet/scripts/README.md index c897ab3b..d15dbbaf 100644 --- a/samples/web-app-cosmosdb-nosql-api/dotnet/scripts/README.md +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/scripts/README.md @@ -69,6 +69,15 @@ Run the deployment script: ./deploy.sh ``` +By default, the web app reaches the CosmosDB account with its primary key. To have it authenticate with Microsoft Entra ID instead, as a managed identity with the Cosmos DB Built-in Data Contributor role on the account, set `MANAGED_IDENTITY_TYPE` to `SystemAssigned` or `UserAssigned`, and pass the same value to the validation script: + +```bash +MANAGED_IDENTITY_TYPE=UserAssigned ./deploy.sh +MANAGED_IDENTITY_TYPE=UserAssigned ./validate.sh +``` + +See [Microsoft Entra ID authentication](../README.md#microsoft-entra-id-authentication). + ## Validation After deployment, you can use the `validate.sh` script to verify that all resources were created and configured correctly: diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/scripts/deploy.sh b/samples/web-app-cosmosdb-nosql-api/dotnet/scripts/deploy.sh index 7464be6f..57fd7ec3 100755 --- a/samples/web-app-cosmosdb-nosql-api/dotnet/scripts/deploy.sh +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/scripts/deploy.sh @@ -21,11 +21,79 @@ AZURECOSMOSDB_DATABASENAME="${AZURECOSMOSDB_DATABASENAME:-vacationplanner}" AZURECOSMOSDB_CONTAINERNAME="${AZURECOSMOSDB_CONTAINERNAME:-activities}" AURECOSMOSDB_PARTITION_KEY="/username" +# By default the web app reaches the Cosmos DB account with the account's primary key, which it gets in the +# AZURECOSMOSDB_PRIMARY_KEY app setting. Set MANAGED_IDENTITY_TYPE to SystemAssigned or UserAssigned to have it +# authenticate with Microsoft Entra ID instead, as a managed identity granted the Cosmos DB Built-in Data Contributor +# role on the account: the key then appears nowhere. +MANAGED_IDENTITY_TYPE="${MANAGED_IDENTITY_TYPE:-None}" +MANAGED_IDENTITY_NAME="${PREFIX}-webapp-nosql-identity-${SUFFIX}" +# Cosmos DB Built-in Data Contributor, a data-plane role every Cosmos DB for NoSQL account has under this id. It is a +# role of the account (a SQL role definition), not an Azure RBAC role. +COSMOSDB_DATA_CONTRIBUTOR_ROLE_ID='00000000-0000-0000-0000-000000000002' +# A role is assigned to a managed identity right after the identity is created: the retries cover the time the new +# principal takes to replicate to Microsoft Entra ID +ROLE_ASSIGNMENT_RETRY_COUNT=5 +ROLE_ASSIGNMENT_RETRY_SLEEP=10 + +case "$MANAGED_IDENTITY_TYPE" in +None | SystemAssigned | UserAssigned) ;; +*) + echo "MANAGED_IDENTITY_TYPE must be None, SystemAssigned or UserAssigned, not [$MANAGED_IDENTITY_TYPE]." + exit 1 + ;; +esac + # run-samples.sh runs this script as `bash scripts/deploy.sh` from the sample root, so relative # paths such as ../src must resolve against the script's own location, not the caller's directory. CURRENT_DIR="$(cd "$(dirname "$0")" && pwd)" cd "$CURRENT_DIR" || exit +# Assign the Cosmos DB Built-in Data Contributor role on the whole Cosmos DB account to a principal, unless the +# assignment already exists +# $1: the object (principal) id of the managed identity +# $2: the description of the managed identity, used in messages +ensure_cosmosdb_role_assignment() { + local principal_id=$1 + local principal_description=$2 + local current attempt + + echo "Checking if the $principal_description has the Cosmos DB Built-in Data Contributor role on the [$COSMOSDB_ACCOUNT_NAME] Cosmos DB account..." + current=$(az cosmosdb sql role assignment list \ + --account-name "$COSMOSDB_ACCOUNT_NAME" \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --query "length([?principalId=='$principal_id' && ends_with(roleDefinitionId, '/$COSMOSDB_DATA_CONTRIBUTOR_ROLE_ID')])" \ + --output tsv \ + --only-show-errors) + + if [[ $current -gt 0 ]]; then + echo "The $principal_description already has the Cosmos DB Built-in Data Contributor role on the [$COSMOSDB_ACCOUNT_NAME] Cosmos DB account" + return 0 + fi + + echo "Assigning the Cosmos DB Built-in Data Contributor role to the $principal_description on the [$COSMOSDB_ACCOUNT_NAME] Cosmos DB account..." + for attempt in $(seq 1 "$ROLE_ASSIGNMENT_RETRY_COUNT"); do + # The scope "/" is the whole account: the Azure CLI turns it into the account's resource id + if az cosmosdb sql role assignment create \ + --account-name "$COSMOSDB_ACCOUNT_NAME" \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --role-definition-id "$COSMOSDB_DATA_CONTRIBUTOR_ROLE_ID" \ + --principal-id "$principal_id" \ + --scope "/" \ + --only-show-errors 1>/dev/null; then + echo "Cosmos DB Built-in Data Contributor role successfully assigned to the $principal_description on the [$COSMOSDB_ACCOUNT_NAME] Cosmos DB account" + return 0 + fi + + if [ "$attempt" -lt "$ROLE_ASSIGNMENT_RETRY_COUNT" ]; then + echo "Attempt $attempt of $ROLE_ASSIGNMENT_RETRY_COUNT to assign the role failed; retrying in $ROLE_ASSIGNMENT_RETRY_SLEEP seconds..." + sleep "$ROLE_ASSIGNMENT_RETRY_SLEEP" + fi + done + + echo "Failed to assign the Cosmos DB Built-in Data Contributor role to the $principal_description on the [$COSMOSDB_ACCOUNT_NAME] Cosmos DB account" + exit 1 +} + # Validates if the resource group exists in the subscription, if not creates it echo "Checking if resource group [$RESOURCE_GROUP_NAME] exists..." az group show --name $RESOURCE_GROUP_NAME &>/dev/null @@ -69,7 +137,7 @@ if [[ $? != 0 ]]; then --location "$LOCATION" \ --query-access "Enabled" \ --retention-time 30 \ - --sku "PerNode" \ + --sku "PerGB2018" \ --tags environment=test iac=az-cli \ --only-show-errors 1>/dev/null @@ -227,21 +295,56 @@ else fi fi -# Retrieve the primary key of the Cosmos DB account -echo "Retrieving the primary key of the [$COSMOSDB_ACCOUNT_NAME] Cosmos DB account..." -AZURECOSMOSDB_PRIMARY_KEY=$(az cosmosdb keys list \ - --resource-group $RESOURCE_GROUP_NAME \ - --name $COSMOSDB_ACCOUNT_NAME \ - --query "primaryMasterKey" \ - --output tsv) +if [[ $MANAGED_IDENTITY_TYPE == "None" ]]; then + # Retrieve the primary key of the Cosmos DB account + echo "Retrieving the primary key of the [$COSMOSDB_ACCOUNT_NAME] Cosmos DB account..." + AZURECOSMOSDB_PRIMARY_KEY=$(az cosmosdb keys list \ + --resource-group $RESOURCE_GROUP_NAME \ + --name $COSMOSDB_ACCOUNT_NAME \ + --query "primaryMasterKey" \ + --output tsv) -if [[ -n $AZURECOSMOSDB_PRIMARY_KEY ]]; then - echo "Successfully retrieved the primary key of the [$COSMOSDB_ACCOUNT_NAME] Cosmos DB account" -else - echo "Failed to retrieve the primary key of the [$COSMOSDB_ACCOUNT_NAME] Cosmos DB account" - exit 1 + if [[ -n $AZURECOSMOSDB_PRIMARY_KEY ]]; then + echo "Successfully retrieved the primary key of the [$COSMOSDB_ACCOUNT_NAME] Cosmos DB account" + else + echo "Failed to retrieve the primary key of the [$COSMOSDB_ACCOUNT_NAME] Cosmos DB account" + exit 1 + fi + export AZURECOSMOSDB_PRIMARY_KEY +fi + +if [[ $MANAGED_IDENTITY_TYPE == "UserAssigned" ]]; then + # Create the user-assigned managed identity the web app authenticates as + if az identity show --name "$MANAGED_IDENTITY_NAME" --resource-group "$RESOURCE_GROUP_NAME" --only-show-errors &>/dev/null; then + echo "[$MANAGED_IDENTITY_NAME] managed identity already exists in the [$RESOURCE_GROUP_NAME] resource group" + elif az identity create \ + --name "$MANAGED_IDENTITY_NAME" \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --location "$LOCATION" \ + --only-show-errors 1>/dev/null; then + echo "[$MANAGED_IDENTITY_NAME] managed identity successfully created in the [$RESOURCE_GROUP_NAME] resource group" + else + echo "Failed to create [$MANAGED_IDENTITY_NAME] managed identity in the [$RESOURCE_GROUP_NAME] resource group" + exit 1 + fi + + # tr turns the three lines into one, and drops the carriage return the Azure CLI ends each line with on Windows + read -r IDENTITY_ID IDENTITY_CLIENT_ID IDENTITY_PRINCIPAL_ID < <(az identity show \ + --name "$MANAGED_IDENTITY_NAME" \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --query "[id, clientId, principalId]" \ + --output tsv \ + --only-show-errors | tr -d '\r' | tr '\n' ' ') + + if [[ -n $IDENTITY_PRINCIPAL_ID ]]; then + echo "[$MANAGED_IDENTITY_NAME] managed identity: client id [$IDENTITY_CLIENT_ID], principal id [$IDENTITY_PRINCIPAL_ID]" + else + echo "Failed to retrieve the ids of the [$MANAGED_IDENTITY_NAME] managed identity" + exit 1 + fi + + ensure_cosmosdb_role_assignment "$IDENTITY_PRINCIPAL_ID" "[$MANAGED_IDENTITY_NAME] managed identity" fi -export AZURECOSMOSDB_PRIMARY_KEY if az appservice plan show --name "$APP_SERVICE_PLAN_NAME" --resource-group "$RESOURCE_GROUP_NAME" --only-show-errors &>/dev/null; then echo "App service plan [$APP_SERVICE_PLAN_NAME] already exists." @@ -283,6 +386,44 @@ else fi fi +case "$MANAGED_IDENTITY_TYPE" in +SystemAssigned) + # A system-assigned identity exists only once the web app does, so it is granted its role here, well before the + # code is deployed: on Azure, a new role assignment takes a while to reach the data plane + echo "Assigning a system-assigned managed identity to the [$WEB_APP_NAME] web app..." + WEB_APP_PRINCIPAL_ID=$(az webapp identity assign \ + --name "$WEB_APP_NAME" \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --query principalId \ + --output tsv \ + --only-show-errors) + + if [[ -n $WEB_APP_PRINCIPAL_ID ]]; then + echo "System-assigned managed identity of the [$WEB_APP_NAME] web app: principal id [$WEB_APP_PRINCIPAL_ID]" + else + echo "Failed to assign a system-assigned managed identity to the [$WEB_APP_NAME] web app" + exit 1 + fi + + ensure_cosmosdb_role_assignment "$WEB_APP_PRINCIPAL_ID" "system-assigned managed identity of the [$WEB_APP_NAME] web app" + ;; +UserAssigned) + echo "Assigning the [$MANAGED_IDENTITY_NAME] managed identity to the [$WEB_APP_NAME] web app..." + az webapp identity assign \ + --name "$WEB_APP_NAME" \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --identities "$IDENTITY_ID" \ + --only-show-errors 1>/dev/null + + if [[ $? == 0 ]]; then + echo "[$MANAGED_IDENTITY_NAME] managed identity successfully assigned to the [$WEB_APP_NAME] web app" + else + echo "Failed to assign the [$MANAGED_IDENTITY_NAME] managed identity to the [$WEB_APP_NAME] web app" + exit 1 + fi + ;; +esac + # Check if the Application Insights component already exists echo "Checking if [$APPLICATION_INSIGHTS_NAME] Application Insights component exists in the [$RESOURCE_GROUP_NAME] resource group..." az monitor app-insights component show \ @@ -331,6 +472,14 @@ else exit 1 fi +# The credential the web app reaches the Cosmos DB account with: the account key, or nothing for a system-assigned +# identity, or the client id DefaultAzureCredential picks a user-assigned identity by +case "$MANAGED_IDENTITY_TYPE" in +None) COSMOSDB_CREDENTIAL_SETTINGS=(AZURECOSMOSDB_PRIMARY_KEY="$AZURECOSMOSDB_PRIMARY_KEY") ;; +SystemAssigned) COSMOSDB_CREDENTIAL_SETTINGS=() ;; +UserAssigned) COSMOSDB_CREDENTIAL_SETTINGS=(AZURE_CLIENT_ID="$IDENTITY_CLIENT_ID") ;; +esac + # Set the application settings of the web app. The package holds the source code, so the deployment builds it: # without SCM_DO_BUILD_DURING_DEPLOYMENT, az webapp deploy only copies the files and Azure serves its welcome page echo "Setting the application settings of the [$WEB_APP_NAME] web app..." @@ -342,7 +491,7 @@ az webapp config appsettings set \ AZURECOSMOSDB_ENDPOINT=$AZURECOSMOSDB_ENDPOINT \ AZURECOSMOSDB_DATABASENAME=$AZURECOSMOSDB_DATABASENAME \ AZURECOSMOSDB_CONTAINERNAME=$AZURECOSMOSDB_CONTAINERNAME \ - AZURECOSMOSDB_PRIMARY_KEY=$AZURECOSMOSDB_PRIMARY_KEY \ + "${COSMOSDB_CREDENTIAL_SETTINGS[@]}" \ APPLICATIONINSIGHTS_CONNECTION_STRING="$APPLICATION_INSIGHTS_CONNECTION_STRING" \ --only-show-errors 1>/dev/null @@ -353,7 +502,32 @@ else exit 1 fi -# Print the names of the application settings of the web app, never their values, which include the account key +# The credentials a previous run with another MANAGED_IDENTITY_TYPE left in the app settings, which the app would keep +# using: the account key of a run without a managed identity, and the client id of a user-assigned run, with which +# DefaultAzureCredential keeps picking the user-assigned identity over the system-assigned one +case "$MANAGED_IDENTITY_TYPE" in +None) STALE_CREDENTIAL_SETTINGS=() ;; +SystemAssigned) STALE_CREDENTIAL_SETTINGS=(AZURECOSMOSDB_PRIMARY_KEY AZURE_CLIENT_ID) ;; +UserAssigned) STALE_CREDENTIAL_SETTINGS=(AZURECOSMOSDB_PRIMARY_KEY) ;; +esac + +if [[ ${#STALE_CREDENTIAL_SETTINGS[@]} -gt 0 ]]; then + echo "Removing [${STALE_CREDENTIAL_SETTINGS[*]}] from the application settings of the [$WEB_APP_NAME] web app, if a previous run set them..." + az webapp config appsettings delete \ + --resource-group $RESOURCE_GROUP_NAME \ + --name $WEB_APP_NAME \ + --setting-names "${STALE_CREDENTIAL_SETTINGS[@]}" \ + --only-show-errors 1>/dev/null + + if [[ $? == 0 ]]; then + echo "No [${STALE_CREDENTIAL_SETTINGS[*]}] is left in the application settings of the [$WEB_APP_NAME] web app" + else + echo "Failed to remove [${STALE_CREDENTIAL_SETTINGS[*]}] from the application settings of the [$WEB_APP_NAME] web app" + exit 1 + fi +fi + +# Print the names of the application settings of the web app, never their values, which can include the account key echo "Names of the application settings of the [$WEB_APP_NAME] web app:" az webapp config appsettings list \ --resource-group $RESOURCE_GROUP_NAME \ diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/scripts/validate.sh b/samples/web-app-cosmosdb-nosql-api/dotnet/scripts/validate.sh index 0795053a..3a5ce82b 100755 --- a/samples/web-app-cosmosdb-nosql-api/dotnet/scripts/validate.sh +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/scripts/validate.sh @@ -9,6 +9,124 @@ APP_SERVICE_PLAN_NAME="${WEB_APP_NAME}" COSMOSDB_ACCOUNT_NAME="${WEB_APP_NAME}" LOG_ANALYTICS_NAME="${PREFIX}-log-analytics-${SUFFIX}" APPLICATION_INSIGHTS_NAME="${PREFIX}-insights-${SUFFIX}" +# The authentication deploy.sh set up: the account key (None), or a managed identity (SystemAssigned, UserAssigned) +MANAGED_IDENTITY_TYPE="${MANAGED_IDENTITY_TYPE:-None}" +MANAGED_IDENTITY_NAME="${PREFIX}-webapp-nosql-identity-${SUFFIX}" +COSMOSDB_DATA_CONTRIBUTOR_ROLE_ID='00000000-0000-0000-0000-000000000002' +# The round trip through the web app waits for the app to start and, on Azure, for a new role assignment to reach the +# data plane +ROUND_TRIP_RETRY_COUNT="${ROUND_TRIP_RETRY_COUNT:-60}" +ROUND_TRIP_RETRY_SLEEP="${ROUND_TRIP_RETRY_SLEEP:-10}" + +# On Windows, Git Bash and MSYS2 shells pass a path such as /tmp/... unconverted to Windows programs +# (az, curl, jq, python, docker) when MSYS_NO_PATHCONV=1 is set, as the README asks. cygpath, which +# those shells provide, returns the C:/... form those programs can open; elsewhere the path is unchanged. +native_path() { + if command -v cygpath >/dev/null 2>&1; then + cygpath -m "$1" + else + echo "$1" + fi +} + +# Where curl discards a response body. Git Bash and MSYS2 shells hand a Windows curl /dev/null +# unchanged when MSYS_NO_PATHCONV=1 is set, as the README asks, and it cannot open that path, so it +# gets the NUL device instead; MSYS2's own curl, under /usr/bin, opens /dev/null as on Linux and macOS. +null_device() { + if command -v cygpath >/dev/null 2>&1 && [[ "$(command -v curl)" != /usr/bin/* ]]; then + echo NUL + else + echo /dev/null + fi +} + +# Add an activity through the web app, find it on the page that lists the activities, and delete it. The app reads and +# writes the Cosmos DB container as its managed identity, so the round trip proves the identity's role assignment. +check_round_trip() { + local host_name url cookies_file cookies discard activity page token status activity_id attempt + local token_args=() + + host_name=$(az webapp show \ + --name "$WEB_APP_NAME" \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --query defaultHostName \ + --output tsv \ + --only-show-errors | tr -d '\r') + + if [[ -z $host_name ]]; then + echo "Error: no default host name found for the [$WEB_APP_NAME] web app" + exit 1 + fi + + url="https://$host_name" + cookies_file=$(mktemp "${TMPDIR:-/tmp}/cosmosdb_nosql_cookies.XXXXXX") + cookies=$(native_path "$cookies_file") + discard=$(null_device) + activity="validation-$(date +%s)" + echo -e "\nAdding the [$activity] activity through the [$WEB_APP_NAME] web app at [$url]..." + + for attempt in $(seq 1 "$ROUND_TRIP_RETRY_COUNT"); do + page=$(curl --max-time 30 -s -c "$cookies" -b "$cookies" "$url/") + + if [[ $page == *'name="activity"'* ]]; then + # The .NET app's forms carry an antiforgery token, which a post must send back with the cookie it came with + token=$(printf '%s' "$page" | grep -o ']*__RequestVerificationToken[^>]*>' | head -n 1 | sed -n 's/.*value="\([^"]*\)".*/\1/p') + token_args=() + if [[ -n $token ]]; then + token_args=(--data-urlencode "__RequestVerificationToken=$token") + fi + + status=$(curl --max-time 30 -s -o "$discard" -w '%{http_code}' -c "$cookies" -b "$cookies" \ + --data-urlencode "activity=$activity" \ + --data-urlencode "row_id=" \ + "${token_args[@]}" \ + "$url/") + page=$(curl --max-time 30 -s -c "$cookies" -b "$cookies" "$url/") + activity_id=$(printf '%s' "$page" | grep -o "data-id=\"[^\"]*\" data-activity=\"$activity\"" | head -n 1 | sed 's/^data-id="\([^"]*\)".*/\1/') + + if [[ -n $activity_id ]]; then + echo "The [$WEB_APP_NAME] web app stored the [$activity] activity as item [$activity_id] and read it back" + break + fi + echo "Attempt $attempt of $ROUND_TRIP_RETRY_COUNT: the web app answered [$status] to the new activity, which its page doesn't list yet." + else + echo "Attempt $attempt of $ROUND_TRIP_RETRY_COUNT: the web app doesn't serve its page yet." + fi + + if [ "$attempt" -lt "$ROUND_TRIP_RETRY_COUNT" ]; then + sleep "$ROUND_TRIP_RETRY_SLEEP" + fi + done + + if [[ -z $activity_id ]]; then + rm -f "$cookies_file" + echo "Error: the [$WEB_APP_NAME] web app didn't store and list the [$activity] activity after $ROUND_TRIP_RETRY_COUNT attempts" + exit 1 + fi + + # Delete the activity, with the antiforgery token of the page that lists it + token=$(printf '%s' "$page" | grep -o ']*__RequestVerificationToken[^>]*>' | head -n 1 | sed -n 's/.*value="\([^"]*\)".*/\1/p') + token_args=() + if [[ -n $token ]]; then + token_args=(--data-urlencode "__RequestVerificationToken=$token") + fi + + status=$(curl --max-time 30 -s -o "$discard" -w '%{http_code}' -c "$cookies" -b "$cookies" -X POST \ + "${token_args[@]}" \ + "$url/delete/$activity_id") + page=$(curl --max-time 30 -s -c "$cookies" -b "$cookies" "$url/") + rm -f "$cookies_file" + + # The app confirms the deletion on the next page, which must also have read the activities again: after a failed + # read it renders the form with no activities, which would hide an activity it did not delete + if [[ $page == *'Activity deleted.'* && $page != *'Failed to load the activities.'* && + $page == *'name="activity"'* && $page != *"data-id=\"$activity_id\""* ]]; then + echo "The [$WEB_APP_NAME] web app deleted the [$activity] activity" + else + echo "Error: the [$WEB_APP_NAME] web app answered [$status] to the deletion of the [$activity] activity, without confirming it or with the activity still listed" + exit 1 + fi +} # Check resource group echo -e "[$RESOURCE_GROUP_NAME] resource group:\n" @@ -67,3 +185,47 @@ az resource list \ --resource-group "$RESOURCE_GROUP_NAME" \ --output table \ --only-show-errors + +if [[ $MANAGED_IDENTITY_TYPE != "None" ]]; then + # The principal the web app authenticates as + if [[ $MANAGED_IDENTITY_TYPE == "SystemAssigned" ]]; then + PRINCIPAL_ID=$(az webapp identity show \ + --name "$WEB_APP_NAME" \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --query principalId \ + --output tsv \ + --only-show-errors | tr -d '\r') + else + PRINCIPAL_ID=$(az identity show \ + --name "$MANAGED_IDENTITY_NAME" \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --query principalId \ + --output tsv \ + --only-show-errors | tr -d '\r') + fi + + # Check the SQL role assignments of the Cosmos DB account + echo -e "\n[$COSMOSDB_ACCOUNT_NAME] cosmos db sql role assignments:\n" + az cosmosdb sql role assignment list \ + --account-name "$COSMOSDB_ACCOUNT_NAME" \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --query '[].{PrincipalId:principalId,RoleDefinitionId:roleDefinitionId,Scope:scope}' \ + --output table \ + --only-show-errors + + ROLE_ASSIGNMENT_COUNT=$(az cosmosdb sql role assignment list \ + --account-name "$COSMOSDB_ACCOUNT_NAME" \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --query "length([?principalId=='$PRINCIPAL_ID' && ends_with(roleDefinitionId, '/$COSMOSDB_DATA_CONTRIBUTOR_ROLE_ID')])" \ + --output tsv \ + --only-show-errors | tr -d '\r') + + if [[ -n $PRINCIPAL_ID && $ROLE_ASSIGNMENT_COUNT -gt 0 ]]; then + echo -e "\nThe $MANAGED_IDENTITY_TYPE managed identity [$PRINCIPAL_ID] of the web app has the Cosmos DB Built-in Data Contributor role" + else + echo -e "\nError: the $MANAGED_IDENTITY_TYPE managed identity [$PRINCIPAL_ID] of the web app has no Cosmos DB Built-in Data Contributor role" + exit 1 + fi + + check_round_trip +fi diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/src/Program.cs b/samples/web-app-cosmosdb-nosql-api/dotnet/src/Program.cs index b795fabc..f5b689a4 100644 --- a/samples/web-app-cosmosdb-nosql-api/dotnet/src/Program.cs +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/src/Program.cs @@ -32,8 +32,11 @@ builder.Services.AddRazorPages(); builder.Services.AddSingleton(sp => new CosmosActivityStore(cosmosOptions, sp.GetRequiredService>())); +// On Azure, a new data-plane role assignment of the app's managed identity can take a few minutes to take effect, and +// until then Azure Cosmos DB refuses the identity: the store is tried for two minutes before the app gives up. builder.Services.AddHostedService(sp => - new StoreInitializer(sp.GetRequiredService(), sp.GetRequiredService>())); + new StoreInitializer(sp.GetRequiredService(), sp.GetRequiredService>(), + attempts: 12, delay: TimeSpan.FromSeconds(10))); var app = builder.Build(); diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/src/Services/CosmosActivityStore.cs b/samples/web-app-cosmosdb-nosql-api/dotnet/src/Services/CosmosActivityStore.cs index a0d128d4..c17b4137 100644 --- a/samples/web-app-cosmosdb-nosql-api/dotnet/src/Services/CosmosActivityStore.cs +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/src/Services/CosmosActivityStore.cs @@ -1,4 +1,5 @@ using System.Net; +using Azure.Identity; using Microsoft.Azure.Cosmos; using VacationPlanner.Models; @@ -18,16 +19,33 @@ public CosmosActivityStore(CosmosOptions options, ILogger l _logger = logger; // Gateway mode talks plain HTTPS to the account endpoint, which is what the LocalStack emulator // exposes; Direct mode (the SDK default) needs the TCP replica endpoints of a real account. - _client = new CosmosClient(options.Endpoint, options.Key, new CosmosClientOptions + var clientOptions = new CosmosClientOptions { ConnectionMode = ConnectionMode.Gateway, LimitToEndpoint = true, // Distributed tracing is off by default in the GA SDK: on, each operation is an activity of an // Azure.Cosmos source, which the Microsoft OpenTelemetry Distro exports as a dependency. CosmosClientTelemetryOptions = new CosmosClientTelemetryOptions { DisableDistributedTracing = false }, - }); + }; + // With the account key, the client signs its requests with it. Without one, the client authenticates with + // Microsoft Entra ID: DefaultAzureCredential gets a token for the web app's managed identity (the one + // AZURE_CLIENT_ID names, for a user-assigned identity), and the identity's Cosmos DB data-plane role decides + // what it may do. + if (options.Key is { Length: > 0 } key) + { + _client = new CosmosClient(options.Endpoint, key, clientOptions); + } + else + { + _logger.LogInformation("Authenticating to Azure Cosmos DB with Microsoft Entra ID"); + _client = new CosmosClient(options.Endpoint, new DefaultAzureCredential(), clientOptions); + } } + /// + /// Reads the database and the container, and creates them only when they don't exist. A Microsoft Entra identity + /// can't create them (Azure refuses it whatever its roles), so the deploy script creates both. + /// public async Task InitializeAsync(CancellationToken cancellationToken) { var database = await _client.CreateDatabaseIfNotExistsAsync(_options.DatabaseName, cancellationToken: cancellationToken); diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/src/Services/CosmosOptions.cs b/samples/web-app-cosmosdb-nosql-api/dotnet/src/Services/CosmosOptions.cs index 4412f8f6..d27b1545 100644 --- a/samples/web-app-cosmosdb-nosql-api/dotnet/src/Services/CosmosOptions.cs +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/src/Services/CosmosOptions.cs @@ -1,7 +1,10 @@ namespace VacationPlanner.Services; -/// Settings read from the same environment variables the Python sample uses. -public sealed record CosmosOptions(string Endpoint, string Key, string DatabaseName, string ContainerName, string Username) +/// +/// Settings read from the same environment variables the Python sample uses. is null when the app +/// authenticates with Microsoft Entra ID, as its managed identity, instead of the account key. +/// +public sealed record CosmosOptions(string Endpoint, string? Key, string DatabaseName, string ContainerName, string Username) { public static CosmosOptions FromEnvironment() { @@ -13,7 +16,7 @@ public static CosmosOptions FromEnvironment() return new CosmosOptions( Endpoint: Require("AZURECOSMOSDB_ENDPOINT"), - Key: Require("AZURECOSMOSDB_PRIMARY_KEY"), + Key: Environment.GetEnvironmentVariable("AZURECOSMOSDB_PRIMARY_KEY") is { Length: > 0 } key ? key : null, DatabaseName: Require("AZURECOSMOSDB_DATABASENAME"), ContainerName: Require("AZURECOSMOSDB_CONTAINERNAME"), Username: username); diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/src/VacationPlanner.csproj b/samples/web-app-cosmosdb-nosql-api/dotnet/src/VacationPlanner.csproj index 92fd4f2e..d2ed109f 100644 --- a/samples/web-app-cosmosdb-nosql-api/dotnet/src/VacationPlanner.csproj +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/src/VacationPlanner.csproj @@ -6,6 +6,7 @@ VacationPlanner + diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/README.md b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/README.md new file mode 100644 index 00000000..20dd5f05 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/README.md @@ -0,0 +1,153 @@ +# Terraform Deployment + +This directory contains the Terraform modules and a deployment script for provisioning the sample in LocalStack for Azure or in Azure. Refer to the [Azure Web App with Azure CosmosDB for NoSQL API](../README.md) guide for details about the sample application. + +## Prerequisites + +Before deploying this solution, ensure you have the following tools installed: + +- [LocalStack for Azure](https://docs.localstack.cloud/azure/): Local Azure cloud emulator for development and testing +- [Visual Studio Code](https://code.visualstudio.com/): Code editor installed on one of the [supported platforms](https://code.visualstudio.com/docs/supporting/requirements#_platforms) +- [Terraform](https://developer.hashicorp.com/terraform/downloads): Infrastructure as code tool, version 1.0 or above +- [Docker](https://docs.docker.com/get-docker/): Container runtime required for LocalStack +- [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli): Azure command-line interface +- [lstk CLI](https://docs.localstack.cloud/aws/developer-tools/running-localstack/lstk/): LocalStack command-line interface (proxies the Azure CLI via `lstk az`) +- [.NET SDK 10.0](https://dotnet.microsoft.com/en-us/download/dotnet/10.0): .NET software development kit + +### Installing lstk CLI + +Deploying to LocalStack requires the `lstk` CLI, which routes Azure CLI commands to the emulator (run `lstk az start-interception` before deploying). Install it using Homebrew: + +```bash +brew install localstack/tap/lstk +``` + +or npm: + +```bash +npm install -g @localstack/lstk +``` + +Alternatively, download a pre-built binary from the [lstk releases page](https://github.com/localstack/lstk/releases). For more information, see the [lstk CLI documentation](https://docs.localstack.cloud/aws/developer-tools/running-localstack/lstk/) and the [lstk GitHub repository](https://github.com/localstack/lstk). + +## Architecture Overview + +[main.tf](main.tf) creates the following resources, most of them through a module in the [modules](modules) folder: + +1. [Resource group](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/manage-resource-groups-cli): holds all the resources of the sample. +2. [Azure Cosmos DB for NoSQL account](https://learn.microsoft.com/en-us/azure/cosmos-db/overview) ([cosmosdb_nosql](modules/cosmosdb_nosql)): the account, the `vacationplanner` database, and the `activities` container, partitioned by `/username`, with 400 request units per second. +3. [Managed identity](https://learn.microsoft.com/en-us/entra/identity/managed-identities-azure-resources/overview) ([managed_identity](modules/managed_identity)): with `MANAGED_IDENTITY_TYPE=UserAssigned`, the default, a user-assigned identity assigned to the web app. With `MANAGED_IDENTITY_TYPE=SystemAssigned`, the web app's own identity instead, which the web app module enables. +4. [Cosmos DB SQL role assignment](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/cosmosdb_sql_role_assignment) (the `azurerm_cosmosdb_sql_role_assignment` resource in [main.tf](main.tf)): grants the identity the [Cosmos DB Built-in Data Contributor](https://learn.microsoft.com/en-us/azure/cosmos-db/reference-data-plane-security#built-in-roles) role on the whole account. It's a role of the Cosmos DB account itself, not an Azure RBAC role. +5. [Azure App Service plan](https://learn.microsoft.com/en-us/azure/app-service/overview-hosting-plans) ([app_service_plan](modules/app_service_plan)): a B1 Linux plan that hosts the web app. +6. [Azure Web App](https://learn.microsoft.com/en-us/azure/app-service/overview) ([web_app](modules/web_app)): hosts the ASP.NET Core Razor Pages *Vacation Planner* application. Its app settings hold the endpoint of the account and the names of the database and the container, and, for a user-assigned identity, its client id in `AZURE_CLIENT_ID`. They hold no key: the app passes `DefaultAzureCredential` to `CosmosClient`, which gets a token for the web app's managed identity. +7. [Log Analytics workspace](https://learn.microsoft.com/en-us/azure/azure-monitor/logs/log-analytics-workspace-overview) ([log_analytics](modules/log_analytics)): stores the telemetry of Application Insights, the logs and metrics that the diagnostic settings send to it, and the audit records of the queries run on it. +8. [Application Insights](https://learn.microsoft.com/en-us/azure/azure-monitor/app/app-insights-overview) ([application_insights](modules/application_insights)): a workspace-based resource that collects the requests, the calls to Azure Cosmos DB, the log records, the exceptions, the custom events and the custom metric of the web app. +9. [Diagnostic settings](https://learn.microsoft.com/en-us/azure/azure-monitor/data-collection/diagnostic-settings): send the logs and metrics of the web app, the metrics of the App Service plan, the `DataPlaneRequests` and `ControlPlaneRequests` logs and the `Requests` metrics of the Cosmos DB account (in the resource-specific tables `CDBDataPlaneRequests` and `CDBControlPlaneRequests`), and the query audit of the workspace to the Log Analytics workspace. + +The resources get the same names as with the [Azure CLI scripts](../scripts/README.md), so the scripts in the [scripts](../scripts) folder validate this deployment and query its telemetry, logs and metrics too. + +## Provisioning Scripts + +You can use the [deploy.sh](deploy.sh) script to deploy all Azure resources and the sample application in a single step. It runs `terraform init`, `terraform plan` and `terraform apply`, with the managed identity type in `MANAGED_IDENTITY_TYPE`: `UserAssigned` (the default) or `SystemAssigned`. It then packages the web application code into a zip file and deploys it to the web app, which builds it. + +## Configuration + +`providers.tf` hardcodes no endpoint and no subscription. `deploy.sh` exports the variables the [Azure Provider for Terraform](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs) reads natively, so the same files run unmodified against the LocalStack emulator and against Azure: + +| Variable | Exported when | Value | +| -------------------------------------- | ------------------------------------- | --------------------------------------------------------- | +| `ARM_SUBSCRIPTION_ID`, `ARM_TENANT_ID` | always | `az account show` | +| `ARM_METADATA_HOSTNAME` | the active `az cloud` is `LocalStack` | host of `az cloud show --query endpoints.resourceManager` | + +The provider discovers every endpoint of the emulator from `ARM_METADATA_HOSTNAME`, and authenticates with the Azure CLI session on both targets. Against Azure, `deploy.sh` unsets `ARM_METADATA_HOSTNAME`, so the provider uses the endpoints of the public cloud. Running `terraform` directly, rather than through `deploy.sh`, needs these variables exported. + +## Deployment + +You can set up the Azure emulator by utilizing LocalStack for Azure Docker image. Before starting, ensure you have a valid `LOCALSTACK_AUTH_TOKEN` to access the Azure emulator. Refer to the [Auth Token guide](https://docs.localstack.cloud/getting-started/auth-token/) to obtain your Auth Token and specify it in the `LOCALSTACK_AUTH_TOKEN` environment variable. The Azure Docker image is available on the [LocalStack Docker Hub](https://hub.docker.com/r/localstack/localstack-azure). To pull the Azure Docker image, execute the following command: + +```bash +docker pull localstack/localstack-azure +``` + +Start the LocalStack Azure emulator with the lstk CLI: + +```bash +# Set the authentication token +export LOCALSTACK_AUTH_TOKEN= + +# Start the LocalStack Azure emulator +lstk start --type azure + +# Route all Azure CLI calls to the LocalStack Azure emulator +lstk az start-interception +``` + +Navigate to the `terraform` folder: + +```bash +cd samples/web-app-cosmosdb-nosql-api/dotnet/terraform +``` + +Make the script executable: + +```bash +chmod +x deploy.sh +``` + +Run the deployment script, which gives the web app a user-assigned managed identity: + +```bash +./deploy.sh +``` + +To use the web app's system-assigned managed identity instead, set `MANAGED_IDENTITY_TYPE`: + +```bash +MANAGED_IDENTITY_TYPE=SystemAssigned ./deploy.sh +``` + +The same script deploys the sample to Azure: run `lstk az stop-interception` to route the Azure CLI back to Azure, sign in with `az login`, and run it again. See [Microsoft Entra ID authentication](../README.md#microsoft-entra-id-authentication). + +## Validation + +After deployment, run the validation script of the [scripts](../scripts) folder with the same `MANAGED_IDENTITY_TYPE`: + +```bash +MANAGED_IDENTITY_TYPE=UserAssigned ../scripts/validate.sh +``` + +It shows the resource group, the App Service plan, the web app, the Cosmos DB account, the Log Analytics workspace, the Application Insights component and the resources of the group. It then checks that the managed identity has the Cosmos DB Built-in Data Contributor role on the account, adds an activity through the web app, finds it on the page, and deletes it. On Azure, a new role assignment can take a few minutes to take effect, and the script retries meanwhile. + +## Telemetry, logs and metrics + +Read the telemetry the web app sent to Application Insights and the logs and metrics the diagnostic settings sent to the workspace: + +```bash +../scripts/query-telemetry.sh +../scripts/query-logs-and-metrics.sh +``` + +See [Application Insights](../README.md#application-insights) and [Logs and metrics](../README.md#logs-and-metrics) for what they read. + +## Cleanup + +To destroy all created resources: + +```bash +# Delete resource group and all contained resources +az group delete --name local-rg --yes --no-wait + +# Verify deletion +az group list --output table +``` + +This will remove all Azure resources created by the Terraform configuration. + +## Related Documentation + +- [Terraform Azure Provider Documentation](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs) +- [azurerm_cosmosdb_sql_role_assignment](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/cosmosdb_sql_role_assignment) +- [Connect to Azure Cosmos DB for NoSQL with role-based access control and Microsoft Entra ID](https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-connect-role-based-access-control) +- [LocalStack for Azure Documentation](https://docs.localstack.cloud/azure/) +- [lstk CLI](https://docs.localstack.cloud/aws/developer-tools/running-localstack/lstk/) +- [lstk GitHub repository](https://github.com/localstack/lstk) diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/deploy.sh b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/deploy.sh new file mode 100755 index 00000000..ce21eb3a --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/deploy.sh @@ -0,0 +1,141 @@ +#!/bin/bash + +# Variables +PREFIX="${PREFIX:-local}" +SUFFIX="${SUFFIX:-test}" +LOCATION='westeurope' +CURRENT_DIR="$(cd "$(dirname "$0")" && pwd)" + +# The web app reaches the Cosmos DB account with Microsoft Entra ID, as a managed identity granted the Cosmos DB +# Built-in Data Contributor role on the account: no key appears anywhere. UserAssigned (the default) creates a +# user-assigned identity and assigns it to the web app; SystemAssigned enables the web app's own identity. +MANAGED_IDENTITY_TYPE="${MANAGED_IDENTITY_TYPE:-UserAssigned}" + +case "$MANAGED_IDENTITY_TYPE" in +SystemAssigned | UserAssigned) ;; +*) + echo "MANAGED_IDENTITY_TYPE must be SystemAssigned or UserAssigned, not [$MANAGED_IDENTITY_TYPE]." + exit 1 + ;; +esac + +# Change the current directory to the script's directory +cd "$CURRENT_DIR" || exit + +# Dual-target provider configuration. providers.tf hardcodes nothing: the azurerm provider reads its endpoints and the +# target subscription from the ARM_* environment variables exported here. +# - On both targets: the subscription and tenant of the active az account. +# - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration +# that `lstk az start-interception` created, so nothing is hardcoded here either. +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') +export ARM_SUBSCRIPTION_ID ARM_TENANT_ID + +if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') + METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" + export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" + echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets the emulator at [$RESOURCE_MANAGER_ENDPOINT]" +else + # Cleared rather than merely not set: a value inherited from an earlier emulator deployment in the same shell would + # keep the provider doing metadata discovery against the emulator while the CLI is on Azure. + unset ARM_METADATA_HOSTNAME + echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets Azure subscription [$ARM_SUBSCRIPTION_ID]" +fi + +echo "Initializing Terraform..." +terraform init -upgrade + +# Run terraform plan and check for errors +echo "Planning Terraform deployment with a [$MANAGED_IDENTITY_TYPE] managed identity..." +terraform plan -out=tfplan \ + -var "prefix=$PREFIX" \ + -var "suffix=$SUFFIX" \ + -var "location=$LOCATION" \ + -var "managed_identity_type=$MANAGED_IDENTITY_TYPE" + +if [[ $? != 0 ]]; then + echo "Terraform plan failed. Exiting." + exit 1 +fi + +# Apply the Terraform configuration +echo "Applying Terraform configuration..." +terraform apply -auto-approve tfplan + +if [[ $? != 0 ]]; then + echo "Terraform apply failed. Exiting." + exit 1 +fi + +# Get the output values +RESOURCE_GROUP_NAME=$(terraform output -raw resource_group_name) +WEB_APP_NAME=$(terraform output -raw web_app_name) +COSMOSDB_ACCOUNT_NAME=$(terraform output -raw cosmosdb_account_name) +PRINCIPAL_ID=$(terraform output -raw principal_id) + +# Check if output values are empty +if [[ -z "$WEB_APP_NAME" || -z "$COSMOSDB_ACCOUNT_NAME" ]]; then + echo "Web App Name or Cosmos DB Account Name is empty. Exiting." + exit 1 +fi + +echo "Deployment details:" +echo "- resourceGroupName: $RESOURCE_GROUP_NAME" +echo "- webAppName: $WEB_APP_NAME" +echo "- cosmosDbAccountName: $COSMOSDB_ACCOUNT_NAME" +echo "- principalId of the [$MANAGED_IDENTITY_TYPE] managed identity: $PRINCIPAL_ID" + +# The zip package is named after the web app, so deployments with different prefixes don't overwrite each other's +ZIPFILE="${WEB_APP_NAME}.zip" + +# Change current directory to source folder +cd "../src" || exit + +# Remove any existing zip package of the web app +if [ -f "$ZIPFILE" ]; then + rm "$ZIPFILE" +fi + +# Create the zip package of the web app +echo "Creating zip package of the web app..." +zip -r "$ZIPFILE" . -x "bin/*" "obj/*" "publish/*" "*.zip" + +# Deploy the web app +echo "Deploying web app [$WEB_APP_NAME] with zip file [$ZIPFILE]..." +# On Azure the deployment service can answer 504 Gateway Timeout while it warms up, or DeploymentInProgress while +# the build of the previous deployment still runs: the upload is tried again. The startup of the site isn't +# tracked: the tracking counted a failed start of the container that ran before the code was deployed, and +# reported a running site as failed after ten minutes; what calls the web app afterwards waits for it instead. +WEBAPP_DEPLOY_RETRY_COUNT="${WEBAPP_DEPLOY_RETRY_COUNT:-10}" +WEBAPP_DEPLOY_RETRY_SLEEP="${WEBAPP_DEPLOY_RETRY_SLEEP:-30}" +WEBAPP_DEPLOYED=0 +for ATTEMPT in $(seq 1 "$WEBAPP_DEPLOY_RETRY_COUNT"); do + if az webapp deploy \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --name "$WEB_APP_NAME" \ + --src-path "$ZIPFILE" \ + --type zip \ + --async true \ + --track-status false 1>/dev/null; then + WEBAPP_DEPLOYED=1 + break + fi + if [ "$ATTEMPT" -lt "$WEBAPP_DEPLOY_RETRY_COUNT" ]; then + echo "Attempt $ATTEMPT of $WEBAPP_DEPLOY_RETRY_COUNT to deploy web app [$WEB_APP_NAME] failed. Waiting [$WEBAPP_DEPLOY_RETRY_SLEEP] seconds before retry..." + sleep "$WEBAPP_DEPLOY_RETRY_SLEEP" + fi +done + +if [ $WEBAPP_DEPLOYED -eq 1 ]; then + echo "Web app [$WEB_APP_NAME] deployed successfully." +else + echo "Failed to deploy web app [$WEB_APP_NAME]." + exit 1 +fi + +# Remove the zip package of the web app +if [ -f "$ZIPFILE" ]; then + rm "$ZIPFILE" +fi diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/main.tf b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/main.tf new file mode 100644 index 00000000..bbff98fb --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/main.tf @@ -0,0 +1,129 @@ +# Local Variables +locals { + # The names the Azure CLI scripts of this sample give the same resources, so the scripts in ../scripts that validate + # the deployment and query its telemetry, logs and metrics work on this deployment too + resource_group_name = "${var.prefix}-rg" + web_app_name = "${var.prefix}-webapp-nosql-${var.suffix}" + app_service_plan_name = local.web_app_name + cosmosdb_account_name = local.web_app_name + managed_identity_name = "${var.prefix}-webapp-nosql-identity-${var.suffix}" + log_analytics_name = "${var.prefix}-log-analytics-${var.suffix}" + application_insights_name = "${var.prefix}-insights-${var.suffix}" + + # The id of the Cosmos DB Built-in Data Contributor role, a data-plane role every Cosmos DB for NoSQL account has + # under this id. It is a role of the account (a SQL role definition), not an Azure RBAC role. + cosmosdb_data_contributor_role_id = "00000000-0000-0000-0000-000000000002" +} + +# Create a resource group +resource "azurerm_resource_group" "example" { + name = local.resource_group_name + location = var.location + tags = var.tags +} + +# Create the Log Analytics workspace that receives the logs and metrics of the resources and the telemetry of the web app +module "log_analytics" { + source = "./modules/log_analytics" + name = local.log_analytics_name + resource_group_name = azurerm_resource_group.example.name + location = azurerm_resource_group.example.location + tags = var.tags +} + +# Create the workspace-based Application Insights component that collects the web app's requests, dependencies, logs, exceptions, custom events and custom metrics +module "application_insights" { + source = "./modules/application_insights" + name = local.application_insights_name + resource_group_name = azurerm_resource_group.example.name + location = azurerm_resource_group.example.location + workspace_id = module.log_analytics.id + tags = var.tags +} + +# Create the Cosmos DB for NoSQL account, its database and container, and the diagnostic setting of the account +module "cosmosdb" { + source = "./modules/cosmosdb_nosql" + name = local.cosmosdb_account_name + resource_group_name = azurerm_resource_group.example.name + location = azurerm_resource_group.example.location + database_name = var.cosmosdb_database_name + container_name = var.cosmosdb_container_name + partition_key_path = var.cosmosdb_partition_key_path + container_throughput = var.cosmosdb_container_throughput + log_analytics_workspace_id = module.log_analytics.id + diagnostic_setting_name = var.diagnostic_settings_name + tags = var.tags +} + +# Conditionally create a user-assigned identity for the web app +module "managed_identity" { + source = "./modules/managed_identity" + count = var.managed_identity_type == "UserAssigned" ? 1 : 0 + name = local.managed_identity_name + resource_group_name = azurerm_resource_group.example.name + location = azurerm_resource_group.example.location + tags = var.tags +} + +# Create the App Service plan and its diagnostic setting +module "app_service_plan" { + source = "./modules/app_service_plan" + name = local.app_service_plan_name + resource_group_name = azurerm_resource_group.example.name + location = azurerm_resource_group.example.location + sku_name = var.sku_name + os_type = var.os_type + zone_balancing_enabled = var.zone_balancing_enabled + log_analytics_workspace_id = module.log_analytics.id + diagnostic_setting_name = var.diagnostic_settings_name + metric_categories = var.metric_categories + tags = var.tags +} + +# Create the web app and its diagnostic setting. The package holds the source code, so the deployment builds it. The +# web app reaches the Cosmos DB account with DefaultAzureCredential as its managed identity, so no key is set anywhere: +# for a user-assigned identity, AZURE_CLIENT_ID tells DefaultAzureCredential which identity to use. +module "web_app" { + source = "./modules/web_app" + name = local.web_app_name + resource_group_name = azurerm_resource_group.example.name + location = azurerm_resource_group.example.location + service_plan_id = module.app_service_plan.id + https_only = var.https_only + public_network_access_enabled = var.webapp_public_network_access_enabled + always_on = var.always_on + http2_enabled = var.http2_enabled + minimum_tls_version = var.minimum_tls_version + dotnet_version = var.dotnet_version + identity_type = var.managed_identity_type + identity_ids = var.managed_identity_type == "UserAssigned" ? [module.managed_identity[0].id] : [] + log_analytics_workspace_id = module.log_analytics.id + diagnostic_setting_name = var.diagnostic_settings_name + log_categories = var.log_categories + metric_categories = var.metric_categories + tags = var.tags + + app_settings = merge( + { + SCM_DO_BUILD_DURING_DEPLOYMENT = "true" + ENABLE_ORYX_BUILD = "true" + AZURECOSMOSDB_ENDPOINT = module.cosmosdb.endpoint + AZURECOSMOSDB_DATABASENAME = module.cosmosdb.database_name + AZURECOSMOSDB_CONTAINERNAME = module.cosmosdb.container_name + APPLICATIONINSIGHTS_CONNECTION_STRING = module.application_insights.connection_string + }, + var.managed_identity_type == "UserAssigned" ? { AZURE_CLIENT_ID = module.managed_identity[0].client_id } : {} + ) +} + +# Assign the Cosmos DB Built-in Data Contributor role on the whole account to the identity of the web app. A Cosmos DB +# data role is assigned with a SQL role assignment of the account, not with an Azure RBAC role assignment. The +# system-assigned identity exists only once the web app does, so the role is assigned after the web app is created. +resource "azurerm_cosmosdb_sql_role_assignment" "data_contributor" { + resource_group_name = azurerm_resource_group.example.name + account_name = module.cosmosdb.name + role_definition_id = "${module.cosmosdb.id}/sqlRoleDefinitions/${local.cosmosdb_data_contributor_role_id}" + principal_id = var.managed_identity_type == "UserAssigned" ? module.managed_identity[0].principal_id : module.web_app.principal_id + scope = module.cosmosdb.id +} diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/app_service_plan/main.tf b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/app_service_plan/main.tf new file mode 100644 index 00000000..44b9821a --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/app_service_plan/main.tf @@ -0,0 +1,35 @@ +resource "azurerm_service_plan" "example" { + name = var.name + resource_group_name = var.resource_group_name + location = var.location + sku_name = var.sku_name + os_type = var.os_type + zone_balancing_enabled = var.zone_balancing_enabled + tags = var.tags + + lifecycle { + ignore_changes = [ + tags + ] + } +} + +resource "azurerm_monitor_diagnostic_setting" "example" { + name = var.diagnostic_setting_name + target_resource_id = azurerm_service_plan.example.id + log_analytics_workspace_id = var.log_analytics_workspace_id + + dynamic "enabled_log" { + for_each = toset(var.log_categories) + content { + category = enabled_log.value + } + } + + dynamic "enabled_metric" { + for_each = toset(var.metric_categories) + content { + category = enabled_metric.value + } + } +} diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/app_service_plan/outputs.tf b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/app_service_plan/outputs.tf new file mode 100644 index 00000000..f1455ea2 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/app_service_plan/outputs.tf @@ -0,0 +1,19 @@ +output "id" { + value = azurerm_service_plan.example.id + description = "Specifies the resource id of the App Service Plan" +} + +output "name" { + value = azurerm_service_plan.example.name + description = "Specifies the name of the App Service Plan" +} + +output "location" { + value = azurerm_service_plan.example.location + description = "Specifies the location of the App Service Plan" +} + +output "resource_group_name" { + value = azurerm_service_plan.example.resource_group_name + description = "Specifies the resource group name of the App Service Plan" +} diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/app_service_plan/variables.tf b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/app_service_plan/variables.tf new file mode 100644 index 00000000..31f1030a --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/app_service_plan/variables.tf @@ -0,0 +1,60 @@ +variable "resource_group_name" { + description = "(Required) Specifies the name of the resource group." + type = string +} + +variable "location" { + description = "(Required) Specifies the location for the App Service Plan." + type = string +} + +variable "name" { + description = "(Required) Specifies the name of the App Service Plan." + type = string +} + +variable "sku_name" { + description = "(Required) Specifies the SKU name for the App Service Plan." + type = string +} + +variable "os_type" { + description = "(Required) Specifies the O/S type for the App Services to be hosted in this plan." + type = string + default = "Linux" +} + +variable "zone_balancing_enabled" { + description = "(Optional) Should the Service Plan balance across Availability Zones in the region." + type = bool + default = false +} + +variable "tags" { + description = "(Optional) Specifies the tags to be applied to the resources." + type = map(any) + default = {} +} + +variable "log_analytics_workspace_id" { + description = "Specifies the resource id of the Azure Log Analytics workspace." + type = string +} + +variable "diagnostic_setting_name" { + description = "(Optional) Specifies the name of the diagnostic setting. Defaults to DiagnosticsSettings." + type = string + default = "DiagnosticsSettings" +} + +variable "log_categories" { + description = "(Optional) Specifies the log categories the diagnostic setting enables." + type = list(string) + default = [] +} + +variable "metric_categories" { + description = "(Optional) Specifies the metric categories the diagnostic setting enables." + type = list(string) + default = ["AllMetrics"] +} diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/application_insights/main.tf b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/application_insights/main.tf new file mode 100644 index 00000000..4211e713 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/application_insights/main.tf @@ -0,0 +1,20 @@ +# The component has no diagnostic setting: its telemetry is already stored in the workspace it's based on, and a +# diagnostic setting of a workspace-based component can't send to that workspace. +resource "azurerm_application_insights" "example" { + name = var.name + location = var.location + resource_group_name = var.resource_group_name + tags = var.tags + application_type = var.application_type + workspace_id = var.workspace_id + ip_masking_enabled = var.ip_masking_enabled + local_authentication_enabled = var.local_authentication_enabled + internet_ingestion_enabled = var.internet_ingestion_enabled + internet_query_enabled = var.internet_query_enabled + + lifecycle { + ignore_changes = [ + tags + ] + } +} diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/application_insights/outputs.tf b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/application_insights/outputs.tf new file mode 100644 index 00000000..a113e5cf --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/application_insights/outputs.tf @@ -0,0 +1,24 @@ +output "name" { + value = azurerm_application_insights.example.name + description = "Specifies the name of the resource." +} + +output "id" { + value = azurerm_application_insights.example.id + description = "Specifies the resource id of the resource." +} + +output "instrumentation_key" { + value = azurerm_application_insights.example.instrumentation_key + description = "Specifies the instrumentation key of the Application Insights." +} + +output "app_id" { + value = azurerm_application_insights.example.app_id + description = "Specifies the resource id of the resource." +} + +output "connection_string" { + value = azurerm_application_insights.example.connection_string + description = "Specifies the connection string of the Application Insights." +} diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/application_insights/variables.tf b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/application_insights/variables.tf new file mode 100644 index 00000000..80e646d2 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/application_insights/variables.tf @@ -0,0 +1,55 @@ +variable "name" { + description = "(Required) Specifies the name of the resource. Changing this forces a new resource to be created." + type = string +} + +variable "resource_group_name" { + description = "(Required) The name of the resource group in which to create the resource. Changing this forces a new resource to be created." + type = string +} + +variable "location" { + description = "(Required) Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created." + type = string +} + +variable "application_type" { + description = "(Required) Specifies the type of Application Insights to create. Valid values are ios for iOS, java for Java web, MobileCenter for App Center, Node.JS for Node.js, other for General, phone for Windows Phone, store for Windows Store and web for ASP.NET. Please note these values are case sensitive; unmatched values are treated as ASP.NET by Azure. Changing this forces a new resource to be created." + type = string + default = "web" +} + +variable "workspace_id" { + description = "(Optional) Specifies the id of a log analytics workspace resource. Changing this forces a new resource to be created." + type = string +} + +variable "tags" { + description = "(Optional) Specifies the tags to be applied to the resources" + type = map(any) + default = {} +} + +variable "ip_masking_enabled" { + description = "(Optional) Specifies whether IP masking is enabled." + type = bool + default = true +} + +variable "local_authentication_enabled" { + description = "(Optional) Specifies whether local authentication is enabled." + type = bool + default = true +} + +variable "internet_ingestion_enabled" { + description = "(Optional) Specifies whether the public network access for ingestion is enabled." + type = bool + default = true +} + +variable "internet_query_enabled" { + description = "(Optional) Specifies whether the public network access for query is enabled." + type = bool + default = true +} diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/cosmosdb_nosql/main.tf b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/cosmosdb_nosql/main.tf new file mode 100644 index 00000000..8e8857cd --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/cosmosdb_nosql/main.tf @@ -0,0 +1,67 @@ +resource "azurerm_cosmosdb_account" "example" { + name = var.name + resource_group_name = var.resource_group_name + location = var.location + offer_type = "Standard" + kind = "GlobalDocumentDB" + automatic_failover_enabled = false + tags = var.tags + + consistency_policy { + consistency_level = var.consistency_level + } + + geo_location { + location = var.location + failover_priority = 0 + } + + lifecycle { + ignore_changes = [ + tags + ] + } +} + +# Created after the diagnostic setting, so the ControlPlaneRequests log records the creation of the database and of the +# container +resource "azurerm_cosmosdb_sql_database" "example" { + name = var.database_name + resource_group_name = var.resource_group_name + account_name = azurerm_cosmosdb_account.example.name + + depends_on = [ + azurerm_monitor_diagnostic_setting.example + ] +} + +resource "azurerm_cosmosdb_sql_container" "example" { + name = var.container_name + resource_group_name = var.resource_group_name + account_name = azurerm_cosmosdb_account.example.name + database_name = azurerm_cosmosdb_sql_database.example.name + partition_key_paths = [var.partition_key_path] + throughput = var.container_throughput +} + +# The logs go to resource-specific tables (CDBDataPlaneRequests, CDBControlPlaneRequests) rather than AzureDiagnostics +resource "azurerm_monitor_diagnostic_setting" "example" { + name = var.diagnostic_setting_name + target_resource_id = azurerm_cosmosdb_account.example.id + log_analytics_workspace_id = var.log_analytics_workspace_id + log_analytics_destination_type = "Dedicated" + + dynamic "enabled_log" { + for_each = toset(var.log_categories) + content { + category = enabled_log.value + } + } + + dynamic "enabled_metric" { + for_each = toset(var.metric_categories) + content { + category = enabled_metric.value + } + } +} diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/cosmosdb_nosql/outputs.tf b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/cosmosdb_nosql/outputs.tf new file mode 100644 index 00000000..89016c17 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/cosmosdb_nosql/outputs.tf @@ -0,0 +1,24 @@ +output "id" { + description = "Specifies the resource id of the Azure Cosmos DB account." + value = azurerm_cosmosdb_account.example.id +} + +output "name" { + description = "Specifies the name of the Azure Cosmos DB account." + value = azurerm_cosmosdb_account.example.name +} + +output "endpoint" { + description = "Specifies the endpoint of the Azure Cosmos DB account." + value = azurerm_cosmosdb_account.example.endpoint +} + +output "database_name" { + description = "Specifies the name of the Cosmos DB for NoSQL database." + value = azurerm_cosmosdb_sql_database.example.name +} + +output "container_name" { + description = "Specifies the name of the container." + value = azurerm_cosmosdb_sql_container.example.name +} diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/cosmosdb_nosql/variables.tf b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/cosmosdb_nosql/variables.tf new file mode 100644 index 00000000..03d5f22b --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/cosmosdb_nosql/variables.tf @@ -0,0 +1,75 @@ +variable "name" { + description = "(Required) Specifies the name of the Azure Cosmos DB for NoSQL account." + type = string +} + +variable "resource_group_name" { + description = "(Required) Specifies the name of the resource group." + type = string +} + +variable "location" { + description = "(Required) Specifies the location of the Azure Cosmos DB account." + type = string +} + +variable "consistency_level" { + description = "(Optional) Specifies the default consistency level of the Azure Cosmos DB account." + type = string + default = "Session" + + validation { + condition = contains(["BoundedStaleness", "Eventual", "Session", "Strong", "ConsistentPrefix"], var.consistency_level) + error_message = "The consistency_level must be one of BoundedStaleness, Eventual, Session, Strong or ConsistentPrefix." + } +} + +variable "database_name" { + description = "(Required) Specifies the name of the Cosmos DB for NoSQL database." + type = string +} + +variable "container_name" { + description = "(Required) Specifies the name of the container." + type = string +} + +variable "partition_key_path" { + description = "(Required) Specifies the partition key path of the container." + type = string +} + +variable "container_throughput" { + description = "(Optional) Specifies the throughput of the container, in request units per second." + type = number + default = 400 +} + +variable "log_analytics_workspace_id" { + description = "(Required) Specifies the resource id of the Log Analytics workspace." + type = string +} + +variable "diagnostic_setting_name" { + description = "(Optional) Specifies the name of the diagnostic setting of the Azure Cosmos DB account." + type = string + default = "default" +} + +variable "log_categories" { + description = "(Optional) Specifies the log categories the diagnostic setting sends to the Log Analytics workspace: the requests of the web app (DataPlaneRequests) and the requests Azure Resource Manager sends to the account (ControlPlaneRequests)." + type = list(string) + default = ["DataPlaneRequests", "ControlPlaneRequests"] +} + +variable "metric_categories" { + description = "(Optional) Specifies the metric categories the diagnostic setting sends to the Log Analytics workspace." + type = list(string) + default = ["Requests"] +} + +variable "tags" { + description = "(Optional) Specifies the tags of the Azure Cosmos DB account." + type = map(any) + default = {} +} diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/log_analytics/main.tf b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/log_analytics/main.tf new file mode 100644 index 00000000..fcd10cb2 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/log_analytics/main.tf @@ -0,0 +1,35 @@ +resource "azurerm_log_analytics_workspace" "example" { + name = var.name + location = var.location + resource_group_name = var.resource_group_name + sku = var.sku + tags = var.tags + retention_in_days = var.retention_in_days != "" ? var.retention_in_days : null + + lifecycle { + ignore_changes = [ + tags + ] + } +} + +# Query auditing: the diagnostic setting of a workspace can send its audit records to the workspace itself. +resource "azurerm_monitor_diagnostic_setting" "example" { + name = var.diagnostic_setting_name + target_resource_id = azurerm_log_analytics_workspace.example.id + log_analytics_workspace_id = azurerm_log_analytics_workspace.example.id + + dynamic "enabled_log" { + for_each = toset(var.log_categories) + content { + category = enabled_log.value + } + } + + dynamic "enabled_metric" { + for_each = toset(var.metric_categories) + content { + category = enabled_metric.value + } + } +} diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/log_analytics/output.tf b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/log_analytics/output.tf new file mode 100644 index 00000000..fe2c398c --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/log_analytics/output.tf @@ -0,0 +1,30 @@ +output "id" { + value = azurerm_log_analytics_workspace.example.id + description = "Specifies the resource id of the log analytics workspace" +} + +output "location" { + value = azurerm_log_analytics_workspace.example.location + description = "Specifies the location of the log analytics workspace" +} + +output "name" { + value = azurerm_log_analytics_workspace.example.name + description = "Specifies the name of the log analytics workspace" +} + +output "resource_group_name" { + value = azurerm_log_analytics_workspace.example.resource_group_name + description = "Specifies the name of the resource group that contains the log analytics workspace" +} + +output "workspace_id" { + value = azurerm_log_analytics_workspace.example.workspace_id + description = "Specifies the workspace id of the log analytics workspace" +} + +output "primary_shared_key" { + value = azurerm_log_analytics_workspace.example.primary_shared_key + description = "Specifies the workspace key of the log analytics workspace" + sensitive = true +} diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/log_analytics/variables.tf b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/log_analytics/variables.tf new file mode 100644 index 00000000..713a0aa1 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/log_analytics/variables.tf @@ -0,0 +1,55 @@ +variable "resource_group_name" { + description = "(Required) Specifies the name of the resource group." + type = string +} + +variable "location" { + description = "(Required) Specifies the location of the Azure Log Analytics workspace" + type = string +} + +variable "name" { + description = "(Required) Specifies the name of the Azure Log Analytics workspace" + type = string +} + +variable "sku" { + description = "(Optional) Specifies the sku of the Azure Log Analytics workspace" + type = string + default = "PerGB2018" + + validation { + condition = contains(["Free", "Standalone", "PerNode", "PerGB2018"], var.sku) + error_message = "The log analytics sku is incorrect." + } +} + +variable "retention_in_days" { + description = " (Optional) Specifies the workspace data retention in days. Possible values are either 7 (Free Tier only) or range between 30 and 730." + type = number + default = 30 +} + +variable "tags" { + description = "(Optional) Specifies the tags of the Azure Log Analytics workspace." + type = map(any) + default = {} +} + +variable "diagnostic_setting_name" { + description = "(Optional) Specifies the name of the diagnostic setting of the workspace." + type = string + default = "default" +} + +variable "log_categories" { + description = "(Optional) Specifies the log categories that the diagnostic setting of the workspace sends to the workspace itself. Audit records the queries run on the workspace in the LAQueryLogs table." + type = list(string) + default = ["Audit"] +} + +variable "metric_categories" { + description = "(Optional) Specifies the metric categories that the diagnostic setting of the workspace sends to the workspace itself." + type = list(string) + default = ["AllMetrics"] +} diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/managed_identity/main.tf b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/managed_identity/main.tf new file mode 100644 index 00000000..6b312c05 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/managed_identity/main.tf @@ -0,0 +1,14 @@ +# The identity a workload authenticates with. Role assignments are not created here: the role_assignment module +# grants the identity access to the resources the workload uses. +resource "azurerm_user_assigned_identity" "identity" { + name = var.name + resource_group_name = var.resource_group_name + location = var.location + tags = var.tags + + lifecycle { + ignore_changes = [ + tags + ] + } +} diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/managed_identity/outputs.tf b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/managed_identity/outputs.tf new file mode 100644 index 00000000..a23d5861 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/managed_identity/outputs.tf @@ -0,0 +1,24 @@ +output "id" { + description = "Specifies the resource id of the user-assigned managed identity." + value = azurerm_user_assigned_identity.identity.id +} + +output "name" { + description = "Specifies the name of the user-assigned managed identity." + value = azurerm_user_assigned_identity.identity.name +} + +output "client_id" { + description = "Specifies the client id of the user-assigned managed identity, the value a workload passes as AZURE_CLIENT_ID." + value = azurerm_user_assigned_identity.identity.client_id +} + +output "principal_id" { + description = "Specifies the principal (object) id of the user-assigned managed identity, the value role assignments are keyed on." + value = azurerm_user_assigned_identity.identity.principal_id +} + +output "tenant_id" { + description = "Specifies the tenant id of the user-assigned managed identity." + value = azurerm_user_assigned_identity.identity.tenant_id +} diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/managed_identity/variables.tf b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/managed_identity/variables.tf new file mode 100644 index 00000000..b54f3504 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/managed_identity/variables.tf @@ -0,0 +1,20 @@ +variable "name" { + description = "(Required) Specifies the name of the user-assigned managed identity. Changing this forces a new resource to be created." + type = string +} + +variable "resource_group_name" { + description = "(Required) Specifies the name of the resource group of the user-assigned managed identity." + type = string +} + +variable "location" { + description = "(Required) Specifies the location where the user-assigned managed identity is deployed." + type = string +} + +variable "tags" { + description = "(Optional) Specifies the tags of the user-assigned managed identity." + type = map(any) + default = {} +} diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/web_app/main.tf b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/web_app/main.tf new file mode 100644 index 00000000..1a57f1fd --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/web_app/main.tf @@ -0,0 +1,55 @@ +resource "azurerm_linux_web_app" "example" { + name = var.name + resource_group_name = var.resource_group_name + location = var.location + service_plan_id = var.service_plan_id + https_only = var.https_only + public_network_access_enabled = var.public_network_access_enabled + client_affinity_enabled = var.client_affinity_enabled + tags = var.tags + + identity { + type = var.identity_type + identity_ids = var.identity_type == "UserAssigned" ? var.identity_ids : null + } + + site_config { + always_on = var.always_on + http2_enabled = var.http2_enabled + minimum_tls_version = var.minimum_tls_version + + # Exactly one of the two versions is set: the other one is null, which leaves it out. + application_stack { + python_version = var.python_version + dotnet_version = var.dotnet_version + } + } + + app_settings = var.app_settings + + lifecycle { + ignore_changes = [ + tags + ] + } +} + +resource "azurerm_monitor_diagnostic_setting" "example" { + name = var.diagnostic_setting_name + target_resource_id = azurerm_linux_web_app.example.id + log_analytics_workspace_id = var.log_analytics_workspace_id + + dynamic "enabled_log" { + for_each = toset(var.log_categories) + content { + category = enabled_log.value + } + } + + dynamic "enabled_metric" { + for_each = toset(var.metric_categories) + content { + category = enabled_metric.value + } + } +} diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/web_app/outputs.tf b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/web_app/outputs.tf new file mode 100644 index 00000000..76d1b268 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/web_app/outputs.tf @@ -0,0 +1,19 @@ +output "id" { + value = azurerm_linux_web_app.example.id + description = "Specifies the resource id of the Web App" +} + +output "name" { + value = azurerm_linux_web_app.example.name + description = "Specifies the name of the Web App" +} + +output "default_hostname" { + value = azurerm_linux_web_app.example.default_hostname + description = "Specifies the default hostname of the Web App" +} + +output "principal_id" { + value = var.identity_type == "SystemAssigned" ? azurerm_linux_web_app.example.identity[0].principal_id : null + description = "Specifies the principal id of the system-assigned managed identity, or null when the Web App uses a user-assigned identity (its principal id comes from the managed_identity module)" +} diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/web_app/variables.tf b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/web_app/variables.tf new file mode 100644 index 00000000..18d08a69 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/modules/web_app/variables.tf @@ -0,0 +1,127 @@ +variable "resource_group_name" { + description = "(Required) Specifies the name of the resource group." + type = string +} + +variable "location" { + description = "(Required) Specifies the location of the Web App." + type = string +} + +variable "name" { + description = "(Required) Specifies the globally unique name of the Web App." + type = string +} + +variable "service_plan_id" { + description = "(Required) Specifies the resource id of the App Service Plan that hosts the Web App." + type = string +} + +variable "https_only" { + description = "(Optional) Specifies whether the Web App requires HTTPS connections." + type = bool + default = false +} + +variable "public_network_access_enabled" { + description = "(Optional) Specifies whether the public network access is enabled." + type = bool + default = true +} + +variable "client_affinity_enabled" { + description = "(Optional) Specifies whether client affinity (ARR affinity) is enabled." + type = bool + default = false +} + +variable "always_on" { + description = "(Optional) Specifies whether the Web App is always on." + type = bool + default = true +} + +variable "http2_enabled" { + description = "(Optional) Specifies whether HTTP/2 is enabled." + type = bool + default = false +} + +variable "minimum_tls_version" { + description = "(Optional) Specifies the minimum TLS version of the Web App." + type = string + default = "1.2" +} + +variable "python_version" { + description = "(Optional) Specifies the Python version of the Web App. Set either python_version or dotnet_version." + type = string + default = null +} + +variable "dotnet_version" { + description = "(Optional) Specifies the .NET version of the Web App. Set either python_version or dotnet_version." + type = string + default = null +} + +variable "identity_type" { + description = "(Optional) Specifies the type of managed identity of the Web App: SystemAssigned or UserAssigned." + type = string + default = "SystemAssigned" + + validation { + condition = contains(["SystemAssigned", "UserAssigned"], var.identity_type) + error_message = "The identity_type must be either SystemAssigned or UserAssigned." + } +} + +variable "identity_ids" { + description = "(Optional) Specifies the resource ids of the user-assigned managed identities of the Web App. Used only when identity_type is UserAssigned." + type = list(string) + default = [] +} + +variable "app_settings" { + description = "(Optional) Specifies the app settings of the Web App." + type = map(string) + default = {} +} + +variable "log_analytics_workspace_id" { + description = "(Required) Specifies the resource id of the Log Analytics workspace." + type = string +} + +variable "diagnostic_setting_name" { + description = "(Optional) Specifies the name of the diagnostic setting of the Web App." + type = string + default = "default" +} + +variable "log_categories" { + description = "(Optional) Specifies the log categories that the diagnostic setting of the Web App sends to the Log Analytics workspace." + type = list(string) + default = [ + "AppServiceHTTPLogs", + "AppServiceConsoleLogs", + "AppServiceAppLogs", + "AppServiceAuditLogs", + "AppServiceIPSecAuditLogs", + "AppServicePlatformLogs", + "AppServiceAuthenticationLogs", + ] +} + +variable "metric_categories" { + description = "(Optional) Specifies the metric categories that the diagnostic setting of the Web App sends to the Log Analytics workspace." + type = list(string) + default = ["AllMetrics"] +} + +variable "tags" { + description = "(Optional) Specifies the tags of the Web App." + type = map(any) + default = {} +} diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/outputs.tf b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/outputs.tf new file mode 100644 index 00000000..fa1d0e83 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/outputs.tf @@ -0,0 +1,44 @@ +output "resource_group_name" { + value = azurerm_resource_group.example.name +} + +output "app_service_plan_name" { + value = module.app_service_plan.name +} + +output "web_app_name" { + value = module.web_app.name +} + +output "web_app_url" { + value = module.web_app.default_hostname +} + +output "cosmosdb_account_name" { + value = module.cosmosdb.name +} + +output "cosmosdb_endpoint" { + value = module.cosmosdb.endpoint +} + +output "cosmosdb_database_name" { + value = module.cosmosdb.database_name +} + +output "cosmosdb_container_name" { + value = module.cosmosdb.container_name +} + +output "principal_id" { + description = "The principal id of the managed identity the web app reaches the Cosmos DB account with." + value = var.managed_identity_type == "UserAssigned" ? module.managed_identity[0].principal_id : module.web_app.principal_id +} + +output "log_analytics_name" { + value = module.log_analytics.name +} + +output "application_insights_name" { + value = module.application_insights.name +} diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/providers.tf b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/providers.tf new file mode 100644 index 00000000..2757acc5 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/providers.tf @@ -0,0 +1,24 @@ +terraform { + required_version = ">=1.0" + + required_providers { + azurerm = { + source = "hashicorp/azurerm" + version = "=5.1.0" + } + } +} + +provider "azurerm" { + features { + resource_group { + prevent_deletion_if_contains_resources = false + } + } + + # Dual-target, deliberately: nothing emulator-specific is hardcoded here. deploy.sh exports ARM_SUBSCRIPTION_ID and + # ARM_TENANT_ID on both targets and, only when the active az cloud is LocalStack, ARM_METADATA_HOSTNAME (the + # emulator's metadata endpoint, from which the provider discovers every other endpoint). Authentication uses the + # Azure CLI session on both targets. Running terraform directly rather than through deploy.sh needs those variables + # exported. +} diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/terraform.tfvars b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/terraform.tfvars new file mode 100644 index 00000000..2c3f770e --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/terraform.tfvars @@ -0,0 +1,2 @@ +location = "westeurope" +dotnet_version = "10.0" \ No newline at end of file diff --git a/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/variables.tf b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/variables.tf new file mode 100644 index 00000000..5f761f9d --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/dotnet/terraform/variables.tf @@ -0,0 +1,191 @@ +variable "prefix" { + description = "(Optional) Specifies the prefix for the name of the Azure resources." + type = string + default = "local" + + validation { + condition = var.prefix == null || length(var.prefix) >= 2 + error_message = "The prefix must be at least 2 characters long." + } +} + +variable "suffix" { + description = "(Optional) Specifies the suffix for the name of the Azure resources." + type = string + default = "test" + + validation { + condition = var.suffix == null || length(var.suffix) >= 2 + error_message = "The suffix must be at least 2 characters long." + } +} + +variable "location" { + description = "(Required) Specifies the location for all resources." + type = string + default = null +} + +variable "cosmosdb_database_name" { + description = "(Optional) Specifies the name of the Cosmos DB for NoSQL database." + type = string + default = "vacationplanner" +} + +variable "cosmosdb_container_name" { + description = "(Optional) Specifies the name of the container that holds the activities." + type = string + default = "activities" +} + +variable "cosmosdb_partition_key_path" { + description = "(Optional) Specifies the partition key path of the container." + type = string + default = "/username" +} + +variable "cosmosdb_container_throughput" { + description = "(Optional) Specifies the throughput of the container, in request units per second." + type = number + default = 400 +} + +variable "os_type" { + description = "(Required) Specifies the O/S type for the App Services to be hosted in this plan. Possible values include Windows, Linux, and WindowsContainer. Changing this forces a new resource to be created." + type = string + default = "Linux" + + validation { + condition = contains([ + "Windows", + "Linux", + "WindowsContainer" + ], var.os_type) + error_message = "The os_type must be either 'Windows', 'Linux', or 'WindowsContainer'." + } +} + +variable "zone_balancing_enabled" { + description = "(Optional) Should the Service Plan balance across Availability Zones in the region." + type = bool + default = false +} + +variable "sku_name" { + description = "(Optional) Specifies the SKU name for the hosting plan." + type = string + default = "B1" + + validation { + condition = contains([ + "B1", "B2", "B3", + "S1", "S2", "S3", + "EP1", "EP2", "EP3", + "P1v2", "P2v2", "P3v2", + "P0v3", "P1v3", "P2v3", "P3v3", + "P1mv3", "P2mv3", "P3mv3", "P4mv3", "P5mv3", + "I1", "I2", "I3", + "I1v2", "I2v2", "I3v2", "I4v2", "I5v2", "I6v2", + "WS1", "WS2", "WS3", + "FC1" + ], var.sku_name) + error_message = "The sku_name must be one of the allowed values." + } +} + +variable "dotnet_version" { + description = "(Optional) Specifies the version of .NET to run. Possible values include 8.0, 9.0 and 10.0." + type = string + default = "10.0" + + validation { + condition = contains(["8.0", "9.0", "10.0"], var.dotnet_version) + error_message = "The dotnet_version must be one of the supported versions: 8.0, 9.0, 10.0." + } +} + +variable "https_only" { + description = "(Optional) Specifies whether the Linux Web App require HTTPS connections. Defaults to false." + type = bool + default = false +} + +variable "minimum_tls_version" { + description = "(Optional) Specifies the minimum version of TLS required for SSL requests. Possible values include: 1.0, 1.1, 1.2 and 1.3. Defaults to 1.2." + type = string + default = "1.2" + + validation { + condition = contains([ + "1.0", + "1.1", + "1.2", + "1.3" + ], var.minimum_tls_version) + error_message = "The minimum_tls_version must be one of the allowed values." + } +} + +variable "always_on" { + description = "(Optional) Specifies whether the Linux Web App is Always On enabled. Defaults to true." + type = bool + default = true +} + +variable "http2_enabled" { + description = "(Optional) Specifies whether HTTP/2 is enabled for the Linux Web App." + type = bool + default = false +} + +variable "webapp_public_network_access_enabled" { + description = "(Optional) Specifies whether the public network access is enabled or disabled." + type = bool + default = true +} + +variable "managed_identity_type" { + description = "(Optional) Specifies the type of managed identity the web app reaches the Cosmos DB account with, through Microsoft Entra ID." + type = string + default = "UserAssigned" + + validation { + condition = contains(["SystemAssigned", "UserAssigned"], var.managed_identity_type) + error_message = "The managed_identity_type must be either 'SystemAssigned' or 'UserAssigned'." + } +} + +variable "tags" { + description = "(Optional) Specifies the tags to be applied to the resources." + type = map(string) + default = { + environment = "test" + iac = "terraform" + } +} + +variable "diagnostic_settings_name" { + description = "(Optional) Specifies the name of the diagnostic settings of the Cosmos DB account, of the web app and of the App Service plan." + type = string + default = "default" +} + +variable "log_categories" { + description = "(Optional) Specifies the log categories that the diagnostic settings of the web app send to the Log Analytics workspace." + type = list(string) + default = [ + "AppServiceHTTPLogs", + "AppServiceConsoleLogs", + "AppServiceAppLogs", + "AppServiceAuditLogs", + "AppServiceIPSecAuditLogs", + "AppServicePlatformLogs", + "AppServiceAuthenticationLogs", + ] +} + +variable "metric_categories" { + description = "(Optional) Specifies the metric categories that the diagnostic settings of the web app and of the App Service plan send to the Log Analytics workspace." + type = list(string) + default = ["AllMetrics"] +} diff --git a/samples/web-app-cosmosdb-nosql-api/python/README.md b/samples/web-app-cosmosdb-nosql-api/python/README.md index 62aeb42b..b5b4386d 100644 --- a/samples/web-app-cosmosdb-nosql-api/python/README.md +++ b/samples/web-app-cosmosdb-nosql-api/python/README.md @@ -11,6 +11,7 @@ The following diagram illustrates the architecture of the solution: - **Azure Web App**: Hosts the Python Flask application - **Azure App Service Plan**: Provides compute resources for the web app - **Azure CosmosDB for NoSQL API**: Stores activity data in a CosmosDB container +- **Managed identity**: The web app authenticates to the CosmosDB account with Microsoft Entra ID, as a system-assigned or user-assigned managed identity that has the Cosmos DB Built-in Data Contributor role on the account, instead of the account key. The Bicep and Terraform deployments always use one, the Azure CLI scripts with `MANAGED_IDENTITY_TYPE=SystemAssigned` or `UserAssigned`. See [Microsoft Entra ID authentication](#microsoft-entra-id-authentication) - **Azure Log Analytics workspace**: Centralizes the diagnostic logs and metrics of the web app, its plan and the CosmosDB account, the telemetry of Application Insights, and the audit records of the queries run on it - **Azure Application Insights**: A workspace-based resource that collects the requests, the calls to Azure Cosmos DB, the log records, the exceptions, the custom events and the custom metric of the web app, which the Microsoft OpenTelemetry Distro sends to the connection string of the `APPLICATIONINSIGHTS_CONNECTION_STRING` app setting. See [Application Insights](#application-insights) @@ -19,6 +20,7 @@ The following diagram illustrates the architecture of the solution: - [lstk CLI](https://docs.localstack.cloud/aws/developer-tools/running-localstack/lstk/) - [Azure Subscription](https://azure.microsoft.com/free/) - [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli) +- [Terraform](https://developer.hashicorp.com/terraform/downloads), if you plan to install the sample via Terraform. - [Python 3.11+](https://www.python.org/downloads/) - [Flask](https://flask.palletsprojects.com/) @@ -52,10 +54,44 @@ lstk az start-interception Deploy the application to LocalStack for Azure using: - [Azure CLI Deployment](./scripts/README.md) +- [Bicep Deployment](./bicep/README.md) +- [Terraform Deployment](./terraform/README.md) > [!NOTE] > When you deploy the application to LocalStack for Azure for the first time, the initialization process involves downloading and building Docker images. This is a one-time operation—subsequent deployments will be significantly faster. Depending on your internet connection and system resources, this initial setup may take several minutes. +### Microsoft Entra ID authentication + +The web app reaches the CosmosDB account either with the account's primary key, in the `AZURECOSMOSDB_PRIMARY_KEY` app setting, or with Microsoft Entra ID, as a managed identity that has the [Cosmos DB Built-in Data Contributor](https://learn.microsoft.com/en-us/azure/cosmos-db/reference-data-plane-security#built-in-roles) role on the whole account, with no key anywhere. `MANAGED_IDENTITY_TYPE` picks one: + +| Deployment | `MANAGED_IDENTITY_TYPE` | Default | +| --- | --- | --- | +| [Azure CLI](./scripts/README.md) | `None` (the account key), `SystemAssigned` or `UserAssigned` | `None` | +| [Bicep](./bicep/README.md) | `SystemAssigned` or `UserAssigned` | `UserAssigned` | +| [Terraform](./terraform/README.md) | `SystemAssigned` or `UserAssigned` | `UserAssigned` | + +The three deployments give the resources the same names, so the validation script checks any of them. Pass it the same `MANAGED_IDENTITY_TYPE`: + +```bash +# Azure CLI, with the web app's system-assigned identity +MANAGED_IDENTITY_TYPE=SystemAssigned bash scripts/deploy.sh +MANAGED_IDENTITY_TYPE=SystemAssigned bash scripts/validate.sh + +# Bicep, with a user-assigned identity (for Terraform, run terraform/deploy.sh) +MANAGED_IDENTITY_TYPE=UserAssigned bash bicep/deploy.sh +MANAGED_IDENTITY_TYPE=UserAssigned bash scripts/validate.sh +``` + +With a managed identity, each deployment: + +- gives the web app a system-assigned managed identity, or creates a user-assigned managed identity, assigns it to the web app, and passes its client id in the `AZURE_CLIENT_ID` app setting +- assigns the identity the Cosmos DB Built-in Data Contributor role on the whole account. It's a role of the CosmosDB account itself (a SQL role assignment), not an Azure RBAC role: the Azure CLI scripts run `az cosmosdb sql role assignment create`, the Bicep template deploys a `Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments` resource ([cosmos-db-sql-role-assignment.bicep](./bicep/modules/cosmos-db-sql-role-assignment.bicep)), and the Terraform configuration an `azurerm_cosmosdb_sql_role_assignment` resource ([main.tf](./terraform/main.tf)) +- creates the database and the container through Azure Resource Manager, because CosmosDB refuses to let a Microsoft Entra identity create them, whatever its roles + +Without a key, the app passes `DefaultAzureCredential` to `CosmosClient` (see [cosmosdb_client.py](./src/cosmosdb_client.py)), which gets a token for the web app's managed identity, on Azure and in the emulator alike. With the managed identity, the validation script also checks the role assignment and adds an activity through the web app, finds it on its page and deletes it. On Azure, a new role assignment can take a few minutes to take effect: the script retries meanwhile. + +By default, the emulator serves the web app's requests whatever role its identity has. Start it with `LS_AZURE_ENFORCE_RBAC=1` to have it authorize each request against the account's role assignments, as Azure does. + ## Test 1. Retrieve the host port Docker maps to the port the Web App listens on in its container, for example with `docker port ` (the container's name starts with `ls-`). Do not assume port 80: the app listens on the port its `WEBSITES_PORT` app setting names, when it has one. diff --git a/samples/web-app-cosmosdb-nosql-api/python/bicep/README.md b/samples/web-app-cosmosdb-nosql-api/python/bicep/README.md new file mode 100644 index 00000000..6c56aa45 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/bicep/README.md @@ -0,0 +1,149 @@ +# Bicep Deployment + +This directory contains the Bicep template and a deployment script for provisioning the sample in LocalStack for Azure or in Azure. Refer to the [Azure Web App with Azure CosmosDB for NoSQL API](../README.md) guide for details about the sample application. + +## Prerequisites + +Before deploying this solution, ensure you have the following tools installed: + +- [LocalStack for Azure](https://docs.localstack.cloud/azure/): Local Azure cloud emulator for development and testing +- [Visual Studio Code](https://code.visualstudio.com/): Code editor installed on one of the [supported platforms](https://code.visualstudio.com/docs/supporting/requirements#_platforms) +- [Bicep extension](https://learn.microsoft.com/en-us/azure/azure-resource-manager/bicep/install#visual-studio-code-and-bicep-extension): VS Code extension for Bicep language support and IntelliSense +- [Docker](https://docs.docker.com/get-docker/): Container runtime required for LocalStack +- [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli): Azure command-line interface, which installs the [Bicep CLI](https://learn.microsoft.com/en-us/azure/azure-resource-manager/bicep/install) on first use +- [lstk CLI](https://docs.localstack.cloud/aws/developer-tools/running-localstack/lstk/): LocalStack command-line interface (proxies the Azure CLI via `lstk az`) +- [Python](https://www.python.org/downloads/): Python runtime (version 3.12 or above) +- [jq](https://jqlang.org/): JSON processor for scripting and parsing command outputs + +### Installing lstk CLI + +Deploying to LocalStack requires the `lstk` CLI, which routes Azure CLI commands to the emulator (run `lstk az start-interception` before deploying). Install it using Homebrew: + +```bash +brew install localstack/tap/lstk +``` + +or npm: + +```bash +npm install -g @localstack/lstk +``` + +Alternatively, download a pre-built binary from the [lstk releases page](https://github.com/localstack/lstk/releases). For more information, see the [lstk CLI documentation](https://docs.localstack.cloud/aws/developer-tools/running-localstack/lstk/) and the [lstk GitHub repository](https://github.com/localstack/lstk). + +## Architecture Overview + +The [deploy.sh](deploy.sh) script creates the [resource group](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/manage-resource-groups-cli), while [main.bicep](main.bicep) creates the following resources, each through a module in the [modules](modules) folder: + +1. [Azure Cosmos DB for NoSQL account](https://learn.microsoft.com/en-us/azure/cosmos-db/overview) ([cosmos-db.bicep](modules/cosmos-db.bicep)): the account, the `vacationplanner` database, and the `activities` container, partitioned by `/username`, with 400 request units per second. +2. [Managed identity](https://learn.microsoft.com/en-us/entra/identity/managed-identities-azure-resources/overview) ([managed-identity.bicep](modules/managed-identity.bicep)): with `MANAGED_IDENTITY_TYPE=UserAssigned`, the default, a user-assigned identity assigned to the web app. With `MANAGED_IDENTITY_TYPE=SystemAssigned`, the web app's own identity instead, which the web app module enables. +3. [Cosmos DB SQL role assignment](https://learn.microsoft.com/en-us/azure/templates/microsoft.documentdb/databaseaccounts/sqlroleassignments) ([cosmos-db-sql-role-assignment.bicep](modules/cosmos-db-sql-role-assignment.bicep)): grants the identity the [Cosmos DB Built-in Data Contributor](https://learn.microsoft.com/en-us/azure/cosmos-db/reference-data-plane-security#built-in-roles) role on the whole account. It's a role of the Cosmos DB account itself, not an Azure RBAC role. +4. [Azure App Service plan](https://learn.microsoft.com/en-us/azure/app-service/overview-hosting-plans) ([app-service-plan.bicep](modules/app-service-plan.bicep)): a B1 Linux plan that hosts the web app. +5. [Azure Web App](https://learn.microsoft.com/en-us/azure/app-service/overview) ([web-app.bicep](modules/web-app.bicep)): hosts the Python Flask *Vacation Planner* application. Its app settings hold the endpoint of the account and the names of the database and the container, and, for a user-assigned identity, its client id in `AZURE_CLIENT_ID`. They hold no key: the app passes `DefaultAzureCredential` to `CosmosClient`, which gets a token for the web app's managed identity. +6. [Log Analytics workspace](https://learn.microsoft.com/en-us/azure/azure-monitor/logs/log-analytics-workspace-overview) ([log-analytics.bicep](modules/log-analytics.bicep)): stores the telemetry of Application Insights, the logs and metrics that the diagnostic settings send to it, and the audit records of the queries run on it. +7. [Application Insights](https://learn.microsoft.com/en-us/azure/azure-monitor/app/app-insights-overview) ([application-insights.bicep](modules/application-insights.bicep)): a workspace-based resource that collects the requests, the calls to Azure Cosmos DB, the log records, the exceptions, the custom events and the custom metric of the web app. +8. [Diagnostic settings](https://learn.microsoft.com/en-us/azure/azure-monitor/data-collection/diagnostic-settings): send the logs and metrics of the web app, the metrics of the App Service plan, the `DataPlaneRequests` and `ControlPlaneRequests` logs and the `Requests` metrics of the Cosmos DB account (in the resource-specific tables `CDBDataPlaneRequests` and `CDBControlPlaneRequests`), and the query audit of the workspace to the Log Analytics workspace. + +The resources get the same names as with the [Azure CLI scripts](../scripts/README.md), so the scripts in the [scripts](../scripts) folder validate this deployment and query its telemetry, logs and metrics too. + +## Provisioning Scripts + +See [deploy.sh](deploy.sh) for the complete deployment script. The script performs the following operations: + +- Creates the resource group if it doesn't exist +- Validates the Bicep template, or previews its changes with a what-if operation when `USE_WHAT_IF` is set to `1` in the script +- Deploys the Bicep template, with the managed identity type in `MANAGED_IDENTITY_TYPE`: `UserAssigned` (the default) or `SystemAssigned` +- Extracts the deployment outputs (resource names, URLs) using jq +- Packages the web application code into a zip file and deploys it to the web app, which builds it +- Removes the zip file + +## Deployment + +You can set up the Azure emulator by utilizing LocalStack for Azure Docker image. Before starting, ensure you have a valid `LOCALSTACK_AUTH_TOKEN` to access the Azure emulator. Refer to the [Auth Token guide](https://docs.localstack.cloud/getting-started/auth-token/) to obtain your Auth Token and specify it in the `LOCALSTACK_AUTH_TOKEN` environment variable. The Azure Docker image is available on the [LocalStack Docker Hub](https://hub.docker.com/r/localstack/localstack-azure). To pull the Azure Docker image, execute the following command: + +```bash +docker pull localstack/localstack-azure +``` + +Start the LocalStack Azure emulator with the lstk CLI: + +```bash +# Set the authentication token +export LOCALSTACK_AUTH_TOKEN= + +# Start the LocalStack Azure emulator +lstk start --type azure + +# Route all Azure CLI calls to the LocalStack Azure emulator +lstk az start-interception +``` + +Navigate to the `bicep` folder: + +```bash +cd samples/web-app-cosmosdb-nosql-api/python/bicep +``` + +Make the script executable: + +```bash +chmod +x deploy.sh +``` + +Run the deployment script, which gives the web app a user-assigned managed identity: + +```bash +./deploy.sh +``` + +To use the web app's system-assigned managed identity instead, set `MANAGED_IDENTITY_TYPE`: + +```bash +MANAGED_IDENTITY_TYPE=SystemAssigned ./deploy.sh +``` + +The same script deploys the sample to Azure: run `lstk az stop-interception` to route the Azure CLI back to Azure, sign in with `az login`, and run it again. See [Microsoft Entra ID authentication](../README.md#microsoft-entra-id-authentication). + +## Validation + +After deployment, run the validation script of the [scripts](../scripts) folder with the same `MANAGED_IDENTITY_TYPE`: + +```bash +MANAGED_IDENTITY_TYPE=UserAssigned ../scripts/validate.sh +``` + +It shows the resource group, the App Service plan, the web app, the Cosmos DB account, the Log Analytics workspace, the Application Insights component and the resources of the group. It then checks that the managed identity has the Cosmos DB Built-in Data Contributor role on the account, adds an activity through the web app, finds it on the page, and deletes it. On Azure, a new role assignment can take a few minutes to take effect, and the script retries meanwhile. + +## Telemetry, logs and metrics + +Read the telemetry the web app sent to Application Insights and the logs and metrics the diagnostic settings sent to the workspace: + +```bash +../scripts/query-telemetry.sh +../scripts/query-logs-and-metrics.sh +``` + +See [Application Insights](../README.md#application-insights) and [Logs and metrics](../README.md#logs-and-metrics) for what they read. + +## Cleanup + +To destroy all created resources: + +```bash +# Delete resource group and all contained resources +az group delete --name local-rg --yes --no-wait + +# Verify deletion +az group list --output table +``` + +This will remove all Azure resources created by the Bicep template. + +## Related Documentation + +- [Azure Bicep Documentation](https://learn.microsoft.com/en-us/azure/azure-resource-manager/bicep/) +- [Bicep reference for Cosmos DB SQL role assignments](https://learn.microsoft.com/en-us/azure/templates/microsoft.documentdb/databaseaccounts/sqlroleassignments) +- [Connect to Azure Cosmos DB for NoSQL with role-based access control and Microsoft Entra ID](https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-connect-role-based-access-control) +- [LocalStack for Azure Documentation](https://docs.localstack.cloud/azure/) +- [lstk CLI](https://docs.localstack.cloud/aws/developer-tools/running-localstack/lstk/) +- [lstk GitHub repository](https://github.com/localstack/lstk) diff --git a/samples/web-app-cosmosdb-nosql-api/python/bicep/deploy.sh b/samples/web-app-cosmosdb-nosql-api/python/bicep/deploy.sh new file mode 100755 index 00000000..ea596c44 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/bicep/deploy.sh @@ -0,0 +1,188 @@ +#!/bin/bash + +# Variables +PREFIX="${PREFIX:-local}" +SUFFIX="${SUFFIX:-test}" +TEMPLATE="main.bicep" +PARAMETERS="main.bicepparam" +RESOURCE_GROUP_NAME="$PREFIX-rg" +LOCATION="westeurope" +VALIDATE_TEMPLATE=1 +USE_WHAT_IF=0 +SUBSCRIPTION_NAME=$(az account show --query name --output tsv) +CURRENT_DIR="$(cd "$(dirname "$0")" && pwd)" + +# The web app reaches the Cosmos DB account with Microsoft Entra ID, as a managed identity granted the Cosmos DB +# Built-in Data Contributor role on the account: no key appears anywhere. UserAssigned (the default) creates a +# user-assigned identity and assigns it to the web app; SystemAssigned enables the web app's own identity. +MANAGED_IDENTITY_TYPE="${MANAGED_IDENTITY_TYPE:-UserAssigned}" + +case "$MANAGED_IDENTITY_TYPE" in +SystemAssigned | UserAssigned) ;; +*) + echo "MANAGED_IDENTITY_TYPE must be SystemAssigned or UserAssigned, not [$MANAGED_IDENTITY_TYPE]." + exit 1 + ;; +esac + +# Change the current directory to the script's directory +cd "$CURRENT_DIR" || exit + +# Validates if the resource group exists in the subscription, if not creates it +echo "Checking if resource group [$RESOURCE_GROUP_NAME] exists in the subscription [$SUBSCRIPTION_NAME]..." +az group show --name $RESOURCE_GROUP_NAME &>/dev/null + +if [[ $? != 0 ]]; then + echo "No resource group [$RESOURCE_GROUP_NAME] exists in the subscription [$SUBSCRIPTION_NAME]" + echo "Creating resource group [$RESOURCE_GROUP_NAME] in the subscription [$SUBSCRIPTION_NAME]..." + + # Create the resource group + az group create \ + --name $RESOURCE_GROUP_NAME \ + --location $LOCATION \ + --only-show-errors 1>/dev/null + + if [[ $? == 0 ]]; then + echo "Resource group [$RESOURCE_GROUP_NAME] successfully created in the subscription [$SUBSCRIPTION_NAME]" + else + echo "Failed to create resource group [$RESOURCE_GROUP_NAME] in the subscription [$SUBSCRIPTION_NAME]" + exit 1 + fi +else + echo "Resource group [$RESOURCE_GROUP_NAME] already exists in the subscription [$SUBSCRIPTION_NAME]" +fi + +# Validates the Bicep template +if [[ $VALIDATE_TEMPLATE == 1 ]]; then + if [[ $USE_WHAT_IF == 1 ]]; then + # Execute a deployment What-If operation at resource group scope. + echo "Previewing changes deployed by Bicep template [$TEMPLATE]..." + az deployment group what-if \ + --resource-group $RESOURCE_GROUP_NAME \ + --template-file $TEMPLATE \ + --parameters $PARAMETERS \ + --parameters location=$LOCATION \ + prefix=$PREFIX \ + suffix=$SUFFIX \ + managedIdentityType=$MANAGED_IDENTITY_TYPE \ + --only-show-errors + + if [[ $? == 0 ]]; then + echo "Bicep template [$TEMPLATE] validation succeeded" + else + echo "Failed to validate Bicep template [$TEMPLATE]" + exit 1 + fi + else + # Validate the Bicep template + echo "Validating Bicep template [$TEMPLATE]..." + output=$(az deployment group validate \ + --resource-group $RESOURCE_GROUP_NAME \ + --template-file $TEMPLATE \ + --parameters $PARAMETERS \ + --parameters location=$LOCATION \ + prefix=$PREFIX \ + suffix=$SUFFIX \ + managedIdentityType=$MANAGED_IDENTITY_TYPE \ + --only-show-errors) + + if [[ $? == 0 ]]; then + echo "Bicep template [$TEMPLATE] validation succeeded" + else + echo "Failed to validate Bicep template [$TEMPLATE]" + echo "$output" + exit 1 + fi + fi +fi + +# Deploy the Bicep template +echo "Deploying Bicep template [$TEMPLATE] with a [$MANAGED_IDENTITY_TYPE] managed identity..." +if DEPLOYMENT_OUTPUTS=$(az deployment group create \ + --resource-group $RESOURCE_GROUP_NAME \ + --only-show-errors \ + --template-file $TEMPLATE \ + --parameters $PARAMETERS \ + --parameters location=$LOCATION \ + prefix=$PREFIX \ + suffix=$SUFFIX \ + managedIdentityType=$MANAGED_IDENTITY_TYPE \ + --query 'properties.outputs' -o json); then + echo "Bicep template [$TEMPLATE] deployed successfully. Outputs:" + echo "$DEPLOYMENT_OUTPUTS" | jq . + APP_SERVICE_PLAN_NAME=$(echo "$DEPLOYMENT_OUTPUTS" | jq -r '.appServicePlanName.value') + WEB_APP_NAME=$(echo "$DEPLOYMENT_OUTPUTS" | jq -r '.webAppName.value') + WEB_APP_URL=$(echo "$DEPLOYMENT_OUTPUTS" | jq -r '.webAppUrl.value') + COSMOSDB_ACCOUNT_NAME=$(echo "$DEPLOYMENT_OUTPUTS" | jq -r '.cosmosDbAccountName.value') + COSMOSDB_ENDPOINT=$(echo "$DEPLOYMENT_OUTPUTS" | jq -r '.cosmosDbEndpoint.value') + PRINCIPAL_ID=$(echo "$DEPLOYMENT_OUTPUTS" | jq -r '.principalId.value') + echo "Deployment details:" + echo "- appServicePlanName: $APP_SERVICE_PLAN_NAME" + echo "- webAppName: $WEB_APP_NAME" + echo "- webAppUrl: $WEB_APP_URL" + echo "- cosmosDbAccountName: $COSMOSDB_ACCOUNT_NAME" + echo "- cosmosDbEndpoint: $COSMOSDB_ENDPOINT" + echo "- principalId of the [$MANAGED_IDENTITY_TYPE] managed identity: $PRINCIPAL_ID" +else + echo "Failed to deploy Bicep template [$TEMPLATE]" + exit 1 +fi + +# Validation before deploying the web app +if [[ -z "$WEB_APP_NAME" || "$WEB_APP_NAME" == "null" ]]; then + echo "Web App Name is empty. Exiting." + exit 1 +fi + +# The zip package is named after the web app, so deployments with different prefixes don't overwrite each other's +ZIPFILE="${WEB_APP_NAME}.zip" + +# CD into the web app directory +cd ../src || exit + +# Remove any existing zip package of the web app +if [ -f "$ZIPFILE" ]; then + rm "$ZIPFILE" +fi + +# Create the zip package of the web app +echo "Creating zip package of the web app..." +zip -r "$ZIPFILE" app.py cosmosdb_client.py gunicorn.conf.py static templates requirements.txt + +# Deploy the web app +echo "Deploying web app [$WEB_APP_NAME] with zip file [$ZIPFILE]..." +# On Azure the deployment service can answer 504 Gateway Timeout while it warms up, or DeploymentInProgress while +# the build of the previous deployment still runs: the upload is tried again. The startup of the site isn't +# tracked: the tracking counted a failed start of the container that ran before the code was deployed, and +# reported a running site as failed after ten minutes; what calls the web app afterwards waits for it instead. +WEBAPP_DEPLOY_RETRY_COUNT="${WEBAPP_DEPLOY_RETRY_COUNT:-10}" +WEBAPP_DEPLOY_RETRY_SLEEP="${WEBAPP_DEPLOY_RETRY_SLEEP:-30}" +WEBAPP_DEPLOYED=0 +for ATTEMPT in $(seq 1 "$WEBAPP_DEPLOY_RETRY_COUNT"); do + if az webapp deploy \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --name "$WEB_APP_NAME" \ + --src-path "$ZIPFILE" \ + --type zip \ + --async true \ + --track-status false 1>/dev/null; then + WEBAPP_DEPLOYED=1 + break + fi + if [ "$ATTEMPT" -lt "$WEBAPP_DEPLOY_RETRY_COUNT" ]; then + echo "Attempt $ATTEMPT of $WEBAPP_DEPLOY_RETRY_COUNT to deploy web app [$WEB_APP_NAME] failed. Waiting [$WEBAPP_DEPLOY_RETRY_SLEEP] seconds before retry..." + sleep "$WEBAPP_DEPLOY_RETRY_SLEEP" + fi +done + +if [ $WEBAPP_DEPLOYED -eq 1 ]; then + echo "Web app [$WEB_APP_NAME] deployed successfully." +else + echo "Failed to deploy web app [$WEB_APP_NAME]." + exit 1 +fi + +# Remove the zip package of the web app +if [ -f "$ZIPFILE" ]; then + rm "$ZIPFILE" +fi diff --git a/samples/web-app-cosmosdb-nosql-api/python/bicep/main.bicep b/samples/web-app-cosmosdb-nosql-api/python/bicep/main.bicep new file mode 100644 index 00000000..620fe0e8 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/bicep/main.bicep @@ -0,0 +1,325 @@ +@description('Specifies the prefix for the name of the Azure resources.') +@minLength(2) +param prefix string = take(uniqueString(resourceGroup().id), 4) + +@description('Specifies the suffix for the name of the Azure resources.') +@minLength(2) +param suffix string = take(uniqueString(resourceGroup().id), 4) + +@description('Specifies the location for all resources.') +param location string = resourceGroup().location + +@description('Specifies the tier name for the hosting plan.') +@allowed([ + 'Basic' + 'Standard' + 'ElasticPremium' + 'Premium' + 'PremiumV2' + 'Premium0V3' + 'PremiumV3' + 'PremiumMV3' + 'Isolated' + 'IsolatedV2' + 'WorkflowStandard' + 'FlexConsumption' +]) +param skuTier string = 'Basic' + +@description('Specifies the SKU name for the hosting plan.') +@allowed([ + 'B1' + 'B2' + 'B3' + 'S1' + 'S2' + 'S3' + 'EP1' + 'EP2' + 'EP3' + 'P1' + 'P2' + 'P3' + 'P1V2' + 'P2V2' + 'P3V2' + 'P0V3' + 'P1V3' + 'P2V3' + 'P3V3' + 'P1MV3' + 'P2MV3' + 'P3MV3' + 'P4MV3' + 'P5MV3' + 'I1' + 'I2' + 'I3' + 'I1V2' + 'I2V2' + 'I3V2' + 'I4V2' + 'I5V2' + 'I6V2' + 'WS1' + 'WS2' + 'WS3' + 'FC1' +]) +param skuName string = 'B1' + +@description('Specifies the kind of the hosting plan.') +@allowed([ + 'app' + 'elastic' + 'functionapp' + 'windows' + 'linux' +]) +param appServicePlanKind string = 'linux' + +@description('Specifies whether the hosting plan is reserved.') +param reserved bool = true + +@description('Specifies whether the hosting plan is zone redundant.') +param appServicePlanZoneRedundant bool = false + +@description('Specifies the language runtime used by the Azure Web App.') +@allowed([ + 'dotnet' + 'dotnetcore' + 'dotnet-isolated' + 'python' + 'java' + 'node' + 'powerShell' + 'custom' +]) +param runtimeName string + +@description('Specifies the target language version used by the Azure Web App.') +param runtimeVersion string + +@description('Specifies the kind of the hosting plan.') +@allowed([ + 'app' // Windows Web app + 'app,linux' // Linux Web app + 'app,linux,container' // Linux Container Web app + 'hyperV' // Windows Container Web App + 'app,container,windows' // Windows Container Web App + 'app,linux,kubernetes' // Linux Web App on ARC + 'app,linux,container,kubernetes' // Linux Container Web App on ARC + 'functionapp' // Function Code App + 'functionapp,linux' // Linux Consumption Function app + 'functionapp,linux,container,kubernetes' // Function Container App on ARC + 'functionapp,linux,kubernetes' // Function Code App on ARC +]) +param webAppKind string = 'app,linux' + +@description('Specifies whether HTTPS is enforced for the Azure Web App.') +param httpsOnly bool = false + +@description('Specifies the minimum TLS version for the Azure Web App.') +@allowed([ + '1.0' + '1.1' + '1.2' + '1.3' +]) +param minTlsVersion string = '1.2' + +@description('Specifies whether the public network access is enabled or disabled') +@allowed([ + 'Enabled' + 'Disabled' +]) +param publicNetworkAccess string = 'Enabled' + +@description('Specifies the optional Git Repo URL.') +param repoUrl string = '' + +@description('Specifies the tags to be applied to the resources.') +param tags object = { + environment: 'test' + iac: 'bicep' +} + +@description('Specifies the name of the Cosmos DB for NoSQL database.') +param databaseName string = 'vacationplanner' + +@description('Specifies the name of the container that holds the activities.') +param containerName string = 'activities' + +@description('Specifies the partition key path of the container.') +param partitionKeyPath string = '/username' + +@description('Specifies the throughput of the container, in request units per second.') +param containerThroughput int = 400 + +@description('Specifies the type of managed identity the web app reaches the Cosmos DB account with, through Microsoft Entra ID.') +@allowed([ + 'SystemAssigned' + 'UserAssigned' +]) +param managedIdentityType string = 'UserAssigned' + +@description('Specifies the name of the diagnostic settings of the web app and of the App Service plan.') +param diagnosticSettingsName string = 'default' + +@description('Specifies the log categories that the diagnostic settings of the web app send to the Log Analytics workspace.') +param logCategories array = [ + 'AppServiceHTTPLogs' + 'AppServiceConsoleLogs' + 'AppServiceAppLogs' + 'AppServiceAuditLogs' + 'AppServiceIPSecAuditLogs' + 'AppServicePlatformLogs' + 'AppServiceAuthenticationLogs' +] + +@description('Specifies the metric categories that the diagnostic settings of the web app and of the App Service plan send to the Log Analytics workspace.') +param metricCategories array = [ + 'AllMetrics' +] + +//******************************************** +// Variables +//******************************************** +// The names the Azure CLI scripts of this sample give the same resources, so the scripts in ../scripts that validate +// the deployment and query its telemetry, logs and metrics work on this deployment too +var webAppName = '${prefix}-webapp-nosql-${suffix}' +var appServicePlanName = webAppName +var cosmosDbAccountName = webAppName +var managedIdentityName = '${prefix}-webapp-nosql-identity-${suffix}' +var logAnalyticsName = '${prefix}-log-analytics-${suffix}' +var applicationInsightsName = '${prefix}-insights-${suffix}' + +// The id of the Cosmos DB Built-in Data Contributor role, a data-plane role every Cosmos DB for NoSQL account has +// under this id. It is a role of the account (a SQL role definition), not an Azure RBAC role. +var cosmosDbDataContributorRoleDefinitionId = '00000000-0000-0000-0000-000000000002' + +//******************************************** +// Modules +//******************************************** +module workspace 'modules/log-analytics.bicep' = { + name: 'workspace' + params: { + name: logAnalyticsName + location: location + tags: tags + } +} + +module applicationInsights 'modules/application-insights.bicep' = { + name: 'applicationInsights' + params: { + name: applicationInsightsName + location: location + workspaceId: workspace.outputs.id + tags: tags + } +} + +module cosmosDb 'modules/cosmos-db.bicep' = { + name: 'cosmosDb' + params: { + name: cosmosDbAccountName + location: location + databaseName: databaseName + containerName: containerName + partitionKeyPath: partitionKeyPath + throughput: containerThroughput + diagnosticSettingsName: diagnosticSettingsName + workspaceId: workspace.outputs.id + tags: tags + } +} + +module managedIdentity 'modules/managed-identity.bicep' = if (managedIdentityType == 'UserAssigned') { + name: 'managedIdentity' + params: { + name: managedIdentityName + location: location + tags: tags + } +} + +module appServicePlan 'modules/app-service-plan.bicep' = { + name: 'appServicePlan' + params: { + name: appServicePlanName + location: location + skuTier: skuTier + skuName: skuName + kind: appServicePlanKind + reserved: reserved + zoneRedundant: appServicePlanZoneRedundant + maximumElasticWorkerCount: skuTier == 'FlexConsumption' ? 1 : 20 + diagnosticSettingsName: diagnosticSettingsName + metricCategories: metricCategories + workspaceId: workspace.outputs.id + tags: tags + } +} + +// The package holds the source code, so the deployment builds it. The web app reaches the Cosmos DB account with +// DefaultAzureCredential as its managed identity, so no key is set anywhere: for a user-assigned identity, +// AZURE_CLIENT_ID tells DefaultAzureCredential which identity to use. +module webApp 'modules/web-app.bicep' = { + name: 'webApp' + params: { + name: webAppName + location: location + kind: webAppKind + runtimeName: runtimeName + runtimeVersion: runtimeVersion + httpsOnly: httpsOnly + minTlsVersion: minTlsVersion + publicNetworkAccess: publicNetworkAccess + identityType: managedIdentityType + managedIdentityId: managedIdentityType == 'UserAssigned' ? managedIdentity!.outputs.id : '' + hostingPlanName: appServicePlan.outputs.name + appSettings: union( + { + SCM_DO_BUILD_DURING_DEPLOYMENT: 'true' + ENABLE_ORYX_BUILD: 'true' + AZURECOSMOSDB_ENDPOINT: cosmosDb.outputs.documentEndpoint + AZURECOSMOSDB_DATABASENAME: cosmosDb.outputs.databaseName + AZURECOSMOSDB_CONTAINERNAME: cosmosDb.outputs.containerName + APPLICATIONINSIGHTS_CONNECTION_STRING: applicationInsights.outputs.connectionString + }, + managedIdentityType == 'UserAssigned' ? { AZURE_CLIENT_ID: managedIdentity!.outputs.clientId } : {} + ) + repoUrl: repoUrl + diagnosticSettingsName: diagnosticSettingsName + logCategories: logCategories + metricCategories: metricCategories + workspaceId: workspace.outputs.id + tags: tags + } +} + +// The web app's identity reads and writes the activities in the container: the system-assigned identity exists only +// once the web app does, so the role is assigned after the web app is created. +module cosmosDbDataContributorRoleAssignment 'modules/cosmos-db-sql-role-assignment.bicep' = { + name: 'cosmosDbDataContributorRoleAssignment' + params: { + cosmosDbAccountName: cosmosDb.outputs.name + roleDefinitionId: cosmosDbDataContributorRoleDefinitionId + principalId: managedIdentityType == 'SystemAssigned' ? webApp.outputs.principalId : managedIdentity!.outputs.principalId + } +} + +//******************************************** +// Outputs +//******************************************** +output appServicePlanName string = appServicePlan.outputs.name +output webAppName string = webApp.outputs.name +output webAppUrl string = webApp.outputs.defaultHostName +output cosmosDbAccountName string = cosmosDb.outputs.name +output cosmosDbEndpoint string = cosmosDb.outputs.documentEndpoint +output databaseName string = cosmosDb.outputs.databaseName +output containerName string = cosmosDb.outputs.containerName +output principalId string = managedIdentityType == 'SystemAssigned' ? webApp.outputs.principalId : managedIdentity!.outputs.principalId +output logAnalyticsName string = workspace.outputs.name +output applicationInsightsName string = applicationInsights.outputs.name diff --git a/samples/web-app-cosmosdb-nosql-api/python/bicep/main.bicepparam b/samples/web-app-cosmosdb-nosql-api/python/bicep/main.bicepparam new file mode 100644 index 00000000..da8c51f7 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/bicep/main.bicepparam @@ -0,0 +1,6 @@ +using 'main.bicep' + +param prefix = 'local' +param suffix = 'test' +param runtimeName = 'python' +param runtimeVersion = '3.13' diff --git a/samples/web-app-cosmosdb-nosql-api/python/bicep/modules/app-service-plan.bicep b/samples/web-app-cosmosdb-nosql-api/python/bicep/modules/app-service-plan.bicep new file mode 100644 index 00000000..3fab18c1 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/bicep/modules/app-service-plan.bicep @@ -0,0 +1,155 @@ +//******************************************** +// Parameters +//******************************************** +@description('Specifies the name of the App Service Plan.') +param name string + +@description('Specifies the location.') +param location string = resourceGroup().location + +@description('Specifies the tier name for the hosting plan.') +@allowed([ + 'Basic' + 'Standard' + 'ElasticPremium' + 'Premium' + 'PremiumV2' + 'Premium0V3' + 'PremiumV3' + 'PremiumMV3' + 'Isolated' + 'IsolatedV2' + 'WorkflowStandard' + 'FlexConsumption' +]) +param skuTier string = 'Standard' + +@description('Specifies the SKU name for the hosting plan.') +@allowed([ + 'B1' + 'B2' + 'B3' + 'S1' + 'S2' + 'S3' + 'EP1' + 'EP2' + 'EP3' + 'P1' + 'P2' + 'P3' + 'P1V2' + 'P2V2' + 'P3V2' + 'P0V3' + 'P1V3' + 'P2V3' + 'P3V3' + 'P1MV3' + 'P2MV3' + 'P3MV3' + 'P4MV3' + 'P5MV3' + 'I1' + 'I2' + 'I3' + 'I1V2' + 'I2V2' + 'I3V2' + 'I4V2' + 'I5V2' + 'I6V2' + 'WS1' + 'WS2' + 'WS3' + 'FC1' +]) +param skuName string = 'S1' + +@description('Specifies the kind of the hosting plan.') +@allowed([ + 'app' + 'elastic' + 'functionapp' + 'windows' + 'linux' +]) +param kind string = 'linux' + +@description('Specifies whether the hosting plan is reserved.') +param reserved bool = true + +@description('Specifies whether the hosting plan is zone redundant.') +param zoneRedundant bool = false + +@description('Specifies the maximum number of elastic workers of the hosting plan.') +param maximumElasticWorkerCount int = 20 + +@description('Specifies the name of the diagnostic settings.') +param diagnosticSettingsName string = 'default' + +@description('Specifies the log categories enabled by the diagnostic settings.') +param logCategories array = [] + +@description('Specifies the metric categories enabled by the diagnostic settings.') +param metricCategories array = [ + 'AllMetrics' +] + +@description('Specifies the resource id of the Log Analytics workspace.') +param workspaceId string + +@description('Specifies the tags to be applied to the resources.') +param tags object = {} + +//******************************************** +// Variables +//******************************************** + +var logs = [ + for category in logCategories: { + category: category + enabled: true + } +] +var metrics = [ + for category in metricCategories: { + category: category + enabled: true + } +] + +//******************************************** +// Resources +//******************************************** +resource appServicePlan 'Microsoft.Web/serverfarms@2024-11-01' = { + name: name + location: location + tags: tags + kind: kind + sku: { + tier: skuTier + name: skuName + } + properties: { + reserved: reserved + zoneRedundant: zoneRedundant + maximumElasticWorkerCount: maximumElasticWorkerCount + } +} + +resource diagnosticSettings 'Microsoft.Insights/diagnosticSettings@2021-05-01-preview' = if(!empty(workspaceId)) { + name: diagnosticSettingsName + scope: appServicePlan + properties: { + workspaceId: workspaceId + logs: logs + metrics: metrics + } +} + +//******************************************** +// Outputs +//******************************************** +output id string = appServicePlan.id +output name string = appServicePlan.name diff --git a/samples/web-app-cosmosdb-nosql-api/python/bicep/modules/application-insights.bicep b/samples/web-app-cosmosdb-nosql-api/python/bicep/modules/application-insights.bicep new file mode 100644 index 00000000..9fe2907f --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/bicep/modules/application-insights.bicep @@ -0,0 +1,79 @@ +//******************************************** +// Parameters +//******************************************** + +@description('Specifies the name of the Azure Application Insights.') +param name string + +@description('Specifies the location.') +param location string = resourceGroup().location + +@description('Specifies the type of application being monitored.') +@allowed([ + 'web' + 'other' +]) +param applicationType string = 'web' + +@description('Specifies whether IP masking is enabled.') +param disableIpMasking bool = false + +@description('Specifies whether the application is enabled for local authentication.') +param disableLocalAuth bool = false + +@description('Specifies whether purging data immediately after 30 days.') +param immediatePurgeDataOn30Days bool = true + +@description('Specifies the network access type for accessing Application Insights ingestion.') +@allowed([ + 'Enabled' + 'Disabled' +]) +param publicNetworkAccessForIngestion string = 'Enabled' + +@description('Specifies the network access type for accessing Application Insights query.') +@allowed([ + 'Enabled' + 'Disabled' +]) +param publicNetworkAccessForQuery string = 'Enabled' + +@description('Specifies the Azure Log Analytics workspace ID.') +param workspaceId string + +@description('Specifies the resource tags.') +param tags object + +//******************************************** +// Resources +//******************************************** + +// The component has no diagnostic settings: its telemetry is already stored in the workspace it's based on, and a +// diagnostic setting of a workspace-based component can't send to that workspace. +resource applicationInsights 'Microsoft.Insights/components@2020-02-02' = { + name: name + location: location + tags: tags + kind: 'web' + properties: { + Application_Type: applicationType + DisableIpMasking: disableIpMasking + DisableLocalAuth: disableLocalAuth + Flow_Type: 'Bluefield' + ImmediatePurgeDataOn30Days: immediatePurgeDataOn30Days + IngestionMode: 'LogAnalytics' + publicNetworkAccessForIngestion: publicNetworkAccessForIngestion + publicNetworkAccessForQuery: publicNetworkAccessForQuery + Request_Source: 'rest' + WorkspaceResourceId: workspaceId + } +} + +//******************************************** +// Outputs +//******************************************** + +output id string = applicationInsights.id +output name string = applicationInsights.name +output connectionString string = applicationInsights.properties.ConnectionString +output instrumentationKey string = applicationInsights.properties.InstrumentationKey diff --git a/samples/web-app-cosmosdb-nosql-api/python/bicep/modules/cosmos-db-sql-role-assignment.bicep b/samples/web-app-cosmosdb-nosql-api/python/bicep/modules/cosmos-db-sql-role-assignment.bicep new file mode 100644 index 00000000..f34a691b --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/bicep/modules/cosmos-db-sql-role-assignment.bicep @@ -0,0 +1,42 @@ +//******************************************** +// Parameters +//******************************************** +@description('Specifies the name of the Azure Cosmos DB for NoSQL account the role is assigned on.') +param cosmosDbAccountName string + +@description('Specifies the id of the SQL role definition to assign: 00000000-0000-0000-0000-000000000001 for Cosmos DB Built-in Data Reader, 00000000-0000-0000-0000-000000000002 for Cosmos DB Built-in Data Contributor.') +param roleDefinitionId string + +@description('Specifies the principal (object) id the role is assigned to. For a managed identity, this is its principal id, never its client id.') +param principalId string + +//******************************************** +// Resources +//******************************************** +resource account 'Microsoft.DocumentDB/databaseAccounts@2025-04-15' existing = { + name: cosmosDbAccountName +} + +resource roleDefinition 'Microsoft.DocumentDB/databaseAccounts/sqlRoleDefinitions@2025-04-15' existing = { + parent: account + name: roleDefinitionId +} + +// A Cosmos DB data role is assigned with a SQL role assignment of the account, not with an Azure RBAC role assignment. +// The name is derived from the account, the principal and the role, so a second deployment updates the same +// assignment instead of creating a duplicate. The scope is the whole account: every database and container in it. +resource roleAssignment 'Microsoft.DocumentDB/databaseAccounts/sqlRoleAssignments@2025-04-15' = { + parent: account + name: guid(account.id, principalId, roleDefinition.id) + properties: { + roleDefinitionId: roleDefinition.id + principalId: principalId + scope: account.id + } +} + +//******************************************** +// Outputs +//******************************************** +output id string = roleAssignment.id +output name string = roleAssignment.name diff --git a/samples/web-app-cosmosdb-nosql-api/python/bicep/modules/cosmos-db.bicep b/samples/web-app-cosmosdb-nosql-api/python/bicep/modules/cosmos-db.bicep new file mode 100644 index 00000000..cc3c7d8e --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/bicep/modules/cosmos-db.bicep @@ -0,0 +1,128 @@ +//******************************************** +// Parameters +//******************************************** +@description('Specifies the name of the Azure Cosmos DB for NoSQL account.') +param name string + +@description('Specifies the location of the Azure Cosmos DB account.') +param location string = resourceGroup().location + +@description('Specifies the name of the Cosmos DB for NoSQL database.') +param databaseName string + +@description('Specifies the name of the container.') +param containerName string + +@description('Specifies the partition key path of the container.') +param partitionKeyPath string + +@description('Specifies the throughput of the container, in request units per second.') +param throughput int = 400 + +@description('Specifies the resource id of the Log Analytics workspace.') +param workspaceId string + +@description('Specifies the name of the diagnostic settings of the Azure Cosmos DB account.') +param diagnosticSettingsName string = 'default' + +@description('Specifies the log categories that the diagnostic settings send to the Log Analytics workspace: the requests of the web app (DataPlaneRequests) and the requests Azure Resource Manager sends to the account (ControlPlaneRequests).') +param logCategories array = [ + 'DataPlaneRequests' + 'ControlPlaneRequests' +] + +@description('Specifies the metric categories that the diagnostic settings send to the Log Analytics workspace.') +param metricCategories array = [ + 'Requests' +] + +@description('Specifies the resource tags.') +param tags object + +//******************************************** +// Resources +//******************************************** +resource account 'Microsoft.DocumentDB/databaseAccounts@2025-04-15' = { + name: name + location: location + kind: 'GlobalDocumentDB' + tags: tags + properties: { + databaseAccountOfferType: 'Standard' + consistencyPolicy: { + defaultConsistencyLevel: 'Session' + } + locations: [ + { + locationName: location + failoverPriority: 0 + isZoneRedundant: false + } + ] + } +} + +// Created after the diagnostic settings, so the ControlPlaneRequests log records the creation of the database and of +// the container +resource database 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases@2025-04-15' = { + parent: account + name: databaseName + dependsOn: [ + diagnosticSettings + ] + properties: { + resource: { + id: databaseName + } + } +} + +resource container 'Microsoft.DocumentDB/databaseAccounts/sqlDatabases/containers@2025-04-15' = { + parent: database + name: containerName + properties: { + resource: { + id: containerName + partitionKey: { + paths: [ + partitionKeyPath + ] + kind: 'Hash' + } + } + options: { + throughput: throughput + } + } +} + +// The logs go to resource-specific tables (CDBDataPlaneRequests, CDBControlPlaneRequests) rather than AzureDiagnostics +resource diagnosticSettings 'Microsoft.Insights/diagnosticSettings@2021-05-01-preview' = { + name: diagnosticSettingsName + scope: account + properties: { + workspaceId: workspaceId + logAnalyticsDestinationType: 'Dedicated' + logs: [ + for category in logCategories: { + category: category + enabled: true + } + ] + metrics: [ + for category in metricCategories: { + category: category + enabled: true + } + ] + } +} + +//******************************************** +// Outputs +//******************************************** +output id string = account.id +output name string = account.name +output documentEndpoint string = account.properties.documentEndpoint +output databaseName string = database.name +output containerName string = container.name diff --git a/samples/web-app-cosmosdb-nosql-api/python/bicep/modules/log-analytics.bicep b/samples/web-app-cosmosdb-nosql-api/python/bicep/modules/log-analytics.bicep new file mode 100644 index 00000000..2096fc03 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/bicep/modules/log-analytics.bicep @@ -0,0 +1,85 @@ +//******************************************** +// Parameters +//******************************************** +@description('Specifies the name of the Log Analytics workspace.') +param name string + +@description('Specifies the location.') +param location string = resourceGroup().location + +@description('Specifies the service tier of the workspace: Free, Standalone, PerNode, Per-GB.') +@allowed([ + 'Free' + 'Standalone' + 'PerNode' + 'PerGB2018' +]) +param sku string = 'PerGB2018' + +@description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') +param retentionInDays int = 60 + +@description('Specifies the name of the diagnostic settings of the workspace.') +param diagnosticSettingsName string = 'default' + +@description('Specifies the log categories that the diagnostic settings of the workspace send to the workspace itself. Audit records the queries run on the workspace in the LAQueryLogs table.') +param logCategories array = [ + 'Audit' +] + +@description('Specifies the metric categories that the diagnostic settings of the workspace send to the workspace itself.') +param metricCategories array = [ + 'AllMetrics' +] + +@description('Specifies the resource tags.') +param tags object + +//******************************************** +// Variables +//******************************************** +var logs = [ + for category in logCategories: { + category: category + enabled: true + } +] +var metrics = [ + for category in metricCategories: { + category: category + enabled: true + } +] + +//******************************************** +// Resources +//******************************************** +resource workspace 'Microsoft.OperationalInsights/workspaces@2025-07-01' = { + name: name + tags: tags + location: location + properties: { + sku: { + name: sku + } + retentionInDays: retentionInDays + } +} + +// Query auditing: the diagnostic settings of a workspace can send its audit records to the workspace itself. +resource diagnosticSettings 'Microsoft.Insights/diagnosticSettings@2021-05-01-preview' = { + name: diagnosticSettingsName + scope: workspace + properties: { + workspaceId: workspace.id + logs: logs + metrics: metrics + } +} + +//******************************************** +// Outputs +//******************************************** +output id string = workspace.id +output name string = workspace.name +output customerId string = workspace.properties.customerId diff --git a/samples/web-app-cosmosdb-nosql-api/python/bicep/modules/managed-identity.bicep b/samples/web-app-cosmosdb-nosql-api/python/bicep/modules/managed-identity.bicep new file mode 100644 index 00000000..7663dd52 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/bicep/modules/managed-identity.bicep @@ -0,0 +1,31 @@ +//******************************************** +// Parameters +//******************************************** +@description('Specifies the name of the user-assigned managed identity.') +param name string + +@description('Specifies the location.') +param location string = resourceGroup().location + +@description('Specifies the resource tags.') +param tags object + +//******************************************** +// Resources +//******************************************** + +// The identity the web app uses to access the storage account. The role assignment lives in the +// storage-account-role-assignment module. +resource managedIdentity 'Microsoft.ManagedIdentity/userAssignedIdentities@2023-01-31' = { + name: name + location: location + tags: tags +} + +//******************************************** +// Outputs +//******************************************** +output id string = managedIdentity.id +output name string = managedIdentity.name +output clientId string = managedIdentity.properties.clientId +output principalId string = managedIdentity.properties.principalId diff --git a/samples/web-app-cosmosdb-nosql-api/python/bicep/modules/web-app.bicep b/samples/web-app-cosmosdb-nosql-api/python/bicep/modules/web-app.bicep new file mode 100644 index 00000000..6c1f0028 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/bicep/modules/web-app.bicep @@ -0,0 +1,193 @@ +//******************************************** +// Parameters +//******************************************** + +@description('Specifies a globally unique name the Azure Web App.') +param name string + +@description('Specifies the location.') +param location string = resourceGroup().location + +@description('Specifies the kind of the Azure Web App.') +@allowed([ + 'app' // Windows Web app + 'app,linux' // Linux Web app + 'app,linux,container' // Linux Container Web app + 'hyperV' // Windows Container Web App + 'app,container,windows' // Windows Container Web App + 'app,linux,kubernetes' // Linux Web App on ARC + 'app,linux,container,kubernetes' // Linux Container Web App on ARC + 'functionapp' // Function Code App + 'functionapp,linux' // Linux Consumption Function app + 'functionapp,linux,container,kubernetes' // Function Container App on ARC + 'functionapp,linux,kubernetes' // Function Code App on ARC +]) +param kind string = 'app,linux' + +@description('Specifies the language runtime used by the Azure Web App.') +@allowed([ + 'dotnet' + 'dotnetcore' + 'dotnet-isolated' + 'python' + 'java' + 'node' + 'powerShell' + 'custom' +]) +param runtimeName string + +@description('Specifies the target language version used by the Azure Web App.') +param runtimeVersion string + +@description('Specifies the minimum TLS version for the Azure Web App.') +@allowed([ + '1.0' + '1.1' + '1.2' + '1.3' +]) +param minTlsVersion string = '1.2' + +@description('Specifies whether the public network access is enabled or disabled') +@allowed([ + 'Enabled' + 'Disabled' +]) +param publicNetworkAccess string = 'Enabled' + +@description('Specifies whether HTTPS is enforced for the Azure Web App.') +param httpsOnly bool = false + +@description('Specifies the type of managed identity of the Azure Web App.') +@allowed([ + 'SystemAssigned' + 'UserAssigned' +]) +param identityType string = 'SystemAssigned' + +@description('Specifies the resource id of the user-assigned managed identity of the Azure Web App. Used only when identityType is UserAssigned.') +param managedIdentityId string = '' + +@description('Specifies the name of the hosting plan.') +param hostingPlanName string + +@description('Specifies the app settings of the Azure Web App.') +param appSettings object = {} + +@description('Specifies the optional Git Repo URL.') +param repoUrl string = '' + +@description('Specifies the branch of the optional Git repository.') +param repoBranch string = 'master' + +@description('Specifies whether the optional Git repository is integrated manually.') +param isManualIntegration bool = true + +@description('Specifies the resource id of the Log Analytics workspace.') +param workspaceId string + +@description('Specifies the name of the diagnostic settings.') +param diagnosticSettingsName string = 'default' + +@description('Specifies the log categories that the diagnostic settings of the Azure Web App send to the Log Analytics workspace.') +param logCategories array = [ + 'AppServiceHTTPLogs' + 'AppServiceConsoleLogs' + 'AppServiceAppLogs' + 'AppServiceAuditLogs' + 'AppServiceIPSecAuditLogs' + 'AppServicePlatformLogs' + 'AppServiceAuthenticationLogs' +] + +@description('Specifies the metric categories that the diagnostic settings of the Azure Web App send to the Log Analytics workspace.') +param metricCategories array = [ + 'AllMetrics' +] + +@description('Specifies the resource tags.') +param tags object + +//******************************************** +// Variables +//******************************************** + +var logs = [ + for category in logCategories: { + category: category + enabled: true + } +] +var metrics = [ + for category in metricCategories: { + category: category + enabled: true + } +] + +//******************************************** +// Resources +//******************************************** + +resource hostingPlan 'Microsoft.Web/serverfarms@2024-11-01' existing = { + name: hostingPlanName +} + +resource webApp 'Microsoft.Web/sites@2024-11-01' = { + name: name + location: location + tags: tags + kind: kind + properties: { + httpsOnly: httpsOnly + serverFarmId: hostingPlan.id + siteConfig: { + linuxFxVersion: toUpper('${runtimeName}|${runtimeVersion}') + minTlsVersion: minTlsVersion + publicNetworkAccess: publicNetworkAccess + } + } + identity: { + type: identityType + userAssignedIdentities: identityType == 'UserAssigned' ? { + '${managedIdentityId}': {} + } : null + } +} + +resource configAppSettings 'Microsoft.Web/sites/config@2024-11-01' = { + parent: webApp + name: 'appsettings' + properties: appSettings +} + +resource webAppSourceControl 'Microsoft.Web/sites/sourcecontrols@2024-11-01' = if (contains(repoUrl, 'http')) { + name: 'web' + parent: webApp + properties: { + repoUrl: repoUrl + branch: repoBranch + isManualIntegration: isManualIntegration + } +} + +resource diagnosticSettings 'Microsoft.Insights/diagnosticSettings@2021-05-01-preview' = if (!empty(workspaceId)) { + name: diagnosticSettingsName + scope: webApp + properties: { + workspaceId: workspaceId + logs: logs + metrics: metrics + } +} + +//******************************************** +// Outputs +//******************************************** +output id string = webApp.id +output name string = webApp.name +output defaultHostName string = webApp.properties.defaultHostName +// The principal id of the system-assigned identity, the value its role assignments are keyed on; empty for a +// user-assigned identity, whose principal id comes from the managed identity module. +output principalId string = identityType == 'SystemAssigned' ? webApp.identity.principalId : '' diff --git a/samples/web-app-cosmosdb-nosql-api/python/scripts/README.md b/samples/web-app-cosmosdb-nosql-api/python/scripts/README.md index 0eff4e28..37af6dab 100644 --- a/samples/web-app-cosmosdb-nosql-api/python/scripts/README.md +++ b/samples/web-app-cosmosdb-nosql-api/python/scripts/README.md @@ -69,6 +69,15 @@ Run the deployment script: ./deploy.sh ``` +By default, the web app reaches the CosmosDB account with its primary key. To have it authenticate with Microsoft Entra ID instead, as a managed identity with the Cosmos DB Built-in Data Contributor role on the account, set `MANAGED_IDENTITY_TYPE` to `SystemAssigned` or `UserAssigned`, and pass the same value to the validation script: + +```bash +MANAGED_IDENTITY_TYPE=UserAssigned ./deploy.sh +MANAGED_IDENTITY_TYPE=UserAssigned ./validate.sh +``` + +See [Microsoft Entra ID authentication](../README.md#microsoft-entra-id-authentication). + ## Validation After deployment, you can use the `validate.sh` script to verify that all resources were created and configured correctly: diff --git a/samples/web-app-cosmosdb-nosql-api/python/scripts/deploy.sh b/samples/web-app-cosmosdb-nosql-api/python/scripts/deploy.sh index 71e69a9b..98ffc13b 100755 --- a/samples/web-app-cosmosdb-nosql-api/python/scripts/deploy.sh +++ b/samples/web-app-cosmosdb-nosql-api/python/scripts/deploy.sh @@ -21,11 +21,79 @@ AZURECOSMOSDB_DATABASENAME="${AZURECOSMOSDB_DATABASENAME:-vacationplanner}" AZURECOSMOSDB_CONTAINERNAME="${AZURECOSMOSDB_CONTAINERNAME:-activities}" AURECOSMOSDB_PARTITION_KEY="/username" +# By default the web app reaches the Cosmos DB account with the account's primary key, which it gets in the +# AZURECOSMOSDB_PRIMARY_KEY app setting. Set MANAGED_IDENTITY_TYPE to SystemAssigned or UserAssigned to have it +# authenticate with Microsoft Entra ID instead, as a managed identity granted the Cosmos DB Built-in Data Contributor +# role on the account: the key then appears nowhere. +MANAGED_IDENTITY_TYPE="${MANAGED_IDENTITY_TYPE:-None}" +MANAGED_IDENTITY_NAME="${PREFIX}-webapp-nosql-identity-${SUFFIX}" +# Cosmos DB Built-in Data Contributor, a data-plane role every Cosmos DB for NoSQL account has under this id. It is a +# role of the account (a SQL role definition), not an Azure RBAC role. +COSMOSDB_DATA_CONTRIBUTOR_ROLE_ID='00000000-0000-0000-0000-000000000002' +# A role is assigned to a managed identity right after the identity is created: the retries cover the time the new +# principal takes to replicate to Microsoft Entra ID +ROLE_ASSIGNMENT_RETRY_COUNT=5 +ROLE_ASSIGNMENT_RETRY_SLEEP=10 + +case "$MANAGED_IDENTITY_TYPE" in +None | SystemAssigned | UserAssigned) ;; +*) + echo "MANAGED_IDENTITY_TYPE must be None, SystemAssigned or UserAssigned, not [$MANAGED_IDENTITY_TYPE]." + exit 1 + ;; +esac + # run-samples.sh runs this script as `bash scripts/deploy.sh` from the sample root, so relative # paths such as ../src must resolve against the script's own location, not the caller's directory. CURRENT_DIR="$(cd "$(dirname "$0")" && pwd)" cd "$CURRENT_DIR" || exit +# Assign the Cosmos DB Built-in Data Contributor role on the whole Cosmos DB account to a principal, unless the +# assignment already exists +# $1: the object (principal) id of the managed identity +# $2: the description of the managed identity, used in messages +ensure_cosmosdb_role_assignment() { + local principal_id=$1 + local principal_description=$2 + local current attempt + + echo "Checking if the $principal_description has the Cosmos DB Built-in Data Contributor role on the [$COSMOSDB_ACCOUNT_NAME] Cosmos DB account..." + current=$(az cosmosdb sql role assignment list \ + --account-name "$COSMOSDB_ACCOUNT_NAME" \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --query "length([?principalId=='$principal_id' && ends_with(roleDefinitionId, '/$COSMOSDB_DATA_CONTRIBUTOR_ROLE_ID')])" \ + --output tsv \ + --only-show-errors) + + if [[ $current -gt 0 ]]; then + echo "The $principal_description already has the Cosmos DB Built-in Data Contributor role on the [$COSMOSDB_ACCOUNT_NAME] Cosmos DB account" + return 0 + fi + + echo "Assigning the Cosmos DB Built-in Data Contributor role to the $principal_description on the [$COSMOSDB_ACCOUNT_NAME] Cosmos DB account..." + for attempt in $(seq 1 "$ROLE_ASSIGNMENT_RETRY_COUNT"); do + # The scope "/" is the whole account: the Azure CLI turns it into the account's resource id + if az cosmosdb sql role assignment create \ + --account-name "$COSMOSDB_ACCOUNT_NAME" \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --role-definition-id "$COSMOSDB_DATA_CONTRIBUTOR_ROLE_ID" \ + --principal-id "$principal_id" \ + --scope "/" \ + --only-show-errors 1>/dev/null; then + echo "Cosmos DB Built-in Data Contributor role successfully assigned to the $principal_description on the [$COSMOSDB_ACCOUNT_NAME] Cosmos DB account" + return 0 + fi + + if [ "$attempt" -lt "$ROLE_ASSIGNMENT_RETRY_COUNT" ]; then + echo "Attempt $attempt of $ROLE_ASSIGNMENT_RETRY_COUNT to assign the role failed; retrying in $ROLE_ASSIGNMENT_RETRY_SLEEP seconds..." + sleep "$ROLE_ASSIGNMENT_RETRY_SLEEP" + fi + done + + echo "Failed to assign the Cosmos DB Built-in Data Contributor role to the $principal_description on the [$COSMOSDB_ACCOUNT_NAME] Cosmos DB account" + exit 1 +} + # Validates if the resource group exists in the subscription, if not creates it echo "Checking if resource group [$RESOURCE_GROUP_NAME] exists..." az group show --name $RESOURCE_GROUP_NAME &>/dev/null @@ -69,7 +137,7 @@ if [[ $? != 0 ]]; then --location "$LOCATION" \ --query-access "Enabled" \ --retention-time 30 \ - --sku "PerNode" \ + --sku "PerGB2018" \ --tags environment=test iac=az-cli \ --only-show-errors 1>/dev/null @@ -227,21 +295,56 @@ else fi fi -# Retrieve the primary key of the Cosmos DB account -echo "Retrieving the primary key of the [$COSMOSDB_ACCOUNT_NAME] Cosmos DB account..." -AZURECOSMOSDB_PRIMARY_KEY=$(az cosmosdb keys list \ - --resource-group $RESOURCE_GROUP_NAME \ - --name $COSMOSDB_ACCOUNT_NAME \ - --query "primaryMasterKey" \ - --output tsv) +if [[ $MANAGED_IDENTITY_TYPE == "None" ]]; then + # Retrieve the primary key of the Cosmos DB account + echo "Retrieving the primary key of the [$COSMOSDB_ACCOUNT_NAME] Cosmos DB account..." + AZURECOSMOSDB_PRIMARY_KEY=$(az cosmosdb keys list \ + --resource-group $RESOURCE_GROUP_NAME \ + --name $COSMOSDB_ACCOUNT_NAME \ + --query "primaryMasterKey" \ + --output tsv) -if [[ -n $AZURECOSMOSDB_PRIMARY_KEY ]]; then - echo "Successfully retrieved the primary key of the [$COSMOSDB_ACCOUNT_NAME] Cosmos DB account" -else - echo "Failed to retrieve the primary key of the [$COSMOSDB_ACCOUNT_NAME] Cosmos DB account" - exit 1 + if [[ -n $AZURECOSMOSDB_PRIMARY_KEY ]]; then + echo "Successfully retrieved the primary key of the [$COSMOSDB_ACCOUNT_NAME] Cosmos DB account" + else + echo "Failed to retrieve the primary key of the [$COSMOSDB_ACCOUNT_NAME] Cosmos DB account" + exit 1 + fi + export AZURECOSMOSDB_PRIMARY_KEY +fi + +if [[ $MANAGED_IDENTITY_TYPE == "UserAssigned" ]]; then + # Create the user-assigned managed identity the web app authenticates as + if az identity show --name "$MANAGED_IDENTITY_NAME" --resource-group "$RESOURCE_GROUP_NAME" --only-show-errors &>/dev/null; then + echo "[$MANAGED_IDENTITY_NAME] managed identity already exists in the [$RESOURCE_GROUP_NAME] resource group" + elif az identity create \ + --name "$MANAGED_IDENTITY_NAME" \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --location "$LOCATION" \ + --only-show-errors 1>/dev/null; then + echo "[$MANAGED_IDENTITY_NAME] managed identity successfully created in the [$RESOURCE_GROUP_NAME] resource group" + else + echo "Failed to create [$MANAGED_IDENTITY_NAME] managed identity in the [$RESOURCE_GROUP_NAME] resource group" + exit 1 + fi + + # tr turns the three lines into one, and drops the carriage return the Azure CLI ends each line with on Windows + read -r IDENTITY_ID IDENTITY_CLIENT_ID IDENTITY_PRINCIPAL_ID < <(az identity show \ + --name "$MANAGED_IDENTITY_NAME" \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --query "[id, clientId, principalId]" \ + --output tsv \ + --only-show-errors | tr -d '\r' | tr '\n' ' ') + + if [[ -n $IDENTITY_PRINCIPAL_ID ]]; then + echo "[$MANAGED_IDENTITY_NAME] managed identity: client id [$IDENTITY_CLIENT_ID], principal id [$IDENTITY_PRINCIPAL_ID]" + else + echo "Failed to retrieve the ids of the [$MANAGED_IDENTITY_NAME] managed identity" + exit 1 + fi + + ensure_cosmosdb_role_assignment "$IDENTITY_PRINCIPAL_ID" "[$MANAGED_IDENTITY_NAME] managed identity" fi -export AZURECOSMOSDB_PRIMARY_KEY if az appservice plan show --name "$APP_SERVICE_PLAN_NAME" --resource-group "$RESOURCE_GROUP_NAME" --only-show-errors &>/dev/null; then echo "App service plan [$APP_SERVICE_PLAN_NAME] already exists." @@ -283,6 +386,44 @@ else fi fi +case "$MANAGED_IDENTITY_TYPE" in +SystemAssigned) + # A system-assigned identity exists only once the web app does, so it is granted its role here, well before the + # code is deployed: on Azure, a new role assignment takes a while to reach the data plane + echo "Assigning a system-assigned managed identity to the [$WEB_APP_NAME] web app..." + WEB_APP_PRINCIPAL_ID=$(az webapp identity assign \ + --name "$WEB_APP_NAME" \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --query principalId \ + --output tsv \ + --only-show-errors) + + if [[ -n $WEB_APP_PRINCIPAL_ID ]]; then + echo "System-assigned managed identity of the [$WEB_APP_NAME] web app: principal id [$WEB_APP_PRINCIPAL_ID]" + else + echo "Failed to assign a system-assigned managed identity to the [$WEB_APP_NAME] web app" + exit 1 + fi + + ensure_cosmosdb_role_assignment "$WEB_APP_PRINCIPAL_ID" "system-assigned managed identity of the [$WEB_APP_NAME] web app" + ;; +UserAssigned) + echo "Assigning the [$MANAGED_IDENTITY_NAME] managed identity to the [$WEB_APP_NAME] web app..." + az webapp identity assign \ + --name "$WEB_APP_NAME" \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --identities "$IDENTITY_ID" \ + --only-show-errors 1>/dev/null + + if [[ $? == 0 ]]; then + echo "[$MANAGED_IDENTITY_NAME] managed identity successfully assigned to the [$WEB_APP_NAME] web app" + else + echo "Failed to assign the [$MANAGED_IDENTITY_NAME] managed identity to the [$WEB_APP_NAME] web app" + exit 1 + fi + ;; +esac + # Check if the Application Insights component already exists echo "Checking if [$APPLICATION_INSIGHTS_NAME] Application Insights component exists in the [$RESOURCE_GROUP_NAME] resource group..." az monitor app-insights component show \ @@ -331,6 +472,14 @@ else exit 1 fi +# The credential the web app reaches the Cosmos DB account with: the account key, or nothing for a system-assigned +# identity, or the client id DefaultAzureCredential picks a user-assigned identity by +case "$MANAGED_IDENTITY_TYPE" in +None) COSMOSDB_CREDENTIAL_SETTINGS=(AZURECOSMOSDB_PRIMARY_KEY="$AZURECOSMOSDB_PRIMARY_KEY") ;; +SystemAssigned) COSMOSDB_CREDENTIAL_SETTINGS=() ;; +UserAssigned) COSMOSDB_CREDENTIAL_SETTINGS=(AZURE_CLIENT_ID="$IDENTITY_CLIENT_ID") ;; +esac + # Set the application settings of the web app. The package holds the source code, so the deployment builds it: # without SCM_DO_BUILD_DURING_DEPLOYMENT, az webapp deploy only copies the files and Azure serves its welcome page echo "Setting the application settings of the [$WEB_APP_NAME] web app..." @@ -342,7 +491,7 @@ az webapp config appsettings set \ AZURECOSMOSDB_ENDPOINT=$AZURECOSMOSDB_ENDPOINT \ AZURECOSMOSDB_DATABASENAME=$AZURECOSMOSDB_DATABASENAME \ AZURECOSMOSDB_CONTAINERNAME=$AZURECOSMOSDB_CONTAINERNAME \ - AZURECOSMOSDB_PRIMARY_KEY=$AZURECOSMOSDB_PRIMARY_KEY \ + "${COSMOSDB_CREDENTIAL_SETTINGS[@]}" \ APPLICATIONINSIGHTS_CONNECTION_STRING="$APPLICATION_INSIGHTS_CONNECTION_STRING" \ --only-show-errors 1>/dev/null @@ -353,7 +502,32 @@ else exit 1 fi -# Print the names of the application settings of the web app, never their values, which include the account key +# The credentials a previous run with another MANAGED_IDENTITY_TYPE left in the app settings, which the app would keep +# using: the account key of a run without a managed identity, and the client id of a user-assigned run, with which +# DefaultAzureCredential keeps picking the user-assigned identity over the system-assigned one +case "$MANAGED_IDENTITY_TYPE" in +None) STALE_CREDENTIAL_SETTINGS=() ;; +SystemAssigned) STALE_CREDENTIAL_SETTINGS=(AZURECOSMOSDB_PRIMARY_KEY AZURE_CLIENT_ID) ;; +UserAssigned) STALE_CREDENTIAL_SETTINGS=(AZURECOSMOSDB_PRIMARY_KEY) ;; +esac + +if [[ ${#STALE_CREDENTIAL_SETTINGS[@]} -gt 0 ]]; then + echo "Removing [${STALE_CREDENTIAL_SETTINGS[*]}] from the application settings of the [$WEB_APP_NAME] web app, if a previous run set them..." + az webapp config appsettings delete \ + --resource-group $RESOURCE_GROUP_NAME \ + --name $WEB_APP_NAME \ + --setting-names "${STALE_CREDENTIAL_SETTINGS[@]}" \ + --only-show-errors 1>/dev/null + + if [[ $? == 0 ]]; then + echo "No [${STALE_CREDENTIAL_SETTINGS[*]}] is left in the application settings of the [$WEB_APP_NAME] web app" + else + echo "Failed to remove [${STALE_CREDENTIAL_SETTINGS[*]}] from the application settings of the [$WEB_APP_NAME] web app" + exit 1 + fi +fi + +# Print the names of the application settings of the web app, never their values, which can include the account key echo "Names of the application settings of the [$WEB_APP_NAME] web app:" az webapp config appsettings list \ --resource-group $RESOURCE_GROUP_NAME \ diff --git a/samples/web-app-cosmosdb-nosql-api/python/scripts/validate.sh b/samples/web-app-cosmosdb-nosql-api/python/scripts/validate.sh index 0795053a..3a5ce82b 100755 --- a/samples/web-app-cosmosdb-nosql-api/python/scripts/validate.sh +++ b/samples/web-app-cosmosdb-nosql-api/python/scripts/validate.sh @@ -9,6 +9,124 @@ APP_SERVICE_PLAN_NAME="${WEB_APP_NAME}" COSMOSDB_ACCOUNT_NAME="${WEB_APP_NAME}" LOG_ANALYTICS_NAME="${PREFIX}-log-analytics-${SUFFIX}" APPLICATION_INSIGHTS_NAME="${PREFIX}-insights-${SUFFIX}" +# The authentication deploy.sh set up: the account key (None), or a managed identity (SystemAssigned, UserAssigned) +MANAGED_IDENTITY_TYPE="${MANAGED_IDENTITY_TYPE:-None}" +MANAGED_IDENTITY_NAME="${PREFIX}-webapp-nosql-identity-${SUFFIX}" +COSMOSDB_DATA_CONTRIBUTOR_ROLE_ID='00000000-0000-0000-0000-000000000002' +# The round trip through the web app waits for the app to start and, on Azure, for a new role assignment to reach the +# data plane +ROUND_TRIP_RETRY_COUNT="${ROUND_TRIP_RETRY_COUNT:-60}" +ROUND_TRIP_RETRY_SLEEP="${ROUND_TRIP_RETRY_SLEEP:-10}" + +# On Windows, Git Bash and MSYS2 shells pass a path such as /tmp/... unconverted to Windows programs +# (az, curl, jq, python, docker) when MSYS_NO_PATHCONV=1 is set, as the README asks. cygpath, which +# those shells provide, returns the C:/... form those programs can open; elsewhere the path is unchanged. +native_path() { + if command -v cygpath >/dev/null 2>&1; then + cygpath -m "$1" + else + echo "$1" + fi +} + +# Where curl discards a response body. Git Bash and MSYS2 shells hand a Windows curl /dev/null +# unchanged when MSYS_NO_PATHCONV=1 is set, as the README asks, and it cannot open that path, so it +# gets the NUL device instead; MSYS2's own curl, under /usr/bin, opens /dev/null as on Linux and macOS. +null_device() { + if command -v cygpath >/dev/null 2>&1 && [[ "$(command -v curl)" != /usr/bin/* ]]; then + echo NUL + else + echo /dev/null + fi +} + +# Add an activity through the web app, find it on the page that lists the activities, and delete it. The app reads and +# writes the Cosmos DB container as its managed identity, so the round trip proves the identity's role assignment. +check_round_trip() { + local host_name url cookies_file cookies discard activity page token status activity_id attempt + local token_args=() + + host_name=$(az webapp show \ + --name "$WEB_APP_NAME" \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --query defaultHostName \ + --output tsv \ + --only-show-errors | tr -d '\r') + + if [[ -z $host_name ]]; then + echo "Error: no default host name found for the [$WEB_APP_NAME] web app" + exit 1 + fi + + url="https://$host_name" + cookies_file=$(mktemp "${TMPDIR:-/tmp}/cosmosdb_nosql_cookies.XXXXXX") + cookies=$(native_path "$cookies_file") + discard=$(null_device) + activity="validation-$(date +%s)" + echo -e "\nAdding the [$activity] activity through the [$WEB_APP_NAME] web app at [$url]..." + + for attempt in $(seq 1 "$ROUND_TRIP_RETRY_COUNT"); do + page=$(curl --max-time 30 -s -c "$cookies" -b "$cookies" "$url/") + + if [[ $page == *'name="activity"'* ]]; then + # The .NET app's forms carry an antiforgery token, which a post must send back with the cookie it came with + token=$(printf '%s' "$page" | grep -o ']*__RequestVerificationToken[^>]*>' | head -n 1 | sed -n 's/.*value="\([^"]*\)".*/\1/p') + token_args=() + if [[ -n $token ]]; then + token_args=(--data-urlencode "__RequestVerificationToken=$token") + fi + + status=$(curl --max-time 30 -s -o "$discard" -w '%{http_code}' -c "$cookies" -b "$cookies" \ + --data-urlencode "activity=$activity" \ + --data-urlencode "row_id=" \ + "${token_args[@]}" \ + "$url/") + page=$(curl --max-time 30 -s -c "$cookies" -b "$cookies" "$url/") + activity_id=$(printf '%s' "$page" | grep -o "data-id=\"[^\"]*\" data-activity=\"$activity\"" | head -n 1 | sed 's/^data-id="\([^"]*\)".*/\1/') + + if [[ -n $activity_id ]]; then + echo "The [$WEB_APP_NAME] web app stored the [$activity] activity as item [$activity_id] and read it back" + break + fi + echo "Attempt $attempt of $ROUND_TRIP_RETRY_COUNT: the web app answered [$status] to the new activity, which its page doesn't list yet." + else + echo "Attempt $attempt of $ROUND_TRIP_RETRY_COUNT: the web app doesn't serve its page yet." + fi + + if [ "$attempt" -lt "$ROUND_TRIP_RETRY_COUNT" ]; then + sleep "$ROUND_TRIP_RETRY_SLEEP" + fi + done + + if [[ -z $activity_id ]]; then + rm -f "$cookies_file" + echo "Error: the [$WEB_APP_NAME] web app didn't store and list the [$activity] activity after $ROUND_TRIP_RETRY_COUNT attempts" + exit 1 + fi + + # Delete the activity, with the antiforgery token of the page that lists it + token=$(printf '%s' "$page" | grep -o ']*__RequestVerificationToken[^>]*>' | head -n 1 | sed -n 's/.*value="\([^"]*\)".*/\1/p') + token_args=() + if [[ -n $token ]]; then + token_args=(--data-urlencode "__RequestVerificationToken=$token") + fi + + status=$(curl --max-time 30 -s -o "$discard" -w '%{http_code}' -c "$cookies" -b "$cookies" -X POST \ + "${token_args[@]}" \ + "$url/delete/$activity_id") + page=$(curl --max-time 30 -s -c "$cookies" -b "$cookies" "$url/") + rm -f "$cookies_file" + + # The app confirms the deletion on the next page, which must also have read the activities again: after a failed + # read it renders the form with no activities, which would hide an activity it did not delete + if [[ $page == *'Activity deleted.'* && $page != *'Failed to load the activities.'* && + $page == *'name="activity"'* && $page != *"data-id=\"$activity_id\""* ]]; then + echo "The [$WEB_APP_NAME] web app deleted the [$activity] activity" + else + echo "Error: the [$WEB_APP_NAME] web app answered [$status] to the deletion of the [$activity] activity, without confirming it or with the activity still listed" + exit 1 + fi +} # Check resource group echo -e "[$RESOURCE_GROUP_NAME] resource group:\n" @@ -67,3 +185,47 @@ az resource list \ --resource-group "$RESOURCE_GROUP_NAME" \ --output table \ --only-show-errors + +if [[ $MANAGED_IDENTITY_TYPE != "None" ]]; then + # The principal the web app authenticates as + if [[ $MANAGED_IDENTITY_TYPE == "SystemAssigned" ]]; then + PRINCIPAL_ID=$(az webapp identity show \ + --name "$WEB_APP_NAME" \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --query principalId \ + --output tsv \ + --only-show-errors | tr -d '\r') + else + PRINCIPAL_ID=$(az identity show \ + --name "$MANAGED_IDENTITY_NAME" \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --query principalId \ + --output tsv \ + --only-show-errors | tr -d '\r') + fi + + # Check the SQL role assignments of the Cosmos DB account + echo -e "\n[$COSMOSDB_ACCOUNT_NAME] cosmos db sql role assignments:\n" + az cosmosdb sql role assignment list \ + --account-name "$COSMOSDB_ACCOUNT_NAME" \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --query '[].{PrincipalId:principalId,RoleDefinitionId:roleDefinitionId,Scope:scope}' \ + --output table \ + --only-show-errors + + ROLE_ASSIGNMENT_COUNT=$(az cosmosdb sql role assignment list \ + --account-name "$COSMOSDB_ACCOUNT_NAME" \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --query "length([?principalId=='$PRINCIPAL_ID' && ends_with(roleDefinitionId, '/$COSMOSDB_DATA_CONTRIBUTOR_ROLE_ID')])" \ + --output tsv \ + --only-show-errors | tr -d '\r') + + if [[ -n $PRINCIPAL_ID && $ROLE_ASSIGNMENT_COUNT -gt 0 ]]; then + echo -e "\nThe $MANAGED_IDENTITY_TYPE managed identity [$PRINCIPAL_ID] of the web app has the Cosmos DB Built-in Data Contributor role" + else + echo -e "\nError: the $MANAGED_IDENTITY_TYPE managed identity [$PRINCIPAL_ID] of the web app has no Cosmos DB Built-in Data Contributor role" + exit 1 + fi + + check_round_trip +fi diff --git a/samples/web-app-cosmosdb-nosql-api/python/src/cosmosdb_client.py b/samples/web-app-cosmosdb-nosql-api/python/src/cosmosdb_client.py index 6de59e1d..06df8b1e 100644 --- a/samples/web-app-cosmosdb-nosql-api/python/src/cosmosdb_client.py +++ b/samples/web-app-cosmosdb-nosql-api/python/src/cosmosdb_client.py @@ -1,13 +1,21 @@ import os import logging from azure.cosmos import CosmosClient, PartitionKey, exceptions +from azure.identity import DefaultAzureCredential # A child of the application's logger, whose records the Microsoft OpenTelemetry Distro sends to Application Insights logger = logging.getLogger(f"webapp.{__name__}") class CosmosDbClient: def __init__(self, endpoint, key, database_name, container_name): - self.client = CosmosClient(endpoint, credential=key) + # With the account key, the client signs its requests with it. Without one, the client authenticates with + # Microsoft Entra ID: DefaultAzureCredential gets a token for the web app's managed identity (the one AZURE_CLIENT_ID + # names, for a user-assigned identity), and the identity's Cosmos DB data-plane role decides what it may do + if key: + self.client = CosmosClient(endpoint, credential=key) + else: + logger.info("Authenticating to Azure Cosmos DB with Microsoft Entra ID") + self.client = CosmosClient(endpoint, credential=DefaultAzureCredential()) self.database_name = database_name self.container_name = container_name @@ -15,6 +23,8 @@ def __init__(self, endpoint, key, database_name, container_name): self.container = None def ensure_initialized(self): + # Each call reads the database and the container first, and creates them only when they don't exist. A Microsoft + # Entra identity can't create them (Azure refuses it whatever its roles), so the deploy script creates both if self.database is None: self.database = self.client.create_database_if_not_exists(self.database_name) if self.container is None: diff --git a/samples/web-app-cosmosdb-nosql-api/python/src/requirements.txt b/samples/web-app-cosmosdb-nosql-api/python/src/requirements.txt index ed9452de..d5cc90e0 100644 --- a/samples/web-app-cosmosdb-nosql-api/python/src/requirements.txt +++ b/samples/web-app-cosmosdb-nosql-api/python/src/requirements.txt @@ -1,6 +1,7 @@ Flask==3.1.3 azure-mgmt-cosmosdb==9.9.0 azure-cosmos==4.15.0 +azure-identity==1.25.3 gunicorn==26.0.0 python-dotenv==1.2.2 setuptools==84.1.0 diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/README.md b/samples/web-app-cosmosdb-nosql-api/python/terraform/README.md new file mode 100644 index 00000000..1ab5219f --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/README.md @@ -0,0 +1,153 @@ +# Terraform Deployment + +This directory contains the Terraform modules and a deployment script for provisioning the sample in LocalStack for Azure or in Azure. Refer to the [Azure Web App with Azure CosmosDB for NoSQL API](../README.md) guide for details about the sample application. + +## Prerequisites + +Before deploying this solution, ensure you have the following tools installed: + +- [LocalStack for Azure](https://docs.localstack.cloud/azure/): Local Azure cloud emulator for development and testing +- [Visual Studio Code](https://code.visualstudio.com/): Code editor installed on one of the [supported platforms](https://code.visualstudio.com/docs/supporting/requirements#_platforms) +- [Terraform](https://developer.hashicorp.com/terraform/downloads): Infrastructure as code tool, version 1.0 or above +- [Docker](https://docs.docker.com/get-docker/): Container runtime required for LocalStack +- [Azure CLI](https://learn.microsoft.com/en-us/cli/azure/install-azure-cli): Azure command-line interface +- [lstk CLI](https://docs.localstack.cloud/aws/developer-tools/running-localstack/lstk/): LocalStack command-line interface (proxies the Azure CLI via `lstk az`) +- [Python](https://www.python.org/downloads/): Python runtime (version 3.12 or above) + +### Installing lstk CLI + +Deploying to LocalStack requires the `lstk` CLI, which routes Azure CLI commands to the emulator (run `lstk az start-interception` before deploying). Install it using Homebrew: + +```bash +brew install localstack/tap/lstk +``` + +or npm: + +```bash +npm install -g @localstack/lstk +``` + +Alternatively, download a pre-built binary from the [lstk releases page](https://github.com/localstack/lstk/releases). For more information, see the [lstk CLI documentation](https://docs.localstack.cloud/aws/developer-tools/running-localstack/lstk/) and the [lstk GitHub repository](https://github.com/localstack/lstk). + +## Architecture Overview + +[main.tf](main.tf) creates the following resources, most of them through a module in the [modules](modules) folder: + +1. [Resource group](https://learn.microsoft.com/en-us/azure/azure-resource-manager/management/manage-resource-groups-cli): holds all the resources of the sample. +2. [Azure Cosmos DB for NoSQL account](https://learn.microsoft.com/en-us/azure/cosmos-db/overview) ([cosmosdb_nosql](modules/cosmosdb_nosql)): the account, the `vacationplanner` database, and the `activities` container, partitioned by `/username`, with 400 request units per second. +3. [Managed identity](https://learn.microsoft.com/en-us/entra/identity/managed-identities-azure-resources/overview) ([managed_identity](modules/managed_identity)): with `MANAGED_IDENTITY_TYPE=UserAssigned`, the default, a user-assigned identity assigned to the web app. With `MANAGED_IDENTITY_TYPE=SystemAssigned`, the web app's own identity instead, which the web app module enables. +4. [Cosmos DB SQL role assignment](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/cosmosdb_sql_role_assignment) (the `azurerm_cosmosdb_sql_role_assignment` resource in [main.tf](main.tf)): grants the identity the [Cosmos DB Built-in Data Contributor](https://learn.microsoft.com/en-us/azure/cosmos-db/reference-data-plane-security#built-in-roles) role on the whole account. It's a role of the Cosmos DB account itself, not an Azure RBAC role. +5. [Azure App Service plan](https://learn.microsoft.com/en-us/azure/app-service/overview-hosting-plans) ([app_service_plan](modules/app_service_plan)): a B1 Linux plan that hosts the web app. +6. [Azure Web App](https://learn.microsoft.com/en-us/azure/app-service/overview) ([web_app](modules/web_app)): hosts the Python Flask *Vacation Planner* application. Its app settings hold the endpoint of the account and the names of the database and the container, and, for a user-assigned identity, its client id in `AZURE_CLIENT_ID`. They hold no key: the app passes `DefaultAzureCredential` to `CosmosClient`, which gets a token for the web app's managed identity. +7. [Log Analytics workspace](https://learn.microsoft.com/en-us/azure/azure-monitor/logs/log-analytics-workspace-overview) ([log_analytics](modules/log_analytics)): stores the telemetry of Application Insights, the logs and metrics that the diagnostic settings send to it, and the audit records of the queries run on it. +8. [Application Insights](https://learn.microsoft.com/en-us/azure/azure-monitor/app/app-insights-overview) ([application_insights](modules/application_insights)): a workspace-based resource that collects the requests, the calls to Azure Cosmos DB, the log records, the exceptions, the custom events and the custom metric of the web app. +9. [Diagnostic settings](https://learn.microsoft.com/en-us/azure/azure-monitor/data-collection/diagnostic-settings): send the logs and metrics of the web app, the metrics of the App Service plan, the `DataPlaneRequests` and `ControlPlaneRequests` logs and the `Requests` metrics of the Cosmos DB account (in the resource-specific tables `CDBDataPlaneRequests` and `CDBControlPlaneRequests`), and the query audit of the workspace to the Log Analytics workspace. + +The resources get the same names as with the [Azure CLI scripts](../scripts/README.md), so the scripts in the [scripts](../scripts) folder validate this deployment and query its telemetry, logs and metrics too. + +## Provisioning Scripts + +You can use the [deploy.sh](deploy.sh) script to deploy all Azure resources and the sample application in a single step. It runs `terraform init`, `terraform plan` and `terraform apply`, with the managed identity type in `MANAGED_IDENTITY_TYPE`: `UserAssigned` (the default) or `SystemAssigned`. It then packages the web application code into a zip file and deploys it to the web app, which builds it. + +## Configuration + +`providers.tf` hardcodes no endpoint and no subscription. `deploy.sh` exports the variables the [Azure Provider for Terraform](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs) reads natively, so the same files run unmodified against the LocalStack emulator and against Azure: + +| Variable | Exported when | Value | +| -------------------------------------- | ------------------------------------- | --------------------------------------------------------- | +| `ARM_SUBSCRIPTION_ID`, `ARM_TENANT_ID` | always | `az account show` | +| `ARM_METADATA_HOSTNAME` | the active `az cloud` is `LocalStack` | host of `az cloud show --query endpoints.resourceManager` | + +The provider discovers every endpoint of the emulator from `ARM_METADATA_HOSTNAME`, and authenticates with the Azure CLI session on both targets. Against Azure, `deploy.sh` unsets `ARM_METADATA_HOSTNAME`, so the provider uses the endpoints of the public cloud. Running `terraform` directly, rather than through `deploy.sh`, needs these variables exported. + +## Deployment + +You can set up the Azure emulator by utilizing LocalStack for Azure Docker image. Before starting, ensure you have a valid `LOCALSTACK_AUTH_TOKEN` to access the Azure emulator. Refer to the [Auth Token guide](https://docs.localstack.cloud/getting-started/auth-token/) to obtain your Auth Token and specify it in the `LOCALSTACK_AUTH_TOKEN` environment variable. The Azure Docker image is available on the [LocalStack Docker Hub](https://hub.docker.com/r/localstack/localstack-azure). To pull the Azure Docker image, execute the following command: + +```bash +docker pull localstack/localstack-azure +``` + +Start the LocalStack Azure emulator with the lstk CLI: + +```bash +# Set the authentication token +export LOCALSTACK_AUTH_TOKEN= + +# Start the LocalStack Azure emulator +lstk start --type azure + +# Route all Azure CLI calls to the LocalStack Azure emulator +lstk az start-interception +``` + +Navigate to the `terraform` folder: + +```bash +cd samples/web-app-cosmosdb-nosql-api/python/terraform +``` + +Make the script executable: + +```bash +chmod +x deploy.sh +``` + +Run the deployment script, which gives the web app a user-assigned managed identity: + +```bash +./deploy.sh +``` + +To use the web app's system-assigned managed identity instead, set `MANAGED_IDENTITY_TYPE`: + +```bash +MANAGED_IDENTITY_TYPE=SystemAssigned ./deploy.sh +``` + +The same script deploys the sample to Azure: run `lstk az stop-interception` to route the Azure CLI back to Azure, sign in with `az login`, and run it again. See [Microsoft Entra ID authentication](../README.md#microsoft-entra-id-authentication). + +## Validation + +After deployment, run the validation script of the [scripts](../scripts) folder with the same `MANAGED_IDENTITY_TYPE`: + +```bash +MANAGED_IDENTITY_TYPE=UserAssigned ../scripts/validate.sh +``` + +It shows the resource group, the App Service plan, the web app, the Cosmos DB account, the Log Analytics workspace, the Application Insights component and the resources of the group. It then checks that the managed identity has the Cosmos DB Built-in Data Contributor role on the account, adds an activity through the web app, finds it on the page, and deletes it. On Azure, a new role assignment can take a few minutes to take effect, and the script retries meanwhile. + +## Telemetry, logs and metrics + +Read the telemetry the web app sent to Application Insights and the logs and metrics the diagnostic settings sent to the workspace: + +```bash +../scripts/query-telemetry.sh +../scripts/query-logs-and-metrics.sh +``` + +See [Application Insights](../README.md#application-insights) and [Logs and metrics](../README.md#logs-and-metrics) for what they read. + +## Cleanup + +To destroy all created resources: + +```bash +# Delete resource group and all contained resources +az group delete --name local-rg --yes --no-wait + +# Verify deletion +az group list --output table +``` + +This will remove all Azure resources created by the Terraform configuration. + +## Related Documentation + +- [Terraform Azure Provider Documentation](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs) +- [azurerm_cosmosdb_sql_role_assignment](https://registry.terraform.io/providers/hashicorp/azurerm/latest/docs/resources/cosmosdb_sql_role_assignment) +- [Connect to Azure Cosmos DB for NoSQL with role-based access control and Microsoft Entra ID](https://learn.microsoft.com/en-us/azure/cosmos-db/how-to-connect-role-based-access-control) +- [LocalStack for Azure Documentation](https://docs.localstack.cloud/azure/) +- [lstk CLI](https://docs.localstack.cloud/aws/developer-tools/running-localstack/lstk/) +- [lstk GitHub repository](https://github.com/localstack/lstk) diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/deploy.sh b/samples/web-app-cosmosdb-nosql-api/python/terraform/deploy.sh new file mode 100755 index 00000000..01523e24 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/deploy.sh @@ -0,0 +1,141 @@ +#!/bin/bash + +# Variables +PREFIX="${PREFIX:-local}" +SUFFIX="${SUFFIX:-test}" +LOCATION='westeurope' +CURRENT_DIR="$(cd "$(dirname "$0")" && pwd)" + +# The web app reaches the Cosmos DB account with Microsoft Entra ID, as a managed identity granted the Cosmos DB +# Built-in Data Contributor role on the account: no key appears anywhere. UserAssigned (the default) creates a +# user-assigned identity and assigns it to the web app; SystemAssigned enables the web app's own identity. +MANAGED_IDENTITY_TYPE="${MANAGED_IDENTITY_TYPE:-UserAssigned}" + +case "$MANAGED_IDENTITY_TYPE" in +SystemAssigned | UserAssigned) ;; +*) + echo "MANAGED_IDENTITY_TYPE must be SystemAssigned or UserAssigned, not [$MANAGED_IDENTITY_TYPE]." + exit 1 + ;; +esac + +# Change the current directory to the script's directory +cd "$CURRENT_DIR" || exit + +# Dual-target provider configuration. providers.tf hardcodes nothing: the azurerm provider reads its endpoints and the +# target subscription from the ARM_* environment variables exported here. +# - On both targets: the subscription and tenant of the active az account. +# - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration +# that `lstk az start-interception` created, so nothing is hardcoded here either. +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') +export ARM_SUBSCRIPTION_ID ARM_TENANT_ID + +if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') + METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" + export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" + echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets the emulator at [$RESOURCE_MANAGER_ENDPOINT]" +else + # Cleared rather than merely not set: a value inherited from an earlier emulator deployment in the same shell would + # keep the provider doing metadata discovery against the emulator while the CLI is on Azure. + unset ARM_METADATA_HOSTNAME + echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets Azure subscription [$ARM_SUBSCRIPTION_ID]" +fi + +echo "Initializing Terraform..." +terraform init -upgrade + +# Run terraform plan and check for errors +echo "Planning Terraform deployment with a [$MANAGED_IDENTITY_TYPE] managed identity..." +terraform plan -out=tfplan \ + -var "prefix=$PREFIX" \ + -var "suffix=$SUFFIX" \ + -var "location=$LOCATION" \ + -var "managed_identity_type=$MANAGED_IDENTITY_TYPE" + +if [[ $? != 0 ]]; then + echo "Terraform plan failed. Exiting." + exit 1 +fi + +# Apply the Terraform configuration +echo "Applying Terraform configuration..." +terraform apply -auto-approve tfplan + +if [[ $? != 0 ]]; then + echo "Terraform apply failed. Exiting." + exit 1 +fi + +# Get the output values +RESOURCE_GROUP_NAME=$(terraform output -raw resource_group_name) +WEB_APP_NAME=$(terraform output -raw web_app_name) +COSMOSDB_ACCOUNT_NAME=$(terraform output -raw cosmosdb_account_name) +PRINCIPAL_ID=$(terraform output -raw principal_id) + +# Check if output values are empty +if [[ -z "$WEB_APP_NAME" || -z "$COSMOSDB_ACCOUNT_NAME" ]]; then + echo "Web App Name or Cosmos DB Account Name is empty. Exiting." + exit 1 +fi + +echo "Deployment details:" +echo "- resourceGroupName: $RESOURCE_GROUP_NAME" +echo "- webAppName: $WEB_APP_NAME" +echo "- cosmosDbAccountName: $COSMOSDB_ACCOUNT_NAME" +echo "- principalId of the [$MANAGED_IDENTITY_TYPE] managed identity: $PRINCIPAL_ID" + +# The zip package is named after the web app, so deployments with different prefixes don't overwrite each other's +ZIPFILE="${WEB_APP_NAME}.zip" + +# Change current directory to source folder +cd "../src" || exit + +# Remove any existing zip package of the web app +if [ -f "$ZIPFILE" ]; then + rm "$ZIPFILE" +fi + +# Create the zip package of the web app +echo "Creating zip package of the web app..." +zip -r "$ZIPFILE" app.py cosmosdb_client.py gunicorn.conf.py static templates requirements.txt + +# Deploy the web app +echo "Deploying web app [$WEB_APP_NAME] with zip file [$ZIPFILE]..." +# On Azure the deployment service can answer 504 Gateway Timeout while it warms up, or DeploymentInProgress while +# the build of the previous deployment still runs: the upload is tried again. The startup of the site isn't +# tracked: the tracking counted a failed start of the container that ran before the code was deployed, and +# reported a running site as failed after ten minutes; what calls the web app afterwards waits for it instead. +WEBAPP_DEPLOY_RETRY_COUNT="${WEBAPP_DEPLOY_RETRY_COUNT:-10}" +WEBAPP_DEPLOY_RETRY_SLEEP="${WEBAPP_DEPLOY_RETRY_SLEEP:-30}" +WEBAPP_DEPLOYED=0 +for ATTEMPT in $(seq 1 "$WEBAPP_DEPLOY_RETRY_COUNT"); do + if az webapp deploy \ + --resource-group "$RESOURCE_GROUP_NAME" \ + --name "$WEB_APP_NAME" \ + --src-path "$ZIPFILE" \ + --type zip \ + --async true \ + --track-status false 1>/dev/null; then + WEBAPP_DEPLOYED=1 + break + fi + if [ "$ATTEMPT" -lt "$WEBAPP_DEPLOY_RETRY_COUNT" ]; then + echo "Attempt $ATTEMPT of $WEBAPP_DEPLOY_RETRY_COUNT to deploy web app [$WEB_APP_NAME] failed. Waiting [$WEBAPP_DEPLOY_RETRY_SLEEP] seconds before retry..." + sleep "$WEBAPP_DEPLOY_RETRY_SLEEP" + fi +done + +if [ $WEBAPP_DEPLOYED -eq 1 ]; then + echo "Web app [$WEB_APP_NAME] deployed successfully." +else + echo "Failed to deploy web app [$WEB_APP_NAME]." + exit 1 +fi + +# Remove the zip package of the web app +if [ -f "$ZIPFILE" ]; then + rm "$ZIPFILE" +fi diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/main.tf b/samples/web-app-cosmosdb-nosql-api/python/terraform/main.tf new file mode 100644 index 00000000..43791f24 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/main.tf @@ -0,0 +1,129 @@ +# Local Variables +locals { + # The names the Azure CLI scripts of this sample give the same resources, so the scripts in ../scripts that validate + # the deployment and query its telemetry, logs and metrics work on this deployment too + resource_group_name = "${var.prefix}-rg" + web_app_name = "${var.prefix}-webapp-nosql-${var.suffix}" + app_service_plan_name = local.web_app_name + cosmosdb_account_name = local.web_app_name + managed_identity_name = "${var.prefix}-webapp-nosql-identity-${var.suffix}" + log_analytics_name = "${var.prefix}-log-analytics-${var.suffix}" + application_insights_name = "${var.prefix}-insights-${var.suffix}" + + # The id of the Cosmos DB Built-in Data Contributor role, a data-plane role every Cosmos DB for NoSQL account has + # under this id. It is a role of the account (a SQL role definition), not an Azure RBAC role. + cosmosdb_data_contributor_role_id = "00000000-0000-0000-0000-000000000002" +} + +# Create a resource group +resource "azurerm_resource_group" "example" { + name = local.resource_group_name + location = var.location + tags = var.tags +} + +# Create the Log Analytics workspace that receives the logs and metrics of the resources and the telemetry of the web app +module "log_analytics" { + source = "./modules/log_analytics" + name = local.log_analytics_name + resource_group_name = azurerm_resource_group.example.name + location = azurerm_resource_group.example.location + tags = var.tags +} + +# Create the workspace-based Application Insights component that collects the web app's requests, dependencies, logs, exceptions, custom events and custom metrics +module "application_insights" { + source = "./modules/application_insights" + name = local.application_insights_name + resource_group_name = azurerm_resource_group.example.name + location = azurerm_resource_group.example.location + workspace_id = module.log_analytics.id + tags = var.tags +} + +# Create the Cosmos DB for NoSQL account, its database and container, and the diagnostic setting of the account +module "cosmosdb" { + source = "./modules/cosmosdb_nosql" + name = local.cosmosdb_account_name + resource_group_name = azurerm_resource_group.example.name + location = azurerm_resource_group.example.location + database_name = var.cosmosdb_database_name + container_name = var.cosmosdb_container_name + partition_key_path = var.cosmosdb_partition_key_path + container_throughput = var.cosmosdb_container_throughput + log_analytics_workspace_id = module.log_analytics.id + diagnostic_setting_name = var.diagnostic_settings_name + tags = var.tags +} + +# Conditionally create a user-assigned identity for the web app +module "managed_identity" { + source = "./modules/managed_identity" + count = var.managed_identity_type == "UserAssigned" ? 1 : 0 + name = local.managed_identity_name + resource_group_name = azurerm_resource_group.example.name + location = azurerm_resource_group.example.location + tags = var.tags +} + +# Create the App Service plan and its diagnostic setting +module "app_service_plan" { + source = "./modules/app_service_plan" + name = local.app_service_plan_name + resource_group_name = azurerm_resource_group.example.name + location = azurerm_resource_group.example.location + sku_name = var.sku_name + os_type = var.os_type + zone_balancing_enabled = var.zone_balancing_enabled + log_analytics_workspace_id = module.log_analytics.id + diagnostic_setting_name = var.diagnostic_settings_name + metric_categories = var.metric_categories + tags = var.tags +} + +# Create the web app and its diagnostic setting. The package holds the source code, so the deployment builds it. The +# web app reaches the Cosmos DB account with DefaultAzureCredential as its managed identity, so no key is set anywhere: +# for a user-assigned identity, AZURE_CLIENT_ID tells DefaultAzureCredential which identity to use. +module "web_app" { + source = "./modules/web_app" + name = local.web_app_name + resource_group_name = azurerm_resource_group.example.name + location = azurerm_resource_group.example.location + service_plan_id = module.app_service_plan.id + https_only = var.https_only + public_network_access_enabled = var.webapp_public_network_access_enabled + always_on = var.always_on + http2_enabled = var.http2_enabled + minimum_tls_version = var.minimum_tls_version + python_version = var.python_version + identity_type = var.managed_identity_type + identity_ids = var.managed_identity_type == "UserAssigned" ? [module.managed_identity[0].id] : [] + log_analytics_workspace_id = module.log_analytics.id + diagnostic_setting_name = var.diagnostic_settings_name + log_categories = var.log_categories + metric_categories = var.metric_categories + tags = var.tags + + app_settings = merge( + { + SCM_DO_BUILD_DURING_DEPLOYMENT = "true" + ENABLE_ORYX_BUILD = "true" + AZURECOSMOSDB_ENDPOINT = module.cosmosdb.endpoint + AZURECOSMOSDB_DATABASENAME = module.cosmosdb.database_name + AZURECOSMOSDB_CONTAINERNAME = module.cosmosdb.container_name + APPLICATIONINSIGHTS_CONNECTION_STRING = module.application_insights.connection_string + }, + var.managed_identity_type == "UserAssigned" ? { AZURE_CLIENT_ID = module.managed_identity[0].client_id } : {} + ) +} + +# Assign the Cosmos DB Built-in Data Contributor role on the whole account to the identity of the web app. A Cosmos DB +# data role is assigned with a SQL role assignment of the account, not with an Azure RBAC role assignment. The +# system-assigned identity exists only once the web app does, so the role is assigned after the web app is created. +resource "azurerm_cosmosdb_sql_role_assignment" "data_contributor" { + resource_group_name = azurerm_resource_group.example.name + account_name = module.cosmosdb.name + role_definition_id = "${module.cosmosdb.id}/sqlRoleDefinitions/${local.cosmosdb_data_contributor_role_id}" + principal_id = var.managed_identity_type == "UserAssigned" ? module.managed_identity[0].principal_id : module.web_app.principal_id + scope = module.cosmosdb.id +} diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/app_service_plan/main.tf b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/app_service_plan/main.tf new file mode 100644 index 00000000..44b9821a --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/app_service_plan/main.tf @@ -0,0 +1,35 @@ +resource "azurerm_service_plan" "example" { + name = var.name + resource_group_name = var.resource_group_name + location = var.location + sku_name = var.sku_name + os_type = var.os_type + zone_balancing_enabled = var.zone_balancing_enabled + tags = var.tags + + lifecycle { + ignore_changes = [ + tags + ] + } +} + +resource "azurerm_monitor_diagnostic_setting" "example" { + name = var.diagnostic_setting_name + target_resource_id = azurerm_service_plan.example.id + log_analytics_workspace_id = var.log_analytics_workspace_id + + dynamic "enabled_log" { + for_each = toset(var.log_categories) + content { + category = enabled_log.value + } + } + + dynamic "enabled_metric" { + for_each = toset(var.metric_categories) + content { + category = enabled_metric.value + } + } +} diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/app_service_plan/outputs.tf b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/app_service_plan/outputs.tf new file mode 100644 index 00000000..f1455ea2 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/app_service_plan/outputs.tf @@ -0,0 +1,19 @@ +output "id" { + value = azurerm_service_plan.example.id + description = "Specifies the resource id of the App Service Plan" +} + +output "name" { + value = azurerm_service_plan.example.name + description = "Specifies the name of the App Service Plan" +} + +output "location" { + value = azurerm_service_plan.example.location + description = "Specifies the location of the App Service Plan" +} + +output "resource_group_name" { + value = azurerm_service_plan.example.resource_group_name + description = "Specifies the resource group name of the App Service Plan" +} diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/app_service_plan/variables.tf b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/app_service_plan/variables.tf new file mode 100644 index 00000000..31f1030a --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/app_service_plan/variables.tf @@ -0,0 +1,60 @@ +variable "resource_group_name" { + description = "(Required) Specifies the name of the resource group." + type = string +} + +variable "location" { + description = "(Required) Specifies the location for the App Service Plan." + type = string +} + +variable "name" { + description = "(Required) Specifies the name of the App Service Plan." + type = string +} + +variable "sku_name" { + description = "(Required) Specifies the SKU name for the App Service Plan." + type = string +} + +variable "os_type" { + description = "(Required) Specifies the O/S type for the App Services to be hosted in this plan." + type = string + default = "Linux" +} + +variable "zone_balancing_enabled" { + description = "(Optional) Should the Service Plan balance across Availability Zones in the region." + type = bool + default = false +} + +variable "tags" { + description = "(Optional) Specifies the tags to be applied to the resources." + type = map(any) + default = {} +} + +variable "log_analytics_workspace_id" { + description = "Specifies the resource id of the Azure Log Analytics workspace." + type = string +} + +variable "diagnostic_setting_name" { + description = "(Optional) Specifies the name of the diagnostic setting. Defaults to DiagnosticsSettings." + type = string + default = "DiagnosticsSettings" +} + +variable "log_categories" { + description = "(Optional) Specifies the log categories the diagnostic setting enables." + type = list(string) + default = [] +} + +variable "metric_categories" { + description = "(Optional) Specifies the metric categories the diagnostic setting enables." + type = list(string) + default = ["AllMetrics"] +} diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/application_insights/main.tf b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/application_insights/main.tf new file mode 100644 index 00000000..4211e713 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/application_insights/main.tf @@ -0,0 +1,20 @@ +# The component has no diagnostic setting: its telemetry is already stored in the workspace it's based on, and a +# diagnostic setting of a workspace-based component can't send to that workspace. +resource "azurerm_application_insights" "example" { + name = var.name + location = var.location + resource_group_name = var.resource_group_name + tags = var.tags + application_type = var.application_type + workspace_id = var.workspace_id + ip_masking_enabled = var.ip_masking_enabled + local_authentication_enabled = var.local_authentication_enabled + internet_ingestion_enabled = var.internet_ingestion_enabled + internet_query_enabled = var.internet_query_enabled + + lifecycle { + ignore_changes = [ + tags + ] + } +} diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/application_insights/outputs.tf b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/application_insights/outputs.tf new file mode 100644 index 00000000..a113e5cf --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/application_insights/outputs.tf @@ -0,0 +1,24 @@ +output "name" { + value = azurerm_application_insights.example.name + description = "Specifies the name of the resource." +} + +output "id" { + value = azurerm_application_insights.example.id + description = "Specifies the resource id of the resource." +} + +output "instrumentation_key" { + value = azurerm_application_insights.example.instrumentation_key + description = "Specifies the instrumentation key of the Application Insights." +} + +output "app_id" { + value = azurerm_application_insights.example.app_id + description = "Specifies the resource id of the resource." +} + +output "connection_string" { + value = azurerm_application_insights.example.connection_string + description = "Specifies the connection string of the Application Insights." +} diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/application_insights/variables.tf b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/application_insights/variables.tf new file mode 100644 index 00000000..80e646d2 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/application_insights/variables.tf @@ -0,0 +1,55 @@ +variable "name" { + description = "(Required) Specifies the name of the resource. Changing this forces a new resource to be created." + type = string +} + +variable "resource_group_name" { + description = "(Required) The name of the resource group in which to create the resource. Changing this forces a new resource to be created." + type = string +} + +variable "location" { + description = "(Required) Specifies the supported Azure location where the resource exists. Changing this forces a new resource to be created." + type = string +} + +variable "application_type" { + description = "(Required) Specifies the type of Application Insights to create. Valid values are ios for iOS, java for Java web, MobileCenter for App Center, Node.JS for Node.js, other for General, phone for Windows Phone, store for Windows Store and web for ASP.NET. Please note these values are case sensitive; unmatched values are treated as ASP.NET by Azure. Changing this forces a new resource to be created." + type = string + default = "web" +} + +variable "workspace_id" { + description = "(Optional) Specifies the id of a log analytics workspace resource. Changing this forces a new resource to be created." + type = string +} + +variable "tags" { + description = "(Optional) Specifies the tags to be applied to the resources" + type = map(any) + default = {} +} + +variable "ip_masking_enabled" { + description = "(Optional) Specifies whether IP masking is enabled." + type = bool + default = true +} + +variable "local_authentication_enabled" { + description = "(Optional) Specifies whether local authentication is enabled." + type = bool + default = true +} + +variable "internet_ingestion_enabled" { + description = "(Optional) Specifies whether the public network access for ingestion is enabled." + type = bool + default = true +} + +variable "internet_query_enabled" { + description = "(Optional) Specifies whether the public network access for query is enabled." + type = bool + default = true +} diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/cosmosdb_nosql/main.tf b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/cosmosdb_nosql/main.tf new file mode 100644 index 00000000..8e8857cd --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/cosmosdb_nosql/main.tf @@ -0,0 +1,67 @@ +resource "azurerm_cosmosdb_account" "example" { + name = var.name + resource_group_name = var.resource_group_name + location = var.location + offer_type = "Standard" + kind = "GlobalDocumentDB" + automatic_failover_enabled = false + tags = var.tags + + consistency_policy { + consistency_level = var.consistency_level + } + + geo_location { + location = var.location + failover_priority = 0 + } + + lifecycle { + ignore_changes = [ + tags + ] + } +} + +# Created after the diagnostic setting, so the ControlPlaneRequests log records the creation of the database and of the +# container +resource "azurerm_cosmosdb_sql_database" "example" { + name = var.database_name + resource_group_name = var.resource_group_name + account_name = azurerm_cosmosdb_account.example.name + + depends_on = [ + azurerm_monitor_diagnostic_setting.example + ] +} + +resource "azurerm_cosmosdb_sql_container" "example" { + name = var.container_name + resource_group_name = var.resource_group_name + account_name = azurerm_cosmosdb_account.example.name + database_name = azurerm_cosmosdb_sql_database.example.name + partition_key_paths = [var.partition_key_path] + throughput = var.container_throughput +} + +# The logs go to resource-specific tables (CDBDataPlaneRequests, CDBControlPlaneRequests) rather than AzureDiagnostics +resource "azurerm_monitor_diagnostic_setting" "example" { + name = var.diagnostic_setting_name + target_resource_id = azurerm_cosmosdb_account.example.id + log_analytics_workspace_id = var.log_analytics_workspace_id + log_analytics_destination_type = "Dedicated" + + dynamic "enabled_log" { + for_each = toset(var.log_categories) + content { + category = enabled_log.value + } + } + + dynamic "enabled_metric" { + for_each = toset(var.metric_categories) + content { + category = enabled_metric.value + } + } +} diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/cosmosdb_nosql/outputs.tf b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/cosmosdb_nosql/outputs.tf new file mode 100644 index 00000000..89016c17 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/cosmosdb_nosql/outputs.tf @@ -0,0 +1,24 @@ +output "id" { + description = "Specifies the resource id of the Azure Cosmos DB account." + value = azurerm_cosmosdb_account.example.id +} + +output "name" { + description = "Specifies the name of the Azure Cosmos DB account." + value = azurerm_cosmosdb_account.example.name +} + +output "endpoint" { + description = "Specifies the endpoint of the Azure Cosmos DB account." + value = azurerm_cosmosdb_account.example.endpoint +} + +output "database_name" { + description = "Specifies the name of the Cosmos DB for NoSQL database." + value = azurerm_cosmosdb_sql_database.example.name +} + +output "container_name" { + description = "Specifies the name of the container." + value = azurerm_cosmosdb_sql_container.example.name +} diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/cosmosdb_nosql/variables.tf b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/cosmosdb_nosql/variables.tf new file mode 100644 index 00000000..03d5f22b --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/cosmosdb_nosql/variables.tf @@ -0,0 +1,75 @@ +variable "name" { + description = "(Required) Specifies the name of the Azure Cosmos DB for NoSQL account." + type = string +} + +variable "resource_group_name" { + description = "(Required) Specifies the name of the resource group." + type = string +} + +variable "location" { + description = "(Required) Specifies the location of the Azure Cosmos DB account." + type = string +} + +variable "consistency_level" { + description = "(Optional) Specifies the default consistency level of the Azure Cosmos DB account." + type = string + default = "Session" + + validation { + condition = contains(["BoundedStaleness", "Eventual", "Session", "Strong", "ConsistentPrefix"], var.consistency_level) + error_message = "The consistency_level must be one of BoundedStaleness, Eventual, Session, Strong or ConsistentPrefix." + } +} + +variable "database_name" { + description = "(Required) Specifies the name of the Cosmos DB for NoSQL database." + type = string +} + +variable "container_name" { + description = "(Required) Specifies the name of the container." + type = string +} + +variable "partition_key_path" { + description = "(Required) Specifies the partition key path of the container." + type = string +} + +variable "container_throughput" { + description = "(Optional) Specifies the throughput of the container, in request units per second." + type = number + default = 400 +} + +variable "log_analytics_workspace_id" { + description = "(Required) Specifies the resource id of the Log Analytics workspace." + type = string +} + +variable "diagnostic_setting_name" { + description = "(Optional) Specifies the name of the diagnostic setting of the Azure Cosmos DB account." + type = string + default = "default" +} + +variable "log_categories" { + description = "(Optional) Specifies the log categories the diagnostic setting sends to the Log Analytics workspace: the requests of the web app (DataPlaneRequests) and the requests Azure Resource Manager sends to the account (ControlPlaneRequests)." + type = list(string) + default = ["DataPlaneRequests", "ControlPlaneRequests"] +} + +variable "metric_categories" { + description = "(Optional) Specifies the metric categories the diagnostic setting sends to the Log Analytics workspace." + type = list(string) + default = ["Requests"] +} + +variable "tags" { + description = "(Optional) Specifies the tags of the Azure Cosmos DB account." + type = map(any) + default = {} +} diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/log_analytics/main.tf b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/log_analytics/main.tf new file mode 100644 index 00000000..fcd10cb2 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/log_analytics/main.tf @@ -0,0 +1,35 @@ +resource "azurerm_log_analytics_workspace" "example" { + name = var.name + location = var.location + resource_group_name = var.resource_group_name + sku = var.sku + tags = var.tags + retention_in_days = var.retention_in_days != "" ? var.retention_in_days : null + + lifecycle { + ignore_changes = [ + tags + ] + } +} + +# Query auditing: the diagnostic setting of a workspace can send its audit records to the workspace itself. +resource "azurerm_monitor_diagnostic_setting" "example" { + name = var.diagnostic_setting_name + target_resource_id = azurerm_log_analytics_workspace.example.id + log_analytics_workspace_id = azurerm_log_analytics_workspace.example.id + + dynamic "enabled_log" { + for_each = toset(var.log_categories) + content { + category = enabled_log.value + } + } + + dynamic "enabled_metric" { + for_each = toset(var.metric_categories) + content { + category = enabled_metric.value + } + } +} diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/log_analytics/output.tf b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/log_analytics/output.tf new file mode 100644 index 00000000..fe2c398c --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/log_analytics/output.tf @@ -0,0 +1,30 @@ +output "id" { + value = azurerm_log_analytics_workspace.example.id + description = "Specifies the resource id of the log analytics workspace" +} + +output "location" { + value = azurerm_log_analytics_workspace.example.location + description = "Specifies the location of the log analytics workspace" +} + +output "name" { + value = azurerm_log_analytics_workspace.example.name + description = "Specifies the name of the log analytics workspace" +} + +output "resource_group_name" { + value = azurerm_log_analytics_workspace.example.resource_group_name + description = "Specifies the name of the resource group that contains the log analytics workspace" +} + +output "workspace_id" { + value = azurerm_log_analytics_workspace.example.workspace_id + description = "Specifies the workspace id of the log analytics workspace" +} + +output "primary_shared_key" { + value = azurerm_log_analytics_workspace.example.primary_shared_key + description = "Specifies the workspace key of the log analytics workspace" + sensitive = true +} diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/log_analytics/variables.tf b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/log_analytics/variables.tf new file mode 100644 index 00000000..713a0aa1 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/log_analytics/variables.tf @@ -0,0 +1,55 @@ +variable "resource_group_name" { + description = "(Required) Specifies the name of the resource group." + type = string +} + +variable "location" { + description = "(Required) Specifies the location of the Azure Log Analytics workspace" + type = string +} + +variable "name" { + description = "(Required) Specifies the name of the Azure Log Analytics workspace" + type = string +} + +variable "sku" { + description = "(Optional) Specifies the sku of the Azure Log Analytics workspace" + type = string + default = "PerGB2018" + + validation { + condition = contains(["Free", "Standalone", "PerNode", "PerGB2018"], var.sku) + error_message = "The log analytics sku is incorrect." + } +} + +variable "retention_in_days" { + description = " (Optional) Specifies the workspace data retention in days. Possible values are either 7 (Free Tier only) or range between 30 and 730." + type = number + default = 30 +} + +variable "tags" { + description = "(Optional) Specifies the tags of the Azure Log Analytics workspace." + type = map(any) + default = {} +} + +variable "diagnostic_setting_name" { + description = "(Optional) Specifies the name of the diagnostic setting of the workspace." + type = string + default = "default" +} + +variable "log_categories" { + description = "(Optional) Specifies the log categories that the diagnostic setting of the workspace sends to the workspace itself. Audit records the queries run on the workspace in the LAQueryLogs table." + type = list(string) + default = ["Audit"] +} + +variable "metric_categories" { + description = "(Optional) Specifies the metric categories that the diagnostic setting of the workspace sends to the workspace itself." + type = list(string) + default = ["AllMetrics"] +} diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/managed_identity/main.tf b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/managed_identity/main.tf new file mode 100644 index 00000000..6b312c05 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/managed_identity/main.tf @@ -0,0 +1,14 @@ +# The identity a workload authenticates with. Role assignments are not created here: the role_assignment module +# grants the identity access to the resources the workload uses. +resource "azurerm_user_assigned_identity" "identity" { + name = var.name + resource_group_name = var.resource_group_name + location = var.location + tags = var.tags + + lifecycle { + ignore_changes = [ + tags + ] + } +} diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/managed_identity/outputs.tf b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/managed_identity/outputs.tf new file mode 100644 index 00000000..a23d5861 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/managed_identity/outputs.tf @@ -0,0 +1,24 @@ +output "id" { + description = "Specifies the resource id of the user-assigned managed identity." + value = azurerm_user_assigned_identity.identity.id +} + +output "name" { + description = "Specifies the name of the user-assigned managed identity." + value = azurerm_user_assigned_identity.identity.name +} + +output "client_id" { + description = "Specifies the client id of the user-assigned managed identity, the value a workload passes as AZURE_CLIENT_ID." + value = azurerm_user_assigned_identity.identity.client_id +} + +output "principal_id" { + description = "Specifies the principal (object) id of the user-assigned managed identity, the value role assignments are keyed on." + value = azurerm_user_assigned_identity.identity.principal_id +} + +output "tenant_id" { + description = "Specifies the tenant id of the user-assigned managed identity." + value = azurerm_user_assigned_identity.identity.tenant_id +} diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/managed_identity/variables.tf b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/managed_identity/variables.tf new file mode 100644 index 00000000..b54f3504 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/managed_identity/variables.tf @@ -0,0 +1,20 @@ +variable "name" { + description = "(Required) Specifies the name of the user-assigned managed identity. Changing this forces a new resource to be created." + type = string +} + +variable "resource_group_name" { + description = "(Required) Specifies the name of the resource group of the user-assigned managed identity." + type = string +} + +variable "location" { + description = "(Required) Specifies the location where the user-assigned managed identity is deployed." + type = string +} + +variable "tags" { + description = "(Optional) Specifies the tags of the user-assigned managed identity." + type = map(any) + default = {} +} diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/web_app/main.tf b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/web_app/main.tf new file mode 100644 index 00000000..1a57f1fd --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/web_app/main.tf @@ -0,0 +1,55 @@ +resource "azurerm_linux_web_app" "example" { + name = var.name + resource_group_name = var.resource_group_name + location = var.location + service_plan_id = var.service_plan_id + https_only = var.https_only + public_network_access_enabled = var.public_network_access_enabled + client_affinity_enabled = var.client_affinity_enabled + tags = var.tags + + identity { + type = var.identity_type + identity_ids = var.identity_type == "UserAssigned" ? var.identity_ids : null + } + + site_config { + always_on = var.always_on + http2_enabled = var.http2_enabled + minimum_tls_version = var.minimum_tls_version + + # Exactly one of the two versions is set: the other one is null, which leaves it out. + application_stack { + python_version = var.python_version + dotnet_version = var.dotnet_version + } + } + + app_settings = var.app_settings + + lifecycle { + ignore_changes = [ + tags + ] + } +} + +resource "azurerm_monitor_diagnostic_setting" "example" { + name = var.diagnostic_setting_name + target_resource_id = azurerm_linux_web_app.example.id + log_analytics_workspace_id = var.log_analytics_workspace_id + + dynamic "enabled_log" { + for_each = toset(var.log_categories) + content { + category = enabled_log.value + } + } + + dynamic "enabled_metric" { + for_each = toset(var.metric_categories) + content { + category = enabled_metric.value + } + } +} diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/web_app/outputs.tf b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/web_app/outputs.tf new file mode 100644 index 00000000..76d1b268 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/web_app/outputs.tf @@ -0,0 +1,19 @@ +output "id" { + value = azurerm_linux_web_app.example.id + description = "Specifies the resource id of the Web App" +} + +output "name" { + value = azurerm_linux_web_app.example.name + description = "Specifies the name of the Web App" +} + +output "default_hostname" { + value = azurerm_linux_web_app.example.default_hostname + description = "Specifies the default hostname of the Web App" +} + +output "principal_id" { + value = var.identity_type == "SystemAssigned" ? azurerm_linux_web_app.example.identity[0].principal_id : null + description = "Specifies the principal id of the system-assigned managed identity, or null when the Web App uses a user-assigned identity (its principal id comes from the managed_identity module)" +} diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/web_app/variables.tf b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/web_app/variables.tf new file mode 100644 index 00000000..18d08a69 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/modules/web_app/variables.tf @@ -0,0 +1,127 @@ +variable "resource_group_name" { + description = "(Required) Specifies the name of the resource group." + type = string +} + +variable "location" { + description = "(Required) Specifies the location of the Web App." + type = string +} + +variable "name" { + description = "(Required) Specifies the globally unique name of the Web App." + type = string +} + +variable "service_plan_id" { + description = "(Required) Specifies the resource id of the App Service Plan that hosts the Web App." + type = string +} + +variable "https_only" { + description = "(Optional) Specifies whether the Web App requires HTTPS connections." + type = bool + default = false +} + +variable "public_network_access_enabled" { + description = "(Optional) Specifies whether the public network access is enabled." + type = bool + default = true +} + +variable "client_affinity_enabled" { + description = "(Optional) Specifies whether client affinity (ARR affinity) is enabled." + type = bool + default = false +} + +variable "always_on" { + description = "(Optional) Specifies whether the Web App is always on." + type = bool + default = true +} + +variable "http2_enabled" { + description = "(Optional) Specifies whether HTTP/2 is enabled." + type = bool + default = false +} + +variable "minimum_tls_version" { + description = "(Optional) Specifies the minimum TLS version of the Web App." + type = string + default = "1.2" +} + +variable "python_version" { + description = "(Optional) Specifies the Python version of the Web App. Set either python_version or dotnet_version." + type = string + default = null +} + +variable "dotnet_version" { + description = "(Optional) Specifies the .NET version of the Web App. Set either python_version or dotnet_version." + type = string + default = null +} + +variable "identity_type" { + description = "(Optional) Specifies the type of managed identity of the Web App: SystemAssigned or UserAssigned." + type = string + default = "SystemAssigned" + + validation { + condition = contains(["SystemAssigned", "UserAssigned"], var.identity_type) + error_message = "The identity_type must be either SystemAssigned or UserAssigned." + } +} + +variable "identity_ids" { + description = "(Optional) Specifies the resource ids of the user-assigned managed identities of the Web App. Used only when identity_type is UserAssigned." + type = list(string) + default = [] +} + +variable "app_settings" { + description = "(Optional) Specifies the app settings of the Web App." + type = map(string) + default = {} +} + +variable "log_analytics_workspace_id" { + description = "(Required) Specifies the resource id of the Log Analytics workspace." + type = string +} + +variable "diagnostic_setting_name" { + description = "(Optional) Specifies the name of the diagnostic setting of the Web App." + type = string + default = "default" +} + +variable "log_categories" { + description = "(Optional) Specifies the log categories that the diagnostic setting of the Web App sends to the Log Analytics workspace." + type = list(string) + default = [ + "AppServiceHTTPLogs", + "AppServiceConsoleLogs", + "AppServiceAppLogs", + "AppServiceAuditLogs", + "AppServiceIPSecAuditLogs", + "AppServicePlatformLogs", + "AppServiceAuthenticationLogs", + ] +} + +variable "metric_categories" { + description = "(Optional) Specifies the metric categories that the diagnostic setting of the Web App sends to the Log Analytics workspace." + type = list(string) + default = ["AllMetrics"] +} + +variable "tags" { + description = "(Optional) Specifies the tags of the Web App." + type = map(any) + default = {} +} diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/outputs.tf b/samples/web-app-cosmosdb-nosql-api/python/terraform/outputs.tf new file mode 100644 index 00000000..fa1d0e83 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/outputs.tf @@ -0,0 +1,44 @@ +output "resource_group_name" { + value = azurerm_resource_group.example.name +} + +output "app_service_plan_name" { + value = module.app_service_plan.name +} + +output "web_app_name" { + value = module.web_app.name +} + +output "web_app_url" { + value = module.web_app.default_hostname +} + +output "cosmosdb_account_name" { + value = module.cosmosdb.name +} + +output "cosmosdb_endpoint" { + value = module.cosmosdb.endpoint +} + +output "cosmosdb_database_name" { + value = module.cosmosdb.database_name +} + +output "cosmosdb_container_name" { + value = module.cosmosdb.container_name +} + +output "principal_id" { + description = "The principal id of the managed identity the web app reaches the Cosmos DB account with." + value = var.managed_identity_type == "UserAssigned" ? module.managed_identity[0].principal_id : module.web_app.principal_id +} + +output "log_analytics_name" { + value = module.log_analytics.name +} + +output "application_insights_name" { + value = module.application_insights.name +} diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/providers.tf b/samples/web-app-cosmosdb-nosql-api/python/terraform/providers.tf new file mode 100644 index 00000000..2757acc5 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/providers.tf @@ -0,0 +1,24 @@ +terraform { + required_version = ">=1.0" + + required_providers { + azurerm = { + source = "hashicorp/azurerm" + version = "=5.1.0" + } + } +} + +provider "azurerm" { + features { + resource_group { + prevent_deletion_if_contains_resources = false + } + } + + # Dual-target, deliberately: nothing emulator-specific is hardcoded here. deploy.sh exports ARM_SUBSCRIPTION_ID and + # ARM_TENANT_ID on both targets and, only when the active az cloud is LocalStack, ARM_METADATA_HOSTNAME (the + # emulator's metadata endpoint, from which the provider discovers every other endpoint). Authentication uses the + # Azure CLI session on both targets. Running terraform directly rather than through deploy.sh needs those variables + # exported. +} diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/terraform.tfvars b/samples/web-app-cosmosdb-nosql-api/python/terraform/terraform.tfvars new file mode 100644 index 00000000..111c2c40 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/terraform.tfvars @@ -0,0 +1,2 @@ +location = "westeurope" +python_version = "3.13" \ No newline at end of file diff --git a/samples/web-app-cosmosdb-nosql-api/python/terraform/variables.tf b/samples/web-app-cosmosdb-nosql-api/python/terraform/variables.tf new file mode 100644 index 00000000..73764829 --- /dev/null +++ b/samples/web-app-cosmosdb-nosql-api/python/terraform/variables.tf @@ -0,0 +1,200 @@ +variable "prefix" { + description = "(Optional) Specifies the prefix for the name of the Azure resources." + type = string + default = "local" + + validation { + condition = var.prefix == null || length(var.prefix) >= 2 + error_message = "The prefix must be at least 2 characters long." + } +} + +variable "suffix" { + description = "(Optional) Specifies the suffix for the name of the Azure resources." + type = string + default = "test" + + validation { + condition = var.suffix == null || length(var.suffix) >= 2 + error_message = "The suffix must be at least 2 characters long." + } +} + +variable "location" { + description = "(Required) Specifies the location for all resources." + type = string + default = null +} + +variable "cosmosdb_database_name" { + description = "(Optional) Specifies the name of the Cosmos DB for NoSQL database." + type = string + default = "vacationplanner" +} + +variable "cosmosdb_container_name" { + description = "(Optional) Specifies the name of the container that holds the activities." + type = string + default = "activities" +} + +variable "cosmosdb_partition_key_path" { + description = "(Optional) Specifies the partition key path of the container." + type = string + default = "/username" +} + +variable "cosmosdb_container_throughput" { + description = "(Optional) Specifies the throughput of the container, in request units per second." + type = number + default = 400 +} + +variable "os_type" { + description = "(Required) Specifies the O/S type for the App Services to be hosted in this plan. Possible values include Windows, Linux, and WindowsContainer. Changing this forces a new resource to be created." + type = string + default = "Linux" + + validation { + condition = contains([ + "Windows", + "Linux", + "WindowsContainer" + ], var.os_type) + error_message = "The os_type must be either 'Windows', 'Linux', or 'WindowsContainer'." + } +} + +variable "zone_balancing_enabled" { + description = "(Optional) Should the Service Plan balance across Availability Zones in the region." + type = bool + default = false +} + +variable "sku_name" { + description = "(Optional) Specifies the SKU name for the hosting plan." + type = string + default = "B1" + + validation { + condition = contains([ + "B1", "B2", "B3", + "S1", "S2", "S3", + "EP1", "EP2", "EP3", + "P1v2", "P2v2", "P3v2", + "P0v3", "P1v3", "P2v3", "P3v3", + "P1mv3", "P2mv3", "P3mv3", "P4mv3", "P5mv3", + "I1", "I2", "I3", + "I1v2", "I2v2", "I3v2", "I4v2", "I5v2", "I6v2", + "WS1", "WS2", "WS3", + "FC1" + ], var.sku_name) + error_message = "The sku_name must be one of the allowed values." + } +} + +variable "python_version" { + description = "(Optional) Specifies the version of Python to run. Possible values include 3.12, 3.11, 3.10, 3.9, 3.8 and 3.7." + type = string + default = "3.13" + + validation { + condition = contains([ + "3.14", + "3.13", + "3.12", + "3.11", + "3.10", + "3.9", + "3.8", + "3.7" + ], var.python_version) + error_message = "The python_version must be one of the supported versions: 3.13, 3.12, 3.11, 3.10, 3.9, 3.8, 3.7." + } +} + +variable "https_only" { + description = "(Optional) Specifies whether the Linux Web App require HTTPS connections. Defaults to false." + type = bool + default = false +} + +variable "minimum_tls_version" { + description = "(Optional) Specifies the minimum version of TLS required for SSL requests. Possible values include: 1.0, 1.1, 1.2 and 1.3. Defaults to 1.2." + type = string + default = "1.2" + + validation { + condition = contains([ + "1.0", + "1.1", + "1.2", + "1.3" + ], var.minimum_tls_version) + error_message = "The minimum_tls_version must be one of the allowed values." + } +} + +variable "always_on" { + description = "(Optional) Specifies whether the Linux Web App is Always On enabled. Defaults to true." + type = bool + default = true +} + +variable "http2_enabled" { + description = "(Optional) Specifies whether HTTP/2 is enabled for the Linux Web App." + type = bool + default = false +} + +variable "webapp_public_network_access_enabled" { + description = "(Optional) Specifies whether the public network access is enabled or disabled." + type = bool + default = true +} + +variable "managed_identity_type" { + description = "(Optional) Specifies the type of managed identity the web app reaches the Cosmos DB account with, through Microsoft Entra ID." + type = string + default = "UserAssigned" + + validation { + condition = contains(["SystemAssigned", "UserAssigned"], var.managed_identity_type) + error_message = "The managed_identity_type must be either 'SystemAssigned' or 'UserAssigned'." + } +} + +variable "tags" { + description = "(Optional) Specifies the tags to be applied to the resources." + type = map(string) + default = { + environment = "test" + iac = "terraform" + } +} + +variable "diagnostic_settings_name" { + description = "(Optional) Specifies the name of the diagnostic settings of the Cosmos DB account, of the web app and of the App Service plan." + type = string + default = "default" +} + +variable "log_categories" { + description = "(Optional) Specifies the log categories that the diagnostic settings of the web app send to the Log Analytics workspace." + type = list(string) + default = [ + "AppServiceHTTPLogs", + "AppServiceConsoleLogs", + "AppServiceAppLogs", + "AppServiceAuditLogs", + "AppServiceIPSecAuditLogs", + "AppServicePlatformLogs", + "AppServiceAuthenticationLogs", + ] +} + +variable "metric_categories" { + description = "(Optional) Specifies the metric categories that the diagnostic settings of the web app and of the App Service plan send to the Log Analytics workspace." + type = list(string) + default = ["AllMetrics"] +} diff --git a/samples/web-app-custom-image/dotnet/bicep/acr.bicep b/samples/web-app-custom-image/dotnet/bicep/acr.bicep index 01a4e6bb..6e3fa251 100644 --- a/samples/web-app-custom-image/dotnet/bicep/acr.bicep +++ b/samples/web-app-custom-image/dotnet/bicep/acr.bicep @@ -22,7 +22,7 @@ param logAnalyticsName string = '' 'PerNode' 'PerGB2018' ]) -param logAnalyticsSku string = 'PerNode' +param logAnalyticsSku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param logAnalyticsRetentionInDays int = 60 diff --git a/samples/web-app-custom-image/dotnet/bicep/modules/log-analytics.bicep b/samples/web-app-custom-image/dotnet/bicep/modules/log-analytics.bicep index 0f9ca50d..2096fc03 100644 --- a/samples/web-app-custom-image/dotnet/bicep/modules/log-analytics.bicep +++ b/samples/web-app-custom-image/dotnet/bicep/modules/log-analytics.bicep @@ -14,7 +14,7 @@ param location string = resourceGroup().location 'PerNode' 'PerGB2018' ]) -param sku string = 'PerNode' +param sku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param retentionInDays int = 60 diff --git a/samples/web-app-custom-image/dotnet/scripts/deploy.sh b/samples/web-app-custom-image/dotnet/scripts/deploy.sh index 3f338224..872f85db 100755 --- a/samples/web-app-custom-image/dotnet/scripts/deploy.sh +++ b/samples/web-app-custom-image/dotnet/scripts/deploy.sh @@ -812,7 +812,7 @@ if [[ $? != 0 ]]; then --location "$LOCATION" \ --query-access "Enabled" \ --retention-time 30 \ - --sku "PerNode" \ + --sku "PerGB2018" \ --only-show-errors 1>/dev/null if [[ $? == 0 ]]; then diff --git a/samples/web-app-custom-image/dotnet/terraform/deploy.sh b/samples/web-app-custom-image/dotnet/terraform/deploy.sh index b76cd531..5deba61e 100755 --- a/samples/web-app-custom-image/dotnet/terraform/deploy.sh +++ b/samples/web-app-custom-image/dotnet/terraform/deploy.sh @@ -16,13 +16,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets the emulator at [$RESOURCE_MANAGER_ENDPOINT]" diff --git a/samples/web-app-custom-image/python/bicep/acr.bicep b/samples/web-app-custom-image/python/bicep/acr.bicep index 01a4e6bb..6e3fa251 100644 --- a/samples/web-app-custom-image/python/bicep/acr.bicep +++ b/samples/web-app-custom-image/python/bicep/acr.bicep @@ -22,7 +22,7 @@ param logAnalyticsName string = '' 'PerNode' 'PerGB2018' ]) -param logAnalyticsSku string = 'PerNode' +param logAnalyticsSku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param logAnalyticsRetentionInDays int = 60 diff --git a/samples/web-app-custom-image/python/bicep/modules/log-analytics.bicep b/samples/web-app-custom-image/python/bicep/modules/log-analytics.bicep index 0f9ca50d..2096fc03 100644 --- a/samples/web-app-custom-image/python/bicep/modules/log-analytics.bicep +++ b/samples/web-app-custom-image/python/bicep/modules/log-analytics.bicep @@ -14,7 +14,7 @@ param location string = resourceGroup().location 'PerNode' 'PerGB2018' ]) -param sku string = 'PerNode' +param sku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param retentionInDays int = 60 diff --git a/samples/web-app-custom-image/python/scripts/deploy.sh b/samples/web-app-custom-image/python/scripts/deploy.sh index 3f338224..872f85db 100755 --- a/samples/web-app-custom-image/python/scripts/deploy.sh +++ b/samples/web-app-custom-image/python/scripts/deploy.sh @@ -812,7 +812,7 @@ if [[ $? != 0 ]]; then --location "$LOCATION" \ --query-access "Enabled" \ --retention-time 30 \ - --sku "PerNode" \ + --sku "PerGB2018" \ --only-show-errors 1>/dev/null if [[ $? == 0 ]]; then diff --git a/samples/web-app-custom-image/python/terraform/deploy.sh b/samples/web-app-custom-image/python/terraform/deploy.sh index b76cd531..5deba61e 100755 --- a/samples/web-app-custom-image/python/terraform/deploy.sh +++ b/samples/web-app-custom-image/python/terraform/deploy.sh @@ -16,13 +16,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets the emulator at [$RESOURCE_MANAGER_ENDPOINT]" diff --git a/samples/web-app-managed-identity/dotnet/bicep/modules/log-analytics.bicep b/samples/web-app-managed-identity/dotnet/bicep/modules/log-analytics.bicep index 0f9ca50d..2096fc03 100644 --- a/samples/web-app-managed-identity/dotnet/bicep/modules/log-analytics.bicep +++ b/samples/web-app-managed-identity/dotnet/bicep/modules/log-analytics.bicep @@ -14,7 +14,7 @@ param location string = resourceGroup().location 'PerNode' 'PerGB2018' ]) -param sku string = 'PerNode' +param sku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param retentionInDays int = 60 diff --git a/samples/web-app-managed-identity/dotnet/terraform/deploy.sh b/samples/web-app-managed-identity/dotnet/terraform/deploy.sh index 6f6a7f4d..bd0701f0 100755 --- a/samples/web-app-managed-identity/dotnet/terraform/deploy.sh +++ b/samples/web-app-managed-identity/dotnet/terraform/deploy.sh @@ -16,13 +16,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets the emulator at [$RESOURCE_MANAGER_ENDPOINT]" diff --git a/samples/web-app-managed-identity/python/bicep/modules/log-analytics.bicep b/samples/web-app-managed-identity/python/bicep/modules/log-analytics.bicep index 0f9ca50d..2096fc03 100644 --- a/samples/web-app-managed-identity/python/bicep/modules/log-analytics.bicep +++ b/samples/web-app-managed-identity/python/bicep/modules/log-analytics.bicep @@ -14,7 +14,7 @@ param location string = resourceGroup().location 'PerNode' 'PerGB2018' ]) -param sku string = 'PerNode' +param sku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param retentionInDays int = 60 diff --git a/samples/web-app-managed-identity/python/terraform/deploy.sh b/samples/web-app-managed-identity/python/terraform/deploy.sh index 36b948d1..41e93c5b 100755 --- a/samples/web-app-managed-identity/python/terraform/deploy.sh +++ b/samples/web-app-managed-identity/python/terraform/deploy.sh @@ -16,13 +16,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets the emulator at [$RESOURCE_MANAGER_ENDPOINT]" diff --git a/samples/web-app-mysql-flexible-server/dotnet/bicep/main.bicep b/samples/web-app-mysql-flexible-server/dotnet/bicep/main.bicep index 09ca6a18..469c6991 100644 --- a/samples/web-app-mysql-flexible-server/dotnet/bicep/main.bicep +++ b/samples/web-app-mysql-flexible-server/dotnet/bicep/main.bicep @@ -160,7 +160,7 @@ param applicationInsightsName string = '' @description('Specifies the service tier of the workspace.') @allowed(['Free','Standalone','PerNode','PerGB2018']) -param logAnalyticsSku string = 'PerNode' +param logAnalyticsSku string = 'PerGB2018' @description('Specifies the workspace data retention in days.') param logAnalyticsRetentionInDays int = 60 diff --git a/samples/web-app-mysql-flexible-server/dotnet/bicep/modules/log-analytics.bicep b/samples/web-app-mysql-flexible-server/dotnet/bicep/modules/log-analytics.bicep index 0f9ca50d..2096fc03 100644 --- a/samples/web-app-mysql-flexible-server/dotnet/bicep/modules/log-analytics.bicep +++ b/samples/web-app-mysql-flexible-server/dotnet/bicep/modules/log-analytics.bicep @@ -14,7 +14,7 @@ param location string = resourceGroup().location 'PerNode' 'PerGB2018' ]) -param sku string = 'PerNode' +param sku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param retentionInDays int = 60 diff --git a/samples/web-app-mysql-flexible-server/dotnet/scripts/deploy.sh b/samples/web-app-mysql-flexible-server/dotnet/scripts/deploy.sh index c5823769..191eaf9b 100755 --- a/samples/web-app-mysql-flexible-server/dotnet/scripts/deploy.sh +++ b/samples/web-app-mysql-flexible-server/dotnet/scripts/deploy.sh @@ -925,7 +925,7 @@ if [[ $? != 0 ]]; then --location "$LOCATION" \ --query-access "Enabled" \ --retention-time 30 \ - --sku "PerNode" \ + --sku "PerGB2018" \ --tags environment=test iac=az-cli \ --only-show-errors 1>/dev/null diff --git a/samples/web-app-mysql-flexible-server/dotnet/terraform/deploy.sh b/samples/web-app-mysql-flexible-server/dotnet/terraform/deploy.sh index 902833d4..84ca6b57 100755 --- a/samples/web-app-mysql-flexible-server/dotnet/terraform/deploy.sh +++ b/samples/web-app-mysql-flexible-server/dotnet/terraform/deploy.sh @@ -30,13 +30,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets the emulator at [$RESOURCE_MANAGER_ENDPOINT]" diff --git a/samples/web-app-mysql-flexible-server/python/bicep/main.bicep b/samples/web-app-mysql-flexible-server/python/bicep/main.bicep index 7503ac33..b6339cd4 100644 --- a/samples/web-app-mysql-flexible-server/python/bicep/main.bicep +++ b/samples/web-app-mysql-flexible-server/python/bicep/main.bicep @@ -160,7 +160,7 @@ param applicationInsightsName string = '' @description('Specifies the service tier of the workspace.') @allowed(['Free','Standalone','PerNode','PerGB2018']) -param logAnalyticsSku string = 'PerNode' +param logAnalyticsSku string = 'PerGB2018' @description('Specifies the workspace data retention in days.') param logAnalyticsRetentionInDays int = 60 diff --git a/samples/web-app-mysql-flexible-server/python/bicep/modules/log-analytics.bicep b/samples/web-app-mysql-flexible-server/python/bicep/modules/log-analytics.bicep index 0f9ca50d..2096fc03 100644 --- a/samples/web-app-mysql-flexible-server/python/bicep/modules/log-analytics.bicep +++ b/samples/web-app-mysql-flexible-server/python/bicep/modules/log-analytics.bicep @@ -14,7 +14,7 @@ param location string = resourceGroup().location 'PerNode' 'PerGB2018' ]) -param sku string = 'PerNode' +param sku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param retentionInDays int = 60 diff --git a/samples/web-app-mysql-flexible-server/python/scripts/deploy.sh b/samples/web-app-mysql-flexible-server/python/scripts/deploy.sh index b9abb6db..23cd528f 100755 --- a/samples/web-app-mysql-flexible-server/python/scripts/deploy.sh +++ b/samples/web-app-mysql-flexible-server/python/scripts/deploy.sh @@ -925,7 +925,7 @@ if [[ $? != 0 ]]; then --location "$LOCATION" \ --query-access "Enabled" \ --retention-time 30 \ - --sku "PerNode" \ + --sku "PerGB2018" \ --tags environment=test iac=az-cli \ --only-show-errors 1>/dev/null diff --git a/samples/web-app-mysql-flexible-server/python/terraform/deploy.sh b/samples/web-app-mysql-flexible-server/python/terraform/deploy.sh index 8397011e..ff73c34d 100755 --- a/samples/web-app-mysql-flexible-server/python/terraform/deploy.sh +++ b/samples/web-app-mysql-flexible-server/python/terraform/deploy.sh @@ -30,13 +30,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets the emulator at [$RESOURCE_MANAGER_ENDPOINT]" diff --git a/samples/web-app-postgresql-flexible-server/dotnet/bicep/main.bicep b/samples/web-app-postgresql-flexible-server/dotnet/bicep/main.bicep index b05993fa..5e5b5c33 100644 --- a/samples/web-app-postgresql-flexible-server/dotnet/bicep/main.bicep +++ b/samples/web-app-postgresql-flexible-server/dotnet/bicep/main.bicep @@ -160,7 +160,7 @@ param applicationInsightsName string = '' @description('Specifies the service tier of the workspace.') @allowed(['Free','Standalone','PerNode','PerGB2018']) -param logAnalyticsSku string = 'PerNode' +param logAnalyticsSku string = 'PerGB2018' @description('Specifies the workspace data retention in days.') param logAnalyticsRetentionInDays int = 60 diff --git a/samples/web-app-postgresql-flexible-server/dotnet/bicep/modules/log-analytics.bicep b/samples/web-app-postgresql-flexible-server/dotnet/bicep/modules/log-analytics.bicep index 0f9ca50d..2096fc03 100644 --- a/samples/web-app-postgresql-flexible-server/dotnet/bicep/modules/log-analytics.bicep +++ b/samples/web-app-postgresql-flexible-server/dotnet/bicep/modules/log-analytics.bicep @@ -14,7 +14,7 @@ param location string = resourceGroup().location 'PerNode' 'PerGB2018' ]) -param sku string = 'PerNode' +param sku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param retentionInDays int = 60 diff --git a/samples/web-app-postgresql-flexible-server/dotnet/scripts/deploy.sh b/samples/web-app-postgresql-flexible-server/dotnet/scripts/deploy.sh index 60ccc490..0f7b73c0 100755 --- a/samples/web-app-postgresql-flexible-server/dotnet/scripts/deploy.sh +++ b/samples/web-app-postgresql-flexible-server/dotnet/scripts/deploy.sh @@ -922,7 +922,7 @@ if [[ $? != 0 ]]; then --location "$LOCATION" \ --query-access "Enabled" \ --retention-time 30 \ - --sku "PerNode" \ + --sku "PerGB2018" \ --tags environment=test iac=az-cli \ --only-show-errors 1>/dev/null diff --git a/samples/web-app-postgresql-flexible-server/dotnet/terraform/deploy.sh b/samples/web-app-postgresql-flexible-server/dotnet/terraform/deploy.sh index 43639e4c..ae638aa2 100755 --- a/samples/web-app-postgresql-flexible-server/dotnet/terraform/deploy.sh +++ b/samples/web-app-postgresql-flexible-server/dotnet/terraform/deploy.sh @@ -19,13 +19,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets the emulator at [$RESOURCE_MANAGER_ENDPOINT]" diff --git a/samples/web-app-postgresql-flexible-server/python/bicep/main.bicep b/samples/web-app-postgresql-flexible-server/python/bicep/main.bicep index 69dee740..7f4fe6f0 100644 --- a/samples/web-app-postgresql-flexible-server/python/bicep/main.bicep +++ b/samples/web-app-postgresql-flexible-server/python/bicep/main.bicep @@ -160,7 +160,7 @@ param applicationInsightsName string = '' @description('Specifies the service tier of the workspace.') @allowed(['Free','Standalone','PerNode','PerGB2018']) -param logAnalyticsSku string = 'PerNode' +param logAnalyticsSku string = 'PerGB2018' @description('Specifies the workspace data retention in days.') param logAnalyticsRetentionInDays int = 60 diff --git a/samples/web-app-postgresql-flexible-server/python/bicep/modules/log-analytics.bicep b/samples/web-app-postgresql-flexible-server/python/bicep/modules/log-analytics.bicep index 0f9ca50d..2096fc03 100644 --- a/samples/web-app-postgresql-flexible-server/python/bicep/modules/log-analytics.bicep +++ b/samples/web-app-postgresql-flexible-server/python/bicep/modules/log-analytics.bicep @@ -14,7 +14,7 @@ param location string = resourceGroup().location 'PerNode' 'PerGB2018' ]) -param sku string = 'PerNode' +param sku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param retentionInDays int = 60 diff --git a/samples/web-app-postgresql-flexible-server/python/scripts/deploy.sh b/samples/web-app-postgresql-flexible-server/python/scripts/deploy.sh index c3a5aa59..a821ab48 100755 --- a/samples/web-app-postgresql-flexible-server/python/scripts/deploy.sh +++ b/samples/web-app-postgresql-flexible-server/python/scripts/deploy.sh @@ -922,7 +922,7 @@ if [[ $? != 0 ]]; then --location "$LOCATION" \ --query-access "Enabled" \ --retention-time 30 \ - --sku "PerNode" \ + --sku "PerGB2018" \ --tags environment=test iac=az-cli \ --only-show-errors 1>/dev/null diff --git a/samples/web-app-postgresql-flexible-server/python/terraform/deploy.sh b/samples/web-app-postgresql-flexible-server/python/terraform/deploy.sh index d44bd2f1..0f1bf7c0 100755 --- a/samples/web-app-postgresql-flexible-server/python/terraform/deploy.sh +++ b/samples/web-app-postgresql-flexible-server/python/terraform/deploy.sh @@ -19,13 +19,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" echo "Active cloud is [$ACTIVE_CLOUD]: Terraform targets the emulator at [$RESOURCE_MANAGER_ENDPOINT]" diff --git a/samples/web-app-sql-database/dotnet/bicep/main.bicep b/samples/web-app-sql-database/dotnet/bicep/main.bicep index bceaa46e..4d94d801 100644 --- a/samples/web-app-sql-database/dotnet/bicep/main.bicep +++ b/samples/web-app-sql-database/dotnet/bicep/main.bicep @@ -328,7 +328,7 @@ param applicationInsightsName string = '' @description('Specifies the service tier of the workspace.') @allowed(['Free','Standalone','PerNode','PerGB2018']) -param logAnalyticsSku string = 'PerNode' +param logAnalyticsSku string = 'PerGB2018' @description('Specifies the workspace data retention in days.') param logAnalyticsRetentionInDays int = 60 diff --git a/samples/web-app-sql-database/dotnet/bicep/modules/log-analytics.bicep b/samples/web-app-sql-database/dotnet/bicep/modules/log-analytics.bicep index 0f9ca50d..2096fc03 100644 --- a/samples/web-app-sql-database/dotnet/bicep/modules/log-analytics.bicep +++ b/samples/web-app-sql-database/dotnet/bicep/modules/log-analytics.bicep @@ -14,7 +14,7 @@ param location string = resourceGroup().location 'PerNode' 'PerGB2018' ]) -param sku string = 'PerNode' +param sku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param retentionInDays int = 60 diff --git a/samples/web-app-sql-database/dotnet/scripts/deploy.sh b/samples/web-app-sql-database/dotnet/scripts/deploy.sh index 613bc67f..d8c226c7 100755 --- a/samples/web-app-sql-database/dotnet/scripts/deploy.sh +++ b/samples/web-app-sql-database/dotnet/scripts/deploy.sh @@ -199,7 +199,7 @@ if [[ $? != 0 ]]; then --location "$LOCATION" \ --query-access "Enabled" \ --retention-time 30 \ - --sku "PerNode" \ + --sku "PerGB2018" \ --tags environment=test iac=az-cli \ --only-show-errors 1>/dev/null diff --git a/samples/web-app-sql-database/dotnet/terraform/deploy.sh b/samples/web-app-sql-database/dotnet/terraform/deploy.sh index 4f37a224..9114222b 100755 --- a/samples/web-app-sql-database/dotnet/terraform/deploy.sh +++ b/samples/web-app-sql-database/dotnet/terraform/deploy.sh @@ -22,13 +22,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" # The emulator applies role assignments immediately, so the roles need no propagation wait. diff --git a/samples/web-app-sql-database/python/bicep/main.bicep b/samples/web-app-sql-database/python/bicep/main.bicep index c14456a7..132e9f79 100644 --- a/samples/web-app-sql-database/python/bicep/main.bicep +++ b/samples/web-app-sql-database/python/bicep/main.bicep @@ -327,7 +327,7 @@ param applicationInsightsName string = '' @description('Specifies the service tier of the workspace.') @allowed(['Free','Standalone','PerNode','PerGB2018']) -param logAnalyticsSku string = 'PerNode' +param logAnalyticsSku string = 'PerGB2018' @description('Specifies the workspace data retention in days.') param logAnalyticsRetentionInDays int = 60 diff --git a/samples/web-app-sql-database/python/bicep/modules/log-analytics.bicep b/samples/web-app-sql-database/python/bicep/modules/log-analytics.bicep index 0f9ca50d..2096fc03 100644 --- a/samples/web-app-sql-database/python/bicep/modules/log-analytics.bicep +++ b/samples/web-app-sql-database/python/bicep/modules/log-analytics.bicep @@ -14,7 +14,7 @@ param location string = resourceGroup().location 'PerNode' 'PerGB2018' ]) -param sku string = 'PerNode' +param sku string = 'PerGB2018' @description('Specifies the workspace data retention in days. -1 means Unlimited retention for the Unlimited Sku. 730 days is the maximum allowed for all other Skus.') param retentionInDays int = 60 diff --git a/samples/web-app-sql-database/python/scripts/deploy.sh b/samples/web-app-sql-database/python/scripts/deploy.sh index c3f92c43..7ebc74bb 100755 --- a/samples/web-app-sql-database/python/scripts/deploy.sh +++ b/samples/web-app-sql-database/python/scripts/deploy.sh @@ -199,7 +199,7 @@ if [[ $? != 0 ]]; then --location "$LOCATION" \ --query-access "Enabled" \ --retention-time 30 \ - --sku "PerNode" \ + --sku "PerGB2018" \ --tags environment=test iac=az-cli \ --only-show-errors 1>/dev/null diff --git a/samples/web-app-sql-database/python/terraform/deploy.sh b/samples/web-app-sql-database/python/terraform/deploy.sh index 2322a28c..ba5c8852 100755 --- a/samples/web-app-sql-database/python/terraform/deploy.sh +++ b/samples/web-app-sql-database/python/terraform/deploy.sh @@ -22,13 +22,13 @@ cd "$CURRENT_DIR" || exit # - On both targets: the subscription and tenant of the active az account. # - Only when the active az cloud is LocalStack: the emulator's metadata endpoint, taken from the az cloud registration # that `lstk az start-interception` created, so nothing is hardcoded here either. -ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors) -ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors) -ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors) +ACTIVE_CLOUD=$(az cloud show --query name --output tsv --only-show-errors | tr -d '\r') +ARM_SUBSCRIPTION_ID=$(az account show --query id --output tsv --only-show-errors | tr -d '\r') +ARM_TENANT_ID=$(az account show --query tenantId --output tsv --only-show-errors | tr -d '\r') export ARM_SUBSCRIPTION_ID ARM_TENANT_ID if [[ $ACTIVE_CLOUD == "LocalStack" ]]; then - RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors) + RESOURCE_MANAGER_ENDPOINT=$(az cloud show --query endpoints.resourceManager --output tsv --only-show-errors | tr -d '\r') METADATA_HOSTNAME="${RESOURCE_MANAGER_ENDPOINT#https://}" export ARM_METADATA_HOSTNAME="${METADATA_HOSTNAME%/}" # The emulator applies role assignments immediately, so the roles need no propagation wait.