How to update a Secret in Azure Key Vault only if changed in ARM templates or check if it exists

Poul K. Sørensen

I have a production keyvault that keeps a reference of secrets that projects can use, but only if deployed using ARM templates such secrets are not handled by people copy pasting them.

When a new project starts, as part of its deployment script, it will create its own keyvault.

I want to be able to run the templates/scripts as part of CI/CD. And this will today result in the same secret having a new version at each run, even though the value did not change.

How to make it only update the keyvault value when the master vault is updated.

Poul K. Sørensen

In my deployment.sh script I use the following technique.

SendGridUriWithVersion=$((az group deployment create ... assume that the secret exists ... || az group deployment create ... assume that the secret exists ... ) | jq -r '.properties.outputs.secretUriWithVersion.value')

and it works because in the template there is a parameter, if set, that will retrieve the secret and compare it with the new value and only insert if difference. The original problem is that the deployment fails if the secret is not already set (this happens for the first deployment etc).

But then due to Unix ||, the same script is run again without the parameter set and it will use a condition to not try to get the old value and therefore run successful.

Here are the example in dept:

      SecretName="Sendgrid"
      SourceSecretName="Sendgrid"
      SourceVaultName="io-board"
      SourceResourceGroup="io-board" 
      SendGridUriWithVersion=$((az group deployment create -n ${SecretName}-secret -g $(prefix)-$(projectName)-$(projectEnv) --template-uri https://management.dotnetdevops.org/providers/DotNetDevOps.AzureTemplates/templates/KeyVaults/${keyVaultName}/secrets/${SecretName}?sourced=true --parameters sourceVault=${SourceVaultName} sourceResourceGroup=${SourceResourceGroup} sourceSecretName=${SourceSecretName} update=true || az group deployment create -n ${SecretName}-secret -g $(prefix)-$(projectName)-$(projectEnv) --template-uri https://management.dotnetdevops.org/providers/DotNetDevOps.AzureTemplates/templates/KeyVaults/${keyVaultName}/secrets/${SecretName}?sourced=true --parameters sourceVault=${SourceVaultName} sourceResourceGroup=${SourceResourceGroup} sourceSecretName=${SourceSecretName}) | jq -r '.properties.outputs.secretUriWithVersion.value')

The https://management.dotnetdevops.org/providers/DotNetDevOps.AzureTemplates/templates/KeyVaults/{keyvaultName}/secrets/{secretName}?sourced=true returns a template

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "keyVaultName": {
      "type": "string",
      "defaultValue": "io-board-data-ingest-dev"
    },
    "secretName": {
      "type": "string",
      "metadata": {
        "description": "Name of the secret to store in the vault"
      },
      "defaultValue": "DataStorage"
    },
    "sourceVaultSubscription": {
      "type": "string",
      "defaultValue": "[subscription().subscriptionId]"
    },
    "sourceVault": {
      "type": "string",
      "defaultValue": "[subscription().subscriptionId]"
    },
    "sourceResourceGroup": {
      "type": "string",
      "defaultValue": "[resourceGroup().name]"
    },
    "sourceSecretName": {
      "type": "string"
    },
    "update": {
      "type": "bool",
      "defaultValue": false
    }
  },
  "variables": {
    "empty": {
      "value": ""
    },
    "test": {
      "reference": {
        "keyVault": {
          "id": "[resourceId(subscription().subscriptionId, resourceGroup().name, 'Microsoft.KeyVault/vaults', parameters('keyVaultName'))]"
        },
        "secretName": "[parameters('secretName')]"
      }
    }
  },
  "resources": [
    {
      "apiVersion": "2018-05-01",
      "name": "AddLinkedSecret",
      "type": "Microsoft.Resources/deployments",
      "properties": {
        "mode": "Incremental",
        "templateLink": {
          "uri": "[concat('https://management.dotnetdevops.org/providers/DotNetDevOps.AzureTemplates/templates/KeyVaults/',parameters('keyVaultName'),'/secrets/',parameters('secretName'))]",
          "contentVersion": "1.0.0.0"
        },
        "parameters": {
          "existingValue": "[if(parameters('update'),variables('test'),variables('empty'))]",
          "secretValue": {
            "reference": {
              "keyVault": {
                "id": "[resourceId(parameters('sourceVaultSubscription'), parameters('sourceResourceGroup'), 'Microsoft.KeyVault/vaults', parameters('sourceVault'))]"
              },
              "secretName": "[parameters('sourceSecretName')]"
            }
          }
        }
      }
    }
  ],
  "outputs": {
    "secretUriWithVersion": {
      "type": "string",
      "value": "[reference('AddLinkedSecret').outputs.secretUriWithVersion.value]"
    }
  }
}

and that template has a nested call to https://management.dotnetdevops.org/providers/DotNetDevOps.AzureTemplates/templates/KeyVaults/{keyvaultName}/secrets/{secretName} which gives the one with the condition

{
  "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
  "contentVersion": "1.0.0.0",
  "parameters": {
    "keyVaultName": {
      "type": "string",
      "defaultValue": "io-board-data-ingest-dev",
      "metadata": {
        "description": "Name of the existing vault"
      }
    },
    "secretName": {
      "type": "string",
      "metadata": {
        "description": "Name of the secret to store in the vault"
      },
      "defaultValue": "DataStorage"
    },
    "secretValue": {
      "type": "securestring",
      "metadata": {
        "description": "Value of the secret to store in the vault"
      }
    },
    "existingValue": {
      "type": "securestring",
      "defaultValue": ""
    }
  },
  "variables": {},
  "resources": [
    {
      "type": "Microsoft.KeyVault/vaults/secrets",
      "condition": "[not(equals(parameters('existingValue'),parameters('secretValue')))]",
      "apiVersion": "2015-06-01",
      "name": "[concat(parameters('keyVaultName'), '/', parameters('secretName'))]",
      "properties": {
        "value": "[parameters('secretValue')]"
      }
    }
  ],
  "outputs": {
    "secretUriWithVersion": {
      "type": "string",
      "value": "[reference(resourceId(resourceGroup().name, 'Microsoft.KeyVault/vaults/secrets', parameters('keyVaultName'), parameters('secretName')), '2015-06-01').secretUriWithVersion]"
    }
  }
}

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How to check for specific object key and update if exists

Cannot set secret value in Azure Key Vault

How do I update value of my Secret created in Azure Key Vault using .Net SDK

Terraform with Azure Key Vault to get secret value

How to check if secret is in Azure Key Vault

Cannot access azure key vault secret with python

How to write a secret to azure key vault from Azure DevOps pipeline?

How to clear expiration date from Azure Key Vault secret?

How to audit Secret key access in Key Vault

Store key and secret in Azure key-vault

Azure DevOps pipeline for deploying only changed arm templates

How to extract Secret key from Azure key vault in Azure Function App on Nodejs stack

Search secret in Azure key vault

Azure: store resource's secret in Key Vault created by ARM template

How do I use Azure Key Vault secret in linked template

Deploy azure key vault secret using arm template gives error

Azure ARM template - check for existing Key Vault access policies

Access Azure Key Vault secret in Azure Function

Access Azure Key Vault secret without a SecretVersion

How to check if a specific Azure ARM Resource exists or not and if not exists create it with PowerShell

How to retrieve Secret from Azure Key Vault using DefaultAzureCredential

Azure Key Vault access policies and Managed Identities (ARM templates)

Unable to obtain azure key vault secret in ansible

Azure Retrieve Secret from key vault

Terraform: update resources only when Vault secret data has changed

how to authenticate azure key vault using client id and secret?

Reading Azure Key Vault secret into ARM template via parameter file

How to manage Azure Key Vault with secrets without values in ARM template?

How to set tags for Secret in Azure Key Vault using C#

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    pump.io port in URL

  3. 3

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  4. 4

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  5. 5

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  8. 8

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

  9. 9

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  10. 10

    How to remove the extra space from right in a webview?

  11. 11

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  12. 12

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  13. 13

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  14. 14

    java.lang.NullPointerException: Cannot read the array length because "<local3>" is null

  15. 15

    How to use merge windows unallocated space into Ubuntu using GParted?

  16. 16

    flutter: dropdown item programmatically unselect problem

  17. 17

    Pandas - check if dataframe has negative value in any column

  18. 18

    Nuget add packages gives access denied errors

  19. 19

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  20. 20

    Generate random UUIDv4 with Elm

  21. 21

    Client secret not provided in request error with Keycloak

HotTag

Archive