🎉 75% of content is free forever — Unlock Premium from $10/mo →
CW
NEWSLIVESearch All Content
đŸ’ŧ Servicesâ„šī¸ Aboutâœ‰ī¸ ContactView Pricing Plansfrom $10

Azure Key Vault for Data Pipelines: Secrets, Keys, Rotation

Azure Data EngineeringKey Vault⭐ Premium
Azure Data Engineering

Credentials belong in a vault, not a pipeline parameter

12 min read📘Intermediate

Prerequisites

  • !Azure managed identities and service principals
  • !Azure Data Factory linked service concepts
  • !The difference between encryption at rest and in transit

What You'll Learn

  • 1Choose between access policies and RBAC for vault permissions
  • 2Wire ADF and Databricks to Key Vault without embedding secrets
  • 3Automate secret and key rotation on a schedule
  • 4Harden a vault with network rules, purge protection, and diagnostics

Three object types, three different jobs

Key Vault stores three kinds of objects, and conflating them is the most common design error. Secrets are opaque string values: connection strings, API keys, SAS tokens, passwords. Keys are cryptographic material that the vault can use to perform operations such as encrypt, decrypt, sign, and verify without the key ever leaving the vault boundary; this is what enables customer-managed keys for storage encryption. Certificates are X.509 credentials that the vault can issue and renew, which matters for TLS and code signing. A data engineer reaches for secrets ninety percent of the time, but the architectural win comes from knowing when to push work into the vault with keys instead of pulling the material out.

The distinction has a security consequence. When your application retrieves a secret, the plaintext value transits your process memory and is only as protected as that process. When your application asks the vault to decrypt a value with a key, the plaintext key never leaves the Hardware Security Module on Premium vaults, so a compromised application process still cannot exfiltrate the key material. For compliance regimes that mandate FIPS 140-2 Level 2, that difference is not academic.

python
from datetime import datetime, timedelta, timezone
from azure.identity import DefaultAzureCredential
from azure.keyvault.secrets import SecretClient
from azure.keyvault.keys import KeyClient
from azure.keyvault.keys.crypto import CryptographyClient, EncryptionAlgorithm

VAULT_URL = "https://kv-dataeng-prod.vault.azure.net/"
credential = DefaultAzureCredential()
secret_client = SecretClient(vault_url=VAULT_URL, credential=credential)
key_client = KeyClient(vault_url=VAULT_URL, credential=credential)

def store_adls_secret(value: str, days_valid: int = 90) -> None:
    """Store a secret with an explicit expiry so rotation cannot be forgotten."""
    secret_client.set_secret(
        name="adls-gen2-access-key",
        value=value,
        expires_on=datetime.now(timezone.utc) + timedelta(days=days_valid),
    )
    print("secret stored with expiry")

def encrypt_with_vault_key(plaintext: bytes) -> bytes:
    """Encrypt using a vault-held key; the key never leaves the HSM."""
    key = key_client.get_key("cmk-adls-gen2")
    crypto = CryptographyClient(key, credential=credential)
    result = crypto.encrypt(EncryptionAlgorithm.RSA_OAEP, plaintext)
    return result.ciphertext

def rotate_secret(new_value: str) -> None:
    """Overwrite the current version; previous versions remain for rollback."""
    secret_client.set_secret(name="adls-gen2-access-key", value=new_value)
    print("secret rotated; new version is now current")

Access policies versus RBAC: pick one and commit

Key Vault supports two permission models, and they cannot both be authoritative on the same vault. The legacy access policy model grants permissions per vault to an identity, covering operations like get, list, set, delete, and recover. The newer RBAC model uses Azure role assignments scoped to the vault or its resource group, which means permissions inherit the same mental model and tooling as the rest of Azure, and you can grant roles like Key Vault Secrets User without inventing a bespoke policy set. Microsoft's guidance is to use RBAC for all new vaults; access policy mode remains for legacy deployments that have not migrated.

The practical difference for a data engineering team shows up in offboarding. With RBAC, removing a user from the Key Vault Secrets Officer role is a single role assignment removal that takes effect immediately and is auditable in the same activity log as every other resource change. With access policies, the permission lives only on the vault, is easy to forget during an offboarding checklist, and drifts out of sync with the organization's real access structure.

OperationAccess policy permissionRBAC roleNotes
Read a secret valuegetKey Vault Secrets UserMost common grant for pipelines
List secret nameslistKey Vault Secrets ReceiverNeeded for discovery UIs
Write or rotate a secretsetKey Vault Secrets OfficerGrant to rotation automation only
Delete and recoverdelete, recoverKey Vault ContributorShould require elevated approval
Use a key to encryptwrap keyKey Vault Crypto UserKey operations, not secret reads
Perform key managementcreate, updateKey Vault Crypto OfficerCreating and rotating key material

Wiring Data Factory and Databricks without hardcoding

The pattern that satisfies auditors is consistent across tools: the compute identity authenticates to Key Vault with a managed identity, the linked service references the secret by name, and no credential exists anywhere in source control or pipeline parameters. In ADF, the linked service's secret field is typed as AzureKeyVaultSecret with a reference to a Key Vault linked service, which is itself authenticated by the factory's managed identity. In Databricks, secret scopes backed by Key Vault let notebooks read the same values without the workspace ever persisting them.

{
  "name": "ls_adls_gen2_keyvault",
  "properties": {
    "type": "AzureBlobFS",
    "typeProperties": {
      "url": "https://stdatalake001.dfs.core.windows.net",
      "accountKey": {
        "type": "AzureKeyVaultSecret",
        "store": {
          "referenceName": "akv_dataeng_keyvault",
          "type": "LinkedServiceReference"
        },
        "secretName": "adls-gen2-access-key"
      }
    },
    "connectVia": {
      "referenceName": "AutoResolveIntegrationRuntime",
      "type": "IntegrationRuntimeReference"
    }
  }
}

Once this wiring is in place, rotating the secret in Key Vault is the only step required; no pipeline redeploy, no parameter file edit, and no secret in the repository history. That is the entire argument for doing this work up front, and it is the argument auditors respond to.

Rotation automation that survives real operations

Automatic rotation has two halves: generating and storing the new value, and updating whatever system consumes it. For storage account keys, Azure can rotate the account key itself, and Key Vault's rotation policies can track the schedule. For third-party API keys, you write a small function on a timer trigger that calls the provider, stores the new value, and verifies the old one is still honored during the overlap window. The overlap matters; switching instantaneously and discovering the provider's propagation delay is a classic 3 a.m. incident.

python
import azure.functions as func
from azure.identity import ManagedIdentityCredential
from azure.keyvault.secrets import SecretClient
from datetime import datetime, timedelta, timezone

app = func.FunctionApp()
VAULT_URL = "https://kv-dataeng-prod.vault.azure.net/"

@app.timer_trigger(
    schedule="0 0 2 * * *",  # daily at 02:00 UTC
    arg_name="timer",
)
def rotate_vendor_api_key(timer: func.TimerRequest) -> None:
    if timer.past_due:
        print("timer is past due, skipping this run")
        return

    credential = ManagedIdentityCredential()
    client = SecretClient(vault_url=VAULT_URL, credential=credential)

    new_value = generate_vendor_key()          # call the vendor API here
    client.set_secret(
        name="vendor-api-key",
        value=new_value,
        expires_on=datetime.now(timezone.utc) + timedelta(days=90),
    )

    # Keep the previous version readable so consumers can retry during propagation
    versions = list(client.list_secret_versions("vendor-api-key"))
    print(f"rotated; {len(versions)} versions exist, newest is current")

Hardening the vault itself

A vault with a leaky secret policy is one problem; a vault that anyone on the internet can reach is another. Network rules let you default-deny all access and allow only specified subnets, private endpoints, or trusted Microsoft services. Purge protection and soft delete are effectively mandatory: soft delete retains deleted objects for the retention period so an accidental delete is recoverable, and purge protection prevents even an administrator from permanently destroying them during that window. Diagnostics to a Log Analytics workspace give you the audit trail that answers who read which secret and when, which is the question every incident review asks.

# Lock the vault down to private access and enable recoverability
az keyvault update \
  --name kv-dataeng-prod \
  --default-action Deny \
  --bypass AzureServices \
  --enable-purge-protection true \
  --enable-rbac-authorization true

# Send audit events to Log Analytics for retention and alerting
az monitor diagnostic-settings create \
  --name "kv-audit-to-law" \
  --resource "/subscriptions/SUB/resourceGroups/RG/providers/Microsoft.KeyVault/vaults/kv-dataeng-prod" \
  --workspace "/subscriptions/SUB/resourceGroups/RG/providers/Microsoft.OperationalInsights/workspaces/law-dataeng" \
  --logs '[{"category":"AuditEvent","enabled":true},{"category":"AzurePolicyEvaluationDetails","enabled":false}]'

# Grant a pipeline identity read access through RBAC, not an access policy
az role assignment create \
  --assignee-object-id "PRINCIPAL-OBJECT-ID" \
  --role "Key Vault Secrets User" \
  --scope "/subscriptions/SUB/resourceGroups/RG/providers/Microsoft.KeyVault/vaults/kv-dataeng-prod"

Secrets in Databricks, Synapse, and CI pipelines

The Key Vault habit has to extend past ADF or it becomes a hole with a clean front door. Databricks secret scopes backed by Key Vault let notebooks and jobs read credentials with dbutils.secrets.get, and the values never appear in notebook output or workspace files, which matters because notebooks are frequently shared and exported. In Synapse, linked services reference Key Vault secrets the same way ADF does, so a warehouse that loads from a REST API authenticates without the key living in the workspace definition. In Azure DevOps, variable groups linked to the vault inject values at run time, keeping pull request diffs free of credential noise and keeping the repository history clean even when someone inevitably inspects it during an incident.

The unifying principle is that the secret should have exactly one home, and every consumer should reach it through an identity rather than a copy. When you find a secret pasted into a pipeline parameter, a notebook cell, or a wiki page, treat it as an incident-grade finding: rotate it immediately, then fix the reference, because the leak has already happened and rotation is the only thing that bounds it. Inventory audits that scan repositories and pipeline definitions for high-entropy strings are the automated version of this discipline, and they are worth running on a schedule rather than only before compliance reviews.

Common Mistakes

Storing a storage account key as a literal in an ADF linked service parameter

Fix: Reference the secret through an AzureKeyVaultSecret field and a Key Vault linked service so the value never enters source control

Running the vault in access policy mode on a new deployment

Fix: Create new vaults with RBAC authorization enabled; migrate legacy vaults when practical so permissions inherit standard Azure role management

Rotating a secret instantaneously with no overlap window

Fix: Keep the previous version available during the provider's propagation window and verify the new value works before retiring the old one

Leaving purge protection disabled because it complicates teardown scripts

Fix: Enable purge protection everywhere except ephemeral sandbox vaults; the retention window is what turns a malicious or accidental purge into a recoverable event

Best Practices

  • Use managed identities for every vault-authenticating workload; never a client secret in the pipeline definition
  • Set secret expiry dates at write time so rotation cannot silently lapse
  • Default-deny network access and allow only private endpoints and required subnets
  • Stream vault diagnostics to Log Analytics and alert on unusual read volumes
  • Separate production and non-production vaults so a sandbox compromise cannot reach production credentials

Interview Questions

Q1: What is the difference between Key Vault access policies and RBAC?

Access policies are a legacy per-vault permission model with operations like get, set, and delete. RBAC uses standard Azure role assignments scoped to the vault or its resource group, giving consistent inheritance, auditing, and offboarding across all Azure resources. RBAC is the recommended model for new vaults.

Q2: How do you implement secret rotation for a pipeline that reads a vendor API key?

Use a timer-triggered function that calls the vendor to mint a new key, writes it to Key Vault with an expiry date, and leaves the previous version readable during the propagation window. Consumers read by secret name and pick up the new version automatically, so no pipeline redeploy is needed.

Q3: Why would you use a Key Vault key instead of a secret for storage encryption?

Keys let the vault perform cryptographic operations without the material leaving the HSM, which limits blast radius if an application process is compromised and satisfies FIPS 140-2 Level 2 requirements on Premium vaults. Secrets expose plaintext to the reading process by design.

Q4: How do you restrict who can read secrets from a production vault?

Combine RBAC role assignments scoped to the vault, network rules default-deny with private endpoints or approved subnets, and diagnostic logging to Log Analytics so reads are auditable. Soft delete and purge protection guard against destructive actions.

Key Takeaways

  • Secrets, keys, and certificates solve different problems; push crypto into the vault with keys when the workload allows it
  • RBAC on Key Vault aligns offboarding and auditing with the rest of Azure and is the default for new vaults
  • ADF linked services reference secrets by name through a Key Vault linked service, so rotation needs no redeploy
  • Rotation automation must include an overlap window, not an instantaneous switch
  • Network default-deny, purge protection, and diagnostics are the three hardening controls auditors check first
🔒

Premium Content

Azure Key Vault for Data Pipelines: Secrets, Keys, Rotation

You've previewed the first section. Unlock this full lesson and 900+ advanced tutorials with a Premium plan.

đŸŽ¯End-to-end Projects
đŸ’ŧInterview Prep
📜Certificates
🤝Community Access

Already a member? Log in

CW

ChatWhole Learn Editorial Team

Written by experienced data scientists, software engineers, and educators. All content is reviewed by industry professionals to ensure accuracy and relevance.

Last reviewed: 2026-10-13

—
☆☆☆☆☆
0 ratings

Rate & Feedback

Advertisement