Use KeyVault with CLI

Written by

Terms:

Keys:

let’s say you need to encrypt sensitive user data (like SSN) before storing it in your database to ensure confidentiality. You would go for keys in Azure Key Vault. This key would be used to encrypt and decrypt the user data and you NO need to worry about the safety of these keys.

Secrets:

Say, your web application needs to connect to an external API that requires an API key for authentication. You would store this API key as a secret in Azure Key Vault, allowing your application to securely retrieve it when making API requests. whenever the vendor changes the key, you can update it in Secrets.

Role assignment

Try without the access

Error

Grant access to user

Read value from CLI

az account set --subscription your-subscription
az keyvault secret show --vault-name upidev --name docker-container-pass
{
  "attributes": {
    "created": "2025-01-08T12:31:44+00:00",
    "enabled": true,
    "expires": null,
    "notBefore": null,
    "recoverableDays": 90,
    "recoveryLevel": "Recoverable+Purgeable",
    "updated": "2025-01-08T12:31:44+00:00"
  },
  "contentType": null,
  "id": "https://upidev.vault.azure.net/secrets/docker-container-pass/f19a55dab31f485c8ef320f188593c58",
  "kid": null,
  "managed": null,
  "name": "docker-container-pass",
  "tags": {},
  "value": "secret"
}

Get only the value

az keyvault secret show --vault-name upidev --name docker-container-pass --query value

Use shell command to extract secret value using jq

Create new file setup.sh

Give execution permission

chmod a+x setup.sh
secret="$(az keyvault secret show --vault-name upidev --name docker-container-pass --query value)"
echo $secret
echo "$secret" | jq -r

Use a key to encrypt/decrypt sensitive information

Add the following lines to the setup.sh file

# Use a key to encrypt a file and decrypt the string

# Read file content
file_content=$(cat coca-cola-ingredients.txt)
echo $file_content

# Encrypt file content
encrypted_content=$(echo -n "$file_content" | base64 | az keyvault key encrypt --vault-name upidev --name top-secret-key --algorithm RSA-OAEP --value @- --query "result")
echo $encrypted_content
echo "$encrypted_content" > encrypted-coca-cola-ingredients.txt

# Decrypt file content
encrypted_content=$(cat ./encrypted-coca-cola-ingredients.txt)
decrypted_content=$(az keyvault key decrypt --vault-name upidev --name top-secret-key --algorithm RSA-OAEP --value "$encrypted_content" --query "result" -o tsv | base64 -d)

echo $decrypted_content