Quickstart: Azure Key Vault keys client library for Go

In this quickstart, you'll learn to use the Azure SDK for Go to create, retrieve, update, list, and delete Azure Key Vault keys.

Azure Key Vault is a cloud service that works as a secure secrets store. You can securely store keys, passwords, certificates, and other secrets. For more information on Key Vault, you may review the Overview.

Follow this guide to learn how to use the azkeys package to manage your Azure Key Vault keys using Go.

Prerequisites

Sign in to the Azure portal

  1. In the Azure CLI, run the following command:

    az login
    

    If the Azure CLI can open your default browser, it will do so on the Azure portal sign-in page.

    If the page doesn't open automatically, go to https://aka.ms/devicelogin, and then enter the authorization code that's displayed in your terminal.

  2. Sign in to the Azure portal with your account credentials.

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 the Azure CLI quickstart, Azure PowerShell quickstart, or Azure portal quickstart.

Alternatively, you can run these Azure CLI or Azure PowerShell commands.

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" --enable-rbac-authorization

Grant access to your key vault

To gain permissions to your key vault through Role-Based Access Control (RBAC), assign a role to your "User Principal Name" (UPN) using the Azure CLI command az role assignment create.

az role assignment create --role "Key Vault Crypto Officer" --assignee "<upn>" --scope "/subscriptions/<subscription-id>/resourceGroups/<resource-group-name>/providers/Microsoft.KeyVault/vaults/<your-unique-keyvault-name>"

Replace <upn>, <subscription-id>, <resource-group-name> and <your-unique-keyvault-name> with your actual values. Your UPN will typically be in the format of an email address (e.g., username@domain.com).

Create a new Go module and install packages

Run the following Go commands:

go mod init quickstart-keys
go get -u github.com/Azure/azure-sdk-for-go/sdk/azidentity
go get -u github.com/Azure/azure-sdk-for-go/sdk/keyvault/azkeys

Create the sample code

Create a file named main.go and copy the following code into the file:

package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/Azure/azure-sdk-for-go/sdk/azcore/to"
	"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
	"github.com/Azure/azure-sdk-for-go/sdk/keyvault/azkeys"
)

func main() {
	keyVaultName := os.Getenv("KEY_VAULT_NAME")
	keyVaultUrl := fmt.Sprintf("https://%s.vault.azure.net/", keyVaultName)

	// create credential
	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatalf("failed to obtain a credential: %v", err)
	}

	// create azkeys client
	client, err := azkeys.NewClient(keyVaultUrl, cred, nil)
	if err != nil {
		log.Fatal(err)
	}

	// create RSA Key
	rsaKeyParams := azkeys.CreateKeyParameters{
		Kty:     to.Ptr(azkeys.JSONWebKeyTypeRSA),
		KeySize: to.Ptr(int32(2048)),
	}
	rsaResp, err := client.CreateKey(context.TODO(), "new-rsa-key", rsaKeyParams, nil)
	if err != nil {
		log.Fatalf("failed to create rsa key: %v", err)
	}
	fmt.Printf("New RSA key ID: %s\n", *rsaResp.Key.KID)

	// create EC Key
	ecKeyParams := azkeys.CreateKeyParameters{
		Kty:   to.Ptr(azkeys.JSONWebKeyTypeEC),
		Curve: to.Ptr(azkeys.JSONWebKeyCurveNameP256),
	}
	ecResp, err := client.CreateKey(context.TODO(), "new-ec-key", ecKeyParams, nil)
	if err != nil {
		log.Fatalf("failed to create ec key: %v", err)
	}
	fmt.Printf("New EC key ID: %s\n", *ecResp.Key.KID)

	// list all vault keys
	fmt.Println("List all vault keys:")
	pager := client.NewListKeysPager(nil)
	for pager.More() {
		page, err := pager.NextPage(context.TODO())
		if err != nil {
			log.Fatal(err)
		}
		for _, key := range page.Value {
			fmt.Println(*key.KID)
		}
	}

	// update key properties to disable key
	updateParams := azkeys.UpdateKeyParameters{
		KeyAttributes: &azkeys.KeyAttributes{
			Enabled: to.Ptr(false),
		},
	}
	// an empty string version updates the latest version of the key
	version := ""
	updateResp, err := client.UpdateKey(context.TODO(), "new-rsa-key", version, updateParams, nil)
	if err != nil {
		panic(err)
	}
	fmt.Printf("Key %s Enabled attribute set to: %t\n", *updateResp.Key.KID, *updateResp.Attributes.Enabled)

	// delete the created keys
	for _, keyName := range []string{"new-rsa-key", "new-ec-key"} {
		// DeleteKey returns when Key Vault has begun deleting the key. That can take several
		// seconds to complete, so it may be necessary to wait before performing other operations
		// on the deleted key.
		delResp, err := client.DeleteKey(context.TODO(), keyName, nil)
		if err != nil {
			panic(err)
		}
		fmt.Printf("Successfully deleted key %s", *delResp.Key.KID)
	}
}

Run the code

Before you run the code, create an environment variable named KEY_VAULT_NAME. Set the environment variable's value to the name of the Azure Key Vault created previously.

export KEY_VAULT_NAME=quickstart-kv

Next, run the following go run command to run the app:

go run main.go
Key ID: https://quickstart-kv.vault.azure.net/keys/new-rsa-key4/f78fe1f34b064934bac86cc8c66a75c3: Key Type: RSA
Key ID: https://quickstart-kv.vault.azure.net/keys/new-ec-key2/10e2cec51d1749c0a26aab784808cfaf: Key Type: EC
List all vault keys:
https://quickstart-kv.vault.azure.net/keys/new-ec-key
https://quickstart-kv.vault.azure.net/keys/new-ec-key1
https://quickstart-kv.vault.azure.net/keys/new-ec-key2
https://quickstart-kv.vault.azure.net/keys/new-rsa-key4
Enabled set to: false
Successfully deleted key https://quickstart-kv.vault.azure.net/keys/new-rsa-key4/f78fe1f34b064934bac86cc8c66a75c3

Note

The output is for informational purposes only. Your return values may vary based on your Azure subscription and Azure Key Vault.

Code examples

See the module documentation for more examples.

Clean up resources

Run the following command to delete the resource group and all its remaining resources:

az group delete --resource-group quickstart-rg

Next steps