KeyVault
I’m always looking for ways to simply automate deployments, so I don’t have to hard code, or repeat myself. This blog is looking at Key Vault deployments, and its use.
Parameters
For Key Vaults I don’t like to specify the normal key/value pairs, as it would mean that I have to specify the name of the secret within the deployment script. The obvious draw back here is, as the code evolves and the secret changes then you would need to update both the parameters plus the deployment script. So first off in the parameters file put the secrets into an array.
"para_kvSecretsObject": {
"value": {
"secrets": [
{
"secretName": "applicationuser",
"secretValue": "OVERWRITTEN BY VSTS"
},
{
"secretName": "AnotherSecret",
"secretValue": "OVERWRITTEN BY VSTS"
}
]
}
Straight away you can see that the actual secret is injected from the CI tool, this is so you can inject a different secret depending on the environment. Putting the secrets into an array in this way means that we can cycle through the array in the deployment script without actually referring to the secret itself, only using the array index.
Load Secrets
Loading of secrets is normally achieved via the actual KeyVault deployment specifying each secret in turn, but as our secrets are specified as part of an array, we will need to apply them in a slightly different way. At the resource level we create a new feature which has a type of Microsoft.KeyVault/vaults/secrets. In the following code block the lines to look out for are the Copy/Name and Value properties.
- The Copy property looks at the array and determines the number of items we need to process.
- The Name property set the secret name to the ‘secrectName’ value in the array and it is indexed by the copyIndex() parameter
- The Value is specified in the same way as the Name just using the secretValue array name.
One important line which is often overlooked is the DependsOn property. Each resource in the deployment file can be applied by Azure in parallel so by specifying the DependsOn property stops the deployment until the dependant resource exists.
{
"apiVersion": "2015-06-01",
"copy": {
"name": "secretsCopy",
"count": "[length(parameters('para_kvSecretsObject').secrets)]"
},
"dependsOn": [
"[concat('Microsoft.KeyVault/vaults/', variables('var_kv_name'))]"
],
"name": "[concat(variables('var_kv_name'), '/', parameters('para_kvSecretsObject').secrets[copyIndex()].secretName)]",
"properties": {
"value": "[parameters('para_kvSecretsObject').secrets[copyIndex()].secretValue]"
},
"tags": {
"displayName": "Key Vault Secrets"
},
"type": "Microsoft.KeyVault/vaults/secrets"
}
Accessing the Key Vault
A Key Vault cannot exist on its own, when it is deployed it needs the service principal, at the moment the service principal can only be obtained from an AD associated application, such as a web app/api app or function.