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

Azure Key Vault helps you to 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 managed identities 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
  • This tutorial requires that you run the Azure CLI locally. You must have the Azure CLI version 2.0.4 or later installed. Run az --version to find the version. If you need to install or upgrade the CLI, see Install Azure CLI 2.0.

Log in to Azure

To log in to Azure by using the Azure CLI, enter:

az login

Create a resource group and key vault

This quickstart uses a pre-created Azure key vault. You can create a key vault by following the steps in the Azure CLI quickstart, Azure PowerShell quickstart, or Azure portal quickstart.

Alternatively, you can simply run the Azure CLI or Azure PowerShell commands below.

Important

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

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

az keyvault create --name "<your-unique-keyvault-name>" -g "myResourceGroup"

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 "<your-unique-keyvault-name>" --name "mySecret" --value "Success!"

Create a virtual machine

Create a VM called myVM using one of the following methods:

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

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

az vm create \
  --resource-group myResourceGroup \
  --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 identity for the virtual machine by using the Azure CLI az vm identity assign command:

az vm identity assign --name "myVM" --resource-group "myResourceGroup"

Note the system-assigned identity that's displayed in the following code. The output of the preceding command would be:

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

Assign permissions to the VM identity

Now you can assign the previously created identity permissions to your key vault by running the following command:

az keyvault set-policy --name "<your-unique-keyvault-name>" --object-id "<systemAssignedIdentity>" --secret-permissions get list

Log in to the VM

To sign in to the virtual machine, 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 log into a Linux VM, you can use the ssh command with the <publicIpAddress> given in the Create a virtual machine step:

ssh azureuser@<PublicIpAddress>

Install Node.js and npm libraries on the VM

On the virtual machine, install the two npm libraries we'll be using in our JavaScript script: @azure/keyvault-secrets and @azure/identity.

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

    curl -sL https://deb.nodesource.com/setup_14.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 service packages using npm:

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

Create and edit the sample JavaScript file

  1. On the virtual machine in the app directory, create a JavaScript file called index.js.

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

    nano index.js
    
  3. Copy the following code, replacing <your-unique-keyvault-name> with the name of your key vault, and paste into the Nano editor:

    // index.js
    
    const { SecretClient } = require("@azure/keyvault-secrets");
    const { DefaultAzureCredential } = require("@azure/identity");
    
    // Your Azure Key Vault name and secret name
    const keyVaultName = "<your-unique-keyvault-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. When asked Save modified buffer?, enter y.

  6. When asked File Name to Write: index.js, enter Enter.

Run the sample Node.js app

Lastly, run index.js. If all has gone well, it should return the value of your secret:

node index.js

The value of secret 'mySecret' in '<your-unique-keyvault-name>' is: 'Success!'

Clean up resources

When they are no longer needed, delete the virtual machine and your key vault. You can do this quickly by simply deleting the resource group to which they belong:

az group delete -g myResourceGroup

Next steps

Azure Key Vault REST API