Quickstart: Manage secrets by using the Azure Key Vault Go client library
In this quickstart, you'll learn how to use the Azure SDK for Go to create, retrieve, list, and delete secrets from an Azure key vault.
You can store a variety of object types in an Azure key vault. When you store secrets in a key vault, you avoid having to store them in your code, which helps improve the security of your applications.
Get started with the azsecrets package and learn how to manage your secrets in an Azure key vault by using Go.
Prerequisites
- An Azure subscription. If you don't already have a subscription, you can create one for free.
- Go version 1.18 or later, installed.
- The Azure CLI, installed.
Setup
For purposes of this quickstart, you use the azidentity package to authenticate to Azure by using the Azure CLI. To learn about the various authentication methods, see Azure authentication with the Azure SDK for Go.
Sign in to the Azure portal
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.
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 Secrets 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 kvSecrets
go get -u github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets
go get -u github.com/Azure/azure-sdk-for-go/sdk/azidentity
Sample code
Create a file named main.go, and then paste the following code into it:
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/Azure/azure-sdk-for-go/sdk/azidentity"
"github.com/Azure/azure-sdk-for-go/sdk/keyvault/azsecrets"
)
func main() {
mySecretName := "secretName01"
mySecretValue := "secretValue"
vaultURI := fmt.Sprintf("https://%s.vault.azure.net/", os.Getenv("KEY_VAULT_NAME"))
// Create a credential using the NewDefaultAzureCredential type.
cred, err := azidentity.NewDefaultAzureCredential(nil)
if err != nil {
log.Fatalf("failed to obtain a credential: %v", err)
}
// Establish a connection to the Key Vault client
client, err := azsecrets.NewClient(vaultURI, cred, nil)
// Create a secret
params := azsecrets.SetSecretParameters{Value: &mySecretValue}
_, err = client.SetSecret(context.TODO(), mySecretName, params, nil)
if err != nil {
log.Fatalf("failed to create a secret: %v", err)
}
// Get a secret. An empty string version gets the latest version of the secret.
version := ""
resp, err := client.GetSecret(context.TODO(), mySecretName, version, nil)
if err != nil {
log.Fatalf("failed to get the secret: %v", err)
}
fmt.Printf("secretValue: %s\n", *resp.Value)
// List secrets
pager := client.NewListSecretsPager(nil)
for pager.More() {
page, err := pager.NextPage(context.TODO())
if err != nil {
log.Fatal(err)
}
for _, secret := range page.Value {
fmt.Printf("Secret ID: %s\n", *secret.ID)
}
}
// Delete a secret. DeleteSecret returns when Key Vault has begun deleting the secret.
// That can take several seconds to complete, so it may be necessary to wait before
// performing other operations on the deleted secret.
delResp, err := client.DeleteSecret(context.TODO(), mySecretName, nil)
if err != nil {
log.Fatalf("failed to delete secret: %v", err)
}
fmt.Println(delResp.ID.Name() + " has been deleted")
}
Run the code
Before you run the code, create an environment variable named
KEY_VAULT_NAME
. Set the environment variable value to the name of the key vault that you created previously.export KEY_VAULT_NAME=quickstart-kv
To start the Go app, run the following command:
go run main.go
secretValue: createdWithGO Secret ID: https://quickstart-kv.vault.azure.net/secrets/quickstart-secret Secret ID: https://quickstart-kv.vault.azure.net/secrets/secretName quickstart-secret has been deleted
Code examples
See the module documentation for more examples.
Clean up resources
Delete the resource group and all its remaining resources by running the following command:
az group delete --resource-group quickstart-rg