Dev.to Security πŸ” Cybersecurity πŸ‘ 0 πŸ“– 5 min read

Azure DevOps Crash Course (Part 6): Secrets and Settings with Variable Groups and Key Vault

A few years ago I reviewed a pull request that had a production database password sitting right there in appsettings.json. The developer was not careless, they were just in a hurry. The password had been in the Git histo

Azure DevOps Crash Course (Part 6): Secrets and Settings with Variable Groups and Key Vault

A few years ago I reviewed a pull request that had a production database password sitting right there in appsettings.json. The developer was not careless, they were just in a hurry. The password had been in the Git history for two weeks before anyone noticed. We had to rotate it, and of course it was used in four other places.

Since then I have one simple rule: if it is a secret, it never goes in Git, and it never goes in YAML.

In Part 5 we deployed the Todo API to Dev and Prod. Today we give it real configuration: normal settings that change per environment, and real secrets that stay secret. We will use two tools for that: Variable Groups and Azure Key Vault.

Where each setting should live

Where settings live: appsettings, variable group, Key Vault, App Service

  • appsettings.json (in Git): safe defaults only. Things like log levels or a friendly app name.
  • Variable groups (in Azure DevOps): values that are different per environment, like a feature flag or a URL.
  • Azure Key Vault: real secrets. Passwords, API keys, connection strings.
  • App Service app settings: where the pipeline puts the final values so the app can read them.

ASP.NET Core reads all of these through the same IConfiguration, so your code does not care where a value came from. That is the nice part.

Step 1: Read some configuration in the API

Add a default value to src/TodoApi.Api/appsettings.json:

{
  "Logging": {
    "LogLevel": {
      "Default": "Information",
      "Microsoft.AspNetCore": "Warning"
    }
  },
  "AllowedHosts": "*",
  "Greeting": "Hello from my laptop"
}

A quick word of warning from experience: a missing comma or an extra bracket in this file will crash your app on startup, and the error is not always obvious in the cloud logs. When I edit config by hand, I paste it into a JSON parser first to make sure it is valid. It saves a failed deployment and a confused half hour.

Now add an endpoint in Program.cs, just before app.Run();:

app.MapGet("/hello", (IConfiguration config) =>
{
    var greeting = config["Greeting"];
    var hasApiKey = !string.IsNullOrEmpty(config["ApiKey"]);
    return new { greeting, hasApiKey };
});

Notice we never return the API key itself, only whether it exists. Never print secrets, not even in a test endpoint.

Step 2: Create a variable group for each environment

  1. Go to Pipelines > Library and click + Variable group.
  2. Name it todoapi-dev.
  3. Add a variable Greeting with the value Hello from Dev.
  4. Save.
  5. Do the same for todoapi-prod with Hello from Prod.

Now open each group and check Pipeline permissions. Only allow your TodoApi pipeline. Microsoft explains why this matters: anyone who can edit a pipeline could otherwise read the values. Details are here: Manage variable groups.

Step 3: Put the real secret in Azure Key Vault

In the Azure Cloud Shell:

az keyvault create --name kv-todoapi-yourname --resource-group rg-todoapi --location canadacentral

Then open the vault in the Azure portal, go to Secrets, click Generate/Import, and add a secret named ApiKey with any value you like.

If the portal says you are not authorized to create secrets, your vault uses Azure role-based access. Give yourself the Key Vault Secrets Officer role on the vault under Access control (IAM), wait a minute, and try again.

Next, the pipeline needs permission to read secrets. The identity behind your azure-todoapi service connection needs read access to secrets:

  • If your vault uses Azure roles: give it the Key Vault Secrets User role.
  • If your vault uses access policies: give it Get and List on secrets.

You can find the identity by opening the service connection in Project settings > Service connections and clicking Manage service connection roles or Manage App registration.

Step 4: Link Key Vault to the variable group

  1. Open the todoapi-prod variable group.
  2. Turn on Link secrets from an Azure key vault as variables.
  3. Pick the azure-todoapi service connection and your kv-todoapi-yourname vault.
  4. Click + Add and select ApiKey.
  5. Save.

Now ApiKey is available as a pipeline variable, but its value never leaves Key Vault until the moment the pipeline needs it. If you rotate the secret in Key Vault, the next run picks up the new value automatically.

There is also an AzureKeyVault@2 task if you prefer to fetch secrets inside the pipeline itself. Microsoft covers both ways here: Use Azure Key Vault secrets in Azure Pipelines.

Step 5: Use the values in the pipeline

Update the Dev and Prod stages from Part 5. Add the variable group at the stage level and pass the values to the web app as app settings:

  - stage: Dev
    dependsOn: Build
    variables:
      - group: todoapi-dev
    jobs:
      - deployment: DeployDev
        pool:
          vmImage: ubuntu-latest
        environment: todoapi-dev
        strategy:
          runOnce:
            deploy:
              steps:
                - task: AzureWebApp@1
                  inputs:
                    azureSubscription: azure-todoapi
                    appType: webAppLinux
                    appName: todoapi-yourname-dev
                    package: $(Pipeline.Workspace)/drop/**/*.zip
                    appSettings: '-Greeting "$(Greeting)"'

  - stage: Prod
    dependsOn: Dev
    variables:
      - group: todoapi-prod
    jobs:
      - deployment: DeployProd
        pool:
          vmImage: ubuntu-latest
        environment: todoapi-prod
        strategy:
          runOnce:
            deploy:
              steps:
                - task: AzureWebApp@1
                  inputs:
                    azureSubscription: azure-todoapi
                    appType: webAppLinux
                    appName: todoapi-yourname-prod
                    package: $(Pipeline.Workspace)/drop/**/*.zip
                    appSettings: '-Greeting "$(Greeting)" -ApiKey "$(ApiKey)"'

A few things I learned the hard way:

  • Secrets are masked in logs. If you try to print $(ApiKey), you will see ***. That is a feature.
  • Secrets are not automatically available to scripts. You pass them as task inputs, like we did with appSettings. Microsoft explains the rules here: Set secret variables.
  • Nested settings use double underscores. If you have ConnectionStrings:Default in your config, the app setting name is ConnectionStrings__Default. This works on Linux and Windows.

Step 6: Deploy and check

Push on a branch, open a pull request, merge, and approve Prod when it asks. Then open:

  • https://todoapi-yourname-dev.azurewebsites.net/hello and you should see "greeting": "Hello from Dev" and "hasApiKey": false.
  • https://todoapi-yourname-prod.azurewebsites.net/hello and you should see "greeting": "Hello from Prod" and "hasApiKey": true.

Same code, same zip, different configuration. That is exactly what we want.

Quick checklist for secrets

  • No secrets in appsettings.json, appsettings.Development.json or YAML
  • Use dotnet user-secrets for secrets on your own machine
  • Real secrets in Key Vault, linked through a variable group
  • Variable groups only allowed for the pipelines that need them
  • Never print a secret, not even "just to check"

Your homework

  • Add the /hello endpoint and the Greeting default
  • Create the two variable groups
  • Create a Key Vault, add ApiKey, and link it to todoapi-prod
  • Deploy and compare /hello on Dev and Prod

Coming up next

So far App Service runs our code directly. In Part 7 we put the Todo API in a Docker container, push it to Azure Container Registry, and deploy the container instead. Same pipeline ideas, new packaging.

Have you ever found a password in a Git repo? You do not have to say whose it was.

πŸ“° Read the original article on Dev.to Security

Originally published by Dev.to Security. Aggregated on AIWithGhost for educational purposes β€” full credit and traffic to the original publisher.