Редагувати

Поділитися через


Quickstart: Azure Key Vault certificate client library for Go

In this quickstart, you'll learn to use the Azure SDK for Go to manage certificates in an Azure Key Vault.

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 azcertificates package to manage your Azure Key Vault certificates 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 Certificate 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-go-kvcerts
go get github.com/Azure/azure-sdk-for-go/sdk/keyvault/azcertificates
go get github.com/Azure/azure-sdk-for-go/sdk/azidentity

Create the sample code

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

package main

import (
	"context"
	"fmt"
	"log"
	"time"

	"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/azcertificates"
)

func getClient() *azcertificates.Client {
	keyVaultName := os.Getenv("KEY_VAULT_NAME")
	if keyVaultName == "" {
		log.Fatal("KEY_VAULT_NAME environment variable not set")
	}
	keyVaultUrl := fmt.Sprintf("https://%s.vault.azure.net/", keyVaultName)

	cred, err := azidentity.NewDefaultAzureCredential(nil)
	if err != nil {
		log.Fatal(err)
	}

	return azcertificates.NewClient(keyVaultUrl, cred, nil)
}

func createCert(client *azcertificates.Client) {
	params := azcertificates.CreateCertificateParameters{
		CertificatePolicy: &azcertificates.CertificatePolicy{
			IssuerParameters: &azcertificates.IssuerParameters{
				Name: to.Ptr("Self"),
			},
			X509CertificateProperties: &azcertificates.X509CertificateProperties{
				Subject: to.Ptr("CN=DefaultPolicy"),
			},
		},
	}
	resp, err := client.CreateCertificate(context.TODO(), "myCertName", params, nil)
	if err != nil {
		log.Fatal(err)
	}

	fmt.Printf("Requested a new certificate. Operation status: %s\n", *resp.Status)
}

func getCert(client *azcertificates.Client) {
	// an empty string version gets the latest version of the certificate
	version := ""
	getResp, err := client.GetCertificate(context.TODO(), "myCertName", version, nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Enabled set to:", *getResp.Attributes.Enabled)
}

func listCert(client *azcertificates.Client) {
	pager := client.NewListCertificatesPager(nil)
	for pager.More() {
		page, err := pager.NextPage(context.Background())
		if err != nil {
			log.Fatal(err)
		}
		for _, cert := range page.Value {
			fmt.Println(*cert.ID)
		}
	}
}

func updateCert(client *azcertificates.Client) {
	// disables the certificate, sets an expires date, and add a tag
	params := azcertificates.UpdateCertificateParameters{
		CertificateAttributes: &azcertificates.CertificateAttributes{
			Enabled: to.Ptr(false),
			Expires: to.Ptr(time.Now().Add(72 * time.Hour)),
		},
		Tags: map[string]*string{"Owner": to.Ptr("SRE")},
	}
	// an empty string version updates the latest version of the certificate
	version := ""
	_, err := client.UpdateCertificate(context.TODO(), "myCertName", version, params, nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Updated certificate properites: Enabled=false, Expires=72h, Tags=SRE")
}

func deleteCert(client *azcertificates.Client) {
	// DeleteCertificate returns when Key Vault has begun deleting the certificate. That can take several
	// seconds to complete, so it may be necessary to wait before performing other operations on the
	// deleted certificate.
	resp, err := client.DeleteCertificate(context.TODO(), "myCertName", nil)
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println("Deleted certificate with ID: ", *resp.ID)
}

func main() {
	fmt.Println("Authenticating...")
	client := getClient()

	fmt.Println("Creating a certificate...")
	createCert(client)

	fmt.Println("Getting certificate Enabled property ...")
	getCert(client)

	fmt.Println("Listing certificates...")
	listCert(client)

	fmt.Println("Updating a certificate...")
	updateCert(client)

	fmt.Println("Deleting a certificate...")
	deleteCert(client)
}

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=<YourKeyVaultName>

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

go run main.go

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 myResourceGroup

Next steps