diff --git a/.github/iac/swa/azure.yaml b/.github/iac/swa/azure.yaml new file mode 100644 index 00000000000..e2439c0f878 --- /dev/null +++ b/.github/iac/swa/azure.yaml @@ -0,0 +1,28 @@ +# yaml-language-server: $schema=https://raw.githubusercontent.com/Azure/azure-dev/main/schemas/v1.0/azure.yaml.json + +name: swa-deploy-dapr-docs +metadata: + template: swa-deploy-dapr-docs@0.0.1-beta +#hooks: + # postprovision: + # windows: + # shell: pwsh + # run: ./scripts/deploy.ps1 + # interactive: true + # continueOnError: false + # posix: + # shell: sh + # run: ./scripts/deploy.sh + # interactive: true + # continueOnError: false + # predeploy: + # windows: + # shell: pwsh + # run: cd ./app/frontend;npm install;npm run build + # interactive: true + # continueOnError: false + # posix: + # shell: sh + # run: cd ./app/frontend;npm install;npm run build + # interactive: true + # continueOnError: false \ No newline at end of file diff --git a/.github/iac/swa/infra/abbreviations.json b/.github/iac/swa/infra/abbreviations.json new file mode 100644 index 00000000000..703e503867c --- /dev/null +++ b/.github/iac/swa/infra/abbreviations.json @@ -0,0 +1,135 @@ +{ + "analysisServicesServers": "as", + "apiManagementService": "apim-", + "appConfigurationConfigurationStores": "appcs-", + "appManagedEnvironments": "cae-", + "appContainerApps": "ca-", + "authorizationPolicyDefinitions": "policy-", + "automationAutomationAccounts": "aa-", + "blueprintBlueprints": "bp-", + "blueprintBlueprintsArtifacts": "bpa-", + "cacheRedis": "redis-", + "cdnProfiles": "cdnp-", + "cdnProfilesEndpoints": "cdne-", + "cognitiveServicesAccounts": "cog-", + "cognitiveServicesFormRecognizer": "cog-fr-", + "cognitiveServicesTextAnalytics": "cog-ta-", + "computeAvailabilitySets": "avail-", + "computeCloudServices": "cld-", + "computeDiskEncryptionSets": "des", + "computeDisks": "disk", + "computeDisksOs": "osdisk", + "computeGalleries": "gal", + "computeSnapshots": "snap-", + "computeVirtualMachines": "vm", + "computeVirtualMachineScaleSets": "vmss-", + "containerInstanceContainerGroups": "ci", + "containerRegistryRegistries": "cr", + "containerServiceManagedClusters": "aks-", + "databricksWorkspaces": "dbw-", + "dataFactoryFactories": "adf-", + "dataLakeAnalyticsAccounts": "dla", + "dataLakeStoreAccounts": "dls", + "dataMigrationServices": "dms-", + "dBforMySQLServers": "mysql-", + "dBforPostgreSQLServers": "psql-", + "devicesIotHubs": "iot-", + "devicesProvisioningServices": "provs-", + "devicesProvisioningServicesCertificates": "pcert-", + "documentDBDatabaseAccounts": "cosmos-", + "eventGridDomains": "evgd-", + "eventGridDomainsTopics": "evgt-", + "eventGridEventSubscriptions": "evgs-", + "eventHubNamespaces": "evhns-", + "eventHubNamespacesEventHubs": "evh-", + "hdInsightClustersHadoop": "hadoop-", + "hdInsightClustersHbase": "hbase-", + "hdInsightClustersKafka": "kafka-", + "hdInsightClustersMl": "mls-", + "hdInsightClustersSpark": "spark-", + "hdInsightClustersStorm": "storm-", + "hybridComputeMachines": "arcs-", + "insightsActionGroups": "ag-", + "insightsComponents": "appi-", + "keyVaultVaults": "kv-", + "kubernetesConnectedClusters": "arck", + "kustoClusters": "dec", + "kustoClustersDatabases": "dedb", + "logicIntegrationAccounts": "ia-", + "logicWorkflows": "logic-", + "machineLearningServicesWorkspaces": "mlw-", + "managedIdentityUserAssignedIdentities": "id-", + "managementManagementGroups": "mg-", + "migrateAssessmentProjects": "migr-", + "networkApplicationGateways": "agw-", + "networkApplicationSecurityGroups": "asg-", + "networkAzureFirewalls": "afw-", + "networkBastionHosts": "bas-", + "networkConnections": "con-", + "networkDnsZones": "dnsz-", + "networkExpressRouteCircuits": "erc-", + "networkFirewallPolicies": "afwp-", + "networkFirewallPoliciesWebApplication": "waf", + "networkFirewallPoliciesRuleGroups": "wafrg", + "networkFrontDoors": "fd-", + "networkFrontdoorWebApplicationFirewallPolicies": "fdfp-", + "networkLoadBalancersExternal": "lbe-", + "networkLoadBalancersInternal": "lbi-", + "networkLoadBalancersInboundNatRules": "rule-", + "networkLocalNetworkGateways": "lgw-", + "networkNatGateways": "ng-", + "networkNetworkInterfaces": "nic-", + "networkNetworkSecurityGroups": "nsg-", + "networkNetworkSecurityGroupsSecurityRules": "nsgsr-", + "networkNetworkWatchers": "nw-", + "networkPrivateDnsZones": "pdnsz-", + "networkPrivateLinkServices": "pl-", + "networkPublicIPAddresses": "pip-", + "networkPublicIPPrefixes": "ippre-", + "networkRouteFilters": "rf-", + "networkRouteTables": "rt-", + "networkRouteTablesRoutes": "udr-", + "networkTrafficManagerProfiles": "traf-", + "networkVirtualNetworkGateways": "vgw-", + "networkVirtualNetworks": "vnet-", + "networkVirtualNetworksSubnets": "snet-", + "networkVirtualNetworksVirtualNetworkPeerings": "peer-", + "networkVirtualWans": "vwan-", + "networkVpnGateways": "vpng-", + "networkVpnGatewaysVpnConnections": "vcn-", + "networkVpnGatewaysVpnSites": "vst-", + "notificationHubsNamespaces": "ntfns-", + "notificationHubsNamespacesNotificationHubs": "ntf-", + "operationalInsightsWorkspaces": "log-", + "portalDashboards": "dash-", + "powerBIDedicatedCapacities": "pbi-", + "purviewAccounts": "pview-", + "recoveryServicesVaults": "rsv-", + "resourcesResourceGroups": "rg-", + "searchSearchServices": "srch-", + "serviceBusNamespaces": "sb-", + "serviceBusNamespacesQueues": "sbq-", + "serviceBusNamespacesTopics": "sbt-", + "serviceEndPointPolicies": "se-", + "serviceFabricClusters": "sf-", + "signalRServiceSignalR": "sigr", + "sqlManagedInstances": "sqlmi-", + "sqlServers": "sql-", + "sqlServersDataWarehouse": "sqldw-", + "sqlServersDatabases": "sqldb-", + "sqlServersDatabasesStretch": "sqlstrdb-", + "storageStorageAccounts": "st", + "storageStorageAccountsVm": "stvm", + "storSimpleManagers": "ssimp", + "streamAnalyticsCluster": "asa-", + "synapseWorkspaces": "syn", + "synapseWorkspacesAnalyticsWorkspaces": "synw", + "synapseWorkspacesSqlPoolsDedicated": "syndp", + "synapseWorkspacesSqlPoolsSpark": "synsp", + "timeSeriesInsightsEnvironments": "tsi-", + "webServerFarms": "plan-", + "webSitesAppService": "app-", + "webSitesAppServiceEnvironment": "ase-", + "webSitesFunctions": "func-", + "webStaticSites": "stapp-" +} diff --git a/.github/iac/swa/infra/core/host/staticwebsite.bicep b/.github/iac/swa/infra/core/host/staticwebsite.bicep new file mode 100644 index 00000000000..70b138540d4 --- /dev/null +++ b/.github/iac/swa/infra/core/host/staticwebsite.bicep @@ -0,0 +1,33 @@ +param name string +param location string = resourceGroup().location +param tags object = {} +param sku string = 'Standard' + +@allowed([ 'None', 'SystemAssigned', 'UserAssigned' ]) +param identityType string + +@description('User assigned identity name') +param identityId string + + +resource frontend 'Microsoft.Web/staticSites@2022-09-01' = { + name: name + location: location + tags: tags + sku: { + name: sku + tier: sku + } + + properties: { + allowConfigFileUpdates: true + enterpriseGradeCdnStatus: 'Disabled' + } + + identity: { + type: identityType + userAssignedIdentities: { '${identityId}': {} } + } +} + +output name string = frontend.name diff --git a/.github/iac/swa/infra/main.bicep b/.github/iac/swa/infra/main.bicep new file mode 100644 index 00000000000..d73df42b63c --- /dev/null +++ b/.github/iac/swa/infra/main.bicep @@ -0,0 +1,63 @@ +targetScope = 'subscription' + +@minLength(1) +@maxLength(64) +@description('Name of the the environment which is used to generate a short unique hash used in all resources.') +param environmentName string + +@minLength(1) +@description('Primary location for all resources') +@allowed([ 'eastus', 'eastus2', 'westus', 'westus2']) +param location string + +param resourceGroupName string = '' + +param staticWebsiteName string = '' + +@description('Id of the user or app to assign application roles') +param principalId string = '' + +param identityResourceGroupName string = 'dapr-identities' + +var abbrs = loadJsonContent('abbreviations.json') +var resourceToken = toLower(uniqueString(subscription().id, environmentName, location)) +var tags = { 'azd-env-name': environmentName } + +// Organize resources in a resource group +resource resourceGroup 'Microsoft.Resources/resourceGroups@2021-04-01' = { + name: !empty(resourceGroupName) ? resourceGroupName : '${abbrs.resourcesResourceGroups}${environmentName}' + location: location + tags: tags +} + +resource identityResourceGroup 'Microsoft.Resources/resourceGroups@2021-04-01' existing = { + name: identityResourceGroupName +} + +// load existing user assigned identity +resource userAssignedIdentity 'Microsoft.ManagedIdentity/userAssignedIdentities@2023-01-31' existing = { + name: 'dapr-docs-swa-useridentity' + scope: identityResourceGroup +} + +// Create the Static Web App +module staticwebsite 'core/host/staticwebsite.bicep' = { + scope: resourceGroup + name: 'website' + params: { + name: !empty(staticWebsiteName) ? staticWebsiteName : '${abbrs.webStaticSites}${resourceToken}' + location: location + sku: 'Standard' + identityType: 'UserAssigned' + identityId: userAssignedIdentity.id + } + +} + +output AZURE_LOCATION string = location +output AZURE_TENANT_ID string = tenant().tenantId +output AZURE_RESOURCE_GROUP string = resourceGroup.name + +output AZURE_STATICWEBSITE_NAME string = staticwebsite.outputs.name +output IDENTITY_RESOURCE_ID string = userAssignedIdentity.id +output IDENTITY_RESOURCE_GROUP string = identityResourceGroup.name diff --git a/.github/iac/swa/infra/main.parameters.json b/.github/iac/swa/infra/main.parameters.json new file mode 100644 index 00000000000..d9c177fba14 --- /dev/null +++ b/.github/iac/swa/infra/main.parameters.json @@ -0,0 +1,24 @@ +{ + "$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#", + "contentVersion": "1.0.0.0", + "parameters": { + "environmentName": { + "value": "${AZURE_ENV_NAME}" + }, + "location": { + "value": "${AZURE_LOCATION}" + }, + "principalId": { + "value": "${AZURE_PRINCIPAL_ID}" + }, + "resourceGroupName": { + "value": "${AZURE_RESOURCE_GROUP}" + }, + "identityResourceGroup": { + "value": "${IDENTITY_RESOURCE_GROUP}" + }, + "staticWebsiteName": { + "value": "${AZURE_STATICWEBSITE_NAME}" + } + } +} diff --git a/.github/iac/swa/infra/security/lockRg.bicep b/.github/iac/swa/infra/security/lockRg.bicep new file mode 100644 index 00000000000..501615557f3 --- /dev/null +++ b/.github/iac/swa/infra/security/lockRg.bicep @@ -0,0 +1,7 @@ +resource createRgLock 'Microsoft.Authorization/locks@2016-09-01' = { + name: 'rgLock' + properties: { + level: 'do-not-delete' + notes: 'Resource group and its resources should not be deleted because it contains live OSS website.' + } +} diff --git a/.github/iac/swa/infra/security/userAssignedIdentity.bicep b/.github/iac/swa/infra/security/userAssignedIdentity.bicep new file mode 100644 index 00000000000..9a4d4410e9e --- /dev/null +++ b/.github/iac/swa/infra/security/userAssignedIdentity.bicep @@ -0,0 +1,11 @@ +param identityName string +param location string + +resource userAssignedIdentity 'Microsoft.ManagedIdentity/userAssignedIdentities@2023-01-31' = { + name: identityName + location: location +} + +output identityId string = userAssignedIdentity.id +output identityName string = userAssignedIdentity.name +output identityPrincipalId string = userAssignedIdentity.properties.principalId diff --git a/.github/iac/swa/readme.md b/.github/iac/swa/readme.md new file mode 100644 index 00000000000..dd5687bf280 --- /dev/null +++ b/.github/iac/swa/readme.md @@ -0,0 +1,60 @@ +# Dapr Static Web Apps +## dapr.docs.io + +## Summary + +This folder contains a template and infrastructure as code to recreate and reconfigure the static web app used to host docs.dapr.io. + +## Prerequisites + +1) Active Azure Subscription with `Contributor` or `Owner` access to create resources +2) [Azure Developer CLI](https://aka.ms/azd) + +## Deploy Static Web App + +1) Export any environment variables you want to override with your values using `./infra/main.parameters.json` as a reference for the variable names. e.g. + +In a new terminal: + +Bash/sh/zsh: +```bash +export AZURE_RESOURCE_GROUP=rg-dapr-docs-test +export IDENTITY_RESOURCE_GROUP=rg-my-identities +export AZURE_STATICWEBSITE_NAME=daprdocs-latest +``` + +PowerShell +```PowerShell +setx AZURE_RESOURCE_GROUP "rg-dapr-docs-test" +setx IDENTITY_RESOURCE_GROUP "rg-my-identities" +setx AZURE_STATICWEBSITE_NAME "daprdocs-latest" +``` + +This assumes you have an existing [user-assigned managed identity](https://learn.microsoft.com/entra/identity/managed-identities-azure-resources/how-manage-user-assigned-managed-identities?pivots=identity-mi-methods-azp) (see L39 in `./infra/main.bicep` to use or modify name) in a resource group that you can reference as the runtime identity of this static web app. We recommend storing this in a different resource group from your application, to keep the permissions and lifecycles separate of your identity and your web app. We also recommend narrowly limiting who has access to view, contribute or own this identity, and also only apply it to single resource scopes, not to entire resource groups or subscriptions, to avoid elevation of priviledges. + +2) Deploy using the Azure Dev CLI + +The first time, and any updates to this environment + +```bash +azd up +``` + +For subsequent environments/sites, create a side-by-side environment like this: + +```bash +azd env new +azd up +``` + +You will be prompted for the subscription and location (region) to use. The Resource Group and Static Web App will now be created and usable. Typical deployment times are only 20-60 seconds. + +## Configure the Static Web App in portal.azure.com + +1) (Optional) Grant correct minimal permissions for inbound publishing and outbound access to dependencies using the Static Web App -> Access control (IAM) blade of the portal + +2) (Optional) Map your DNS CNAME using the Static Web App -> Custom Domain blade of the portal + +## Configure your CI/CD pipeline + +You will need a rotatable token or ideally a managed identity (coming soon) for your pipeline to have Web publishing access grants to the Static Web App. Get the token from the Overview blade -> Manage Access Token command of the SWA, and store it in the vault/secret for the repo matching your Github Action (or other CI/CD pipeline)'s workflow file. One example for the current/main release of Dapr docs is [here](https://github.com/dapr/docs/blob/v1.13/.github/workflows/website-root.yml#L57). This is an elevated operation that likely needs an admin or maintainer to perform. diff --git a/.github/iac/swa/scripts/deploy.ps1 b/.github/iac/swa/scripts/deploy.ps1 new file mode 100644 index 00000000000..02ed464ebc1 --- /dev/null +++ b/.github/iac/swa/scripts/deploy.ps1 @@ -0,0 +1,32 @@ +$output = azd env get-values + +foreach ($line in $output) { + if (!($line)){ + break + } + $name = $line.Split('=')[0] + $value = $line.Split('=')[1].Trim('"') + Set-Item -Path "env:\$name" -Value $value +} + +Write-Host "Environment variables set." + +$tools = @("az", "swa", "func") + +foreach ($tool in $tools) { + if (!(Get-Command $tool -ErrorAction SilentlyContinue)) { + Write-Host "Error: $tool command line tool is not available, check pre-requisites in README.md" + exit 1 + } +} + +# az account set --subscription $env:AZURE_SUBSCRIPTION_ID +Write-Host $env:AZURE_SUBSCRIPTION_ID + +cd $env:SWA_APP_PATH +$SWA_DEPLOYMENT_TOKEN = az staticwebapp secrets list --name $env:AZURE_STATICWEBSITE_NAME --query "properties.apiKey" --output tsv +if ($SWA_DEPLOYMENT_TOKEN -ne "") { + swa deploy --env production --deployment-token $SWA_DEPLOYMENT_TOKEN +} else { + Write-Host "SWA_DEPLOYMENT_TOKEN is empty, not deployoing froentend, check if the static website is created in Azure portal." +} diff --git a/.github/iac/swa/scripts/deploy.sh b/.github/iac/swa/scripts/deploy.sh new file mode 100755 index 00000000000..b15903ba645 --- /dev/null +++ b/.github/iac/swa/scripts/deploy.sh @@ -0,0 +1,31 @@ +#!/bin/bash + +output=$(azd env get-values) + +while IFS= read -r line; do + name=$(echo $line | cut -d'=' -f1) + value=$(echo $line | cut -d'=' -f2 | sed 's/^"\|"$//g') + export $name=$value + echo "$name=$value" +done <<<$output + +echo "Environment variables set." + +commands=("az" "swa" "func") + +for cmd in "${commands[@]}"; do + if ! command -v "$cmd" &>/dev/null; then + echo "Error: $cmd command is not available, check pre-requisites in README.md" + exit 1 + fi +done + +# az account set --subscription $AZURE_SUBSCRIPTION_ID + +cd $SWA_APP_PATH +SWA_DEPLOYMENT_TOKEN=$(az staticwebapp secrets list --name $AZURE_STATICWEBSITE_NAME --query "properties.apiKey" --output tsv) +if [[ -n $SWA_DEPLOYMENT_TOKEN ]]; then + swa deploy --env production --deployment-token $SWA_DEPLOYMENT_TOKEN +else + echo "SWA_DEPLOYMENT_TOKEN is empty, not deployoing froentend, check if the static website is created in Azure portal." +fi