Search code examples
azureazure-devopsazure-web-app-serviceazure-rm-template

Get Azure KeyVault Secrets from the KeyVault to an App Service using ARM Templates


In the Microsoft KeyVault resource I have a secret:

        {
          "type": "secrets",
          "apiVersion": "2016-10-01",
          "name": "mongodb",
          "location": "[resourceGroup().location]",
          "dependsOn": [
            "[resourceId('Microsoft.KeyVault/vaults', variables('vault').name)]"
          ],
          "properties": {
            "attributes": {
              "enabled": true
            },
            "value": "[listConnectionStrings(resourceId('Microsoft.DocumentDB/databaseAccounts', parameters('cosmosAccountName')), '2019-12-12').connectionStrings[0].connectionString]"
          }
        }

I want to extract this value and store it in a key-value pair in an App Service.

        "siteConfig": {
          "appSettings": [
            {
              "name": "COSMOS_CONNECTION_STRING",
              "value": ""
            }
          ]
        }

They are in the same resource group.

How do I get the value out of the keyvault?


Solution

  • First you need to give the App Service permission to read the keys from the KeyVault, which is done by creating an Access Policy.

    This is done by:

     {
          "type": "Microsoft.KeyVault/vaults/accessPolicies",
          "apiVersion": "2016-10-01",
          "name": "[concat( variables('vault').name, '/replace')]",
          "dependsOn": [
            "[resourceId('Microsoft.KeyVault/vaults', variables('vault').name)]",
          ],
          "properties": {
            "accessPolicies": [
              {
                "tenantId": "[subscription().tenantId]",
                "objectId": "[reference(resourceId('Microsoft.Web/sites', variables('AppService').name), '2016-08-01', 'Full').identity.principalId]",
                "permissions": {
                  "keys": [
                  ],
                  "secrets": [
                    "Get",
                    "List"
                  ],
                  "certificates": []
                }
              }
            ]
          }
        }
    

    Then you can access the secret key by:

    @Microsoft.KeyVault(VaultName=myvault;SecretName=mysecret)
    

    Where myvault is the name of your vault and mysecret is the name of your secret key

    This will create a KeyVault Reference.