Edit

Tutorial: Use Azure Key Vault with a virtual machine in JavaScript

Azure Key Vault helps you protect keys, secrets, and certificates, such as API keys and database connection strings.

In this tutorial, you set up a Node.js application to read information from Azure Key Vault by using a managed identity for Azure resources. You learn how to:

  • Create a key vault
  • Store a secret in Key Vault
  • Create an Azure Linux virtual machine
  • Enable a managed identity for the virtual machine
  • Grant the required permissions for the console application to read data from Key Vault
  • Retrieve a secret from Key Vault

Before you begin, read Key Vault basic concepts.

If you don't have an Azure subscription, create a free account.

Prerequisites

For Windows, Mac, and Linux:

  • Git
  • A current version of the Azure CLI. Run az --version to check the installed version.

Sign in to Azure

Sign in to Azure with the Azure CLI:

az login

Create a resource group and key vault

This quickstart uses a precreated Azure key vault. You can create a key vault by following the steps in these quickstarts:

Alternatively, you can run these Azure CLI commands.

Important

Each key vault must have a unique name. Replace <vault-name> with the name of your key vault in the following examples.

az group create --name "myResourceGroup" -l "EastUS"

az keyvault create --name "<vault-name>" -g "myResourceGroup" --enable-rbac-authorization true

Populate your key vault with a secret

Let's create a secret called mySecret, with a value of Success!. A secret might be a password, a SQL connection string, or any other information that you need to keep both secure and available to your application.

To add a secret to your newly created key vault, use the following command:

az keyvault secret set --vault-name "<vault-name>" --name "mySecret" --value "Success!"

Create a virtual machine

Create a VM named myVM by using one of the following methods:

Linux Windows
Azure CLI Azure CLI
PowerShell PowerShell
Azure portal Azure portal

To create a Linux VM by using the Azure CLI, use the az vm create command. The following example adds a user account named azureuser. The --generate-ssh-keys parameter generates an SSH key and stores it in the default key location (~/.ssh).

az vm create \
  --resource-group <resource-group> \
  --name myVM \
  --image Ubuntu2204 \
  --admin-username azureuser \
  --generate-ssh-keys

Note the value of publicIpAddress in the output.

Assign an identity to the VM

Create a system-assigned managed identity for the VM by using the az vm identity assign command:

az vm identity assign --name "myVM" --resource-group "<resource-group>"

Note the system-assigned identity in the output:

{
  "systemAssignedIdentity": "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx",
  "userAssignedIdentities": {}
}

Assign permissions to the VM identity

Grant the VM's managed identity the Key Vault Secrets User role on the key vault:

az role assignment create --role "Key Vault Secrets User" --assignee "<system-assigned-identity>" --scope /subscriptions/<subscription-id>/resourceGroups/<resource-group>/providers/Microsoft.KeyVault/vaults/<vault-name>

Sign in to the VM

To sign in to the VM, follow the instructions in Connect and sign in to an Azure virtual machine running Linux or Connect and sign in to an Azure virtual machine running Windows.

To sign in to a Linux VM, use ssh with the <public-ip-address> from the Create a virtual machine step:

ssh azureuser@<public-ip-address>

Install Node.js and npm libraries on the VM

On the VM, install the two npm libraries the sample script uses: @azure/keyvault-secrets and @azure/identity.

  1. In the SSH terminal, install Node.js and npm:

    curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash - && \
        sudo apt-get install -y nodejs
    
  2. Create an app directory and initialize the Node.js package:

    mkdir app && cd app && npm init -y
    
  3. Install the Azure packages with npm:

    npm install @azure/keyvault-secrets @azure/identity
    

Create and edit the sample JavaScript file

  1. On the VM in the app directory, create a JavaScript file named index.js:

    touch index.js
    
  2. Open the file with the Nano text editor:

    nano index.js
    
  3. Paste the following code into the editor, replacing <vault-name> with your key vault name:

    // index.js
    
    const { SecretClient } = require("@azure/keyvault-secrets");
    const { DefaultAzureCredential } = require("@azure/identity");
    
    // Your Azure Key Vault name and secret name
    const keyVaultName = "<vault-name>";
    const keyVaultUri = `https://${keyVaultName}.vault.azure.net`;
    const secretName = "mySecret";
    
    // Authenticate to Azure
    const credential = new DefaultAzureCredential();
    const client = new SecretClient(keyVaultUri, credential);
    
    // Get Secret with Azure SDK for JS
    const getSecret = async (secretName) => {
    
        return (await client.getSecret(secretName)).value;
    }
    
    getSecret(secretName).then(secretValue => {
        console.log(`The value of secret '${secretName}' in '${keyVaultName}' is: '${secretValue}'`);
    }).catch(err => {
        console.log(err);
    })
    
  4. Save the file with Ctrl+X.

  5. At the Save modified buffer? prompt, enter y.

  6. At the File Name to Write: index.js prompt, press Enter.

Run the sample Node.js app

Run index.js. If everything is configured correctly, the app prints the secret value:

node index.js

The value of secret 'mySecret' in '<vault-name>' is: 'Success!'

Clean up resources

When you no longer need them, delete the VM and the key vault. The fastest way is to delete the resource group they belong to:

az group delete -g "myResourceGroup"

Next steps

Azure Key Vault REST API