快速入門:適用於 Go 的 Azure Key Vault 憑證用戶端程式庫

在本快速入門文章中,您將瞭解如何使用 Azure SDK for Go 來管理 Azure Key Vault 中的憑證。

Azure Key Vault 是一項雲端服務,可作為安全的祕密存放區。 您也可以安全地儲存金鑰、密碼、憑證和其他祕密。 如需 Key Vault 的詳細資訊,您可以檢閱概觀

請遵循本指南,瞭解如何使用 azcertificates 套件,以使用 Go 管理 Azure Key Vault 憑證。

必要條件

登入 Azure 入口網站

  1. 在 Azure CLI 中執行下列命令:

    az login
    

    如果 Azure CLI 可以開啟預設瀏覽器,它會在 Azure 登入頁面登入。

    如果頁面未自動開啟,請移至 https://aka.ms/devicelogin,然後輸入終端中顯示的授權碼。

  2. 使用您的帳戶登入資訊登入 Azure 入口網站。

建立資源群組和金鑰保存庫

本快速入門會使用預先建立的 Azure 金鑰保存庫。 您可以遵循 Azure CLI 快速入門Azure PowerShell 快速入門Azure 入口網站快速入門中的步驟來建立金鑰保存庫。

或者,您也可以直接執行這些 Azure CLI 或 Azure PowerShell 命令。

重要

每個金鑰保存庫必須有唯一的名稱。 在下列範例中,將 <your-unique-keyvault-name> 取代為您的金鑰保存庫名稱。

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

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

授與對金鑰保存庫的存取權

若要透過角色型存取控制 (RBAC) 取得金鑰保存庫的權限,請使用 Azure CLI 命令 az role assignment create 將角色指派給「使用者主體名稱」(UPN)。

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>"

以實際值取代 <upn>、<subscription-id>、<resource-group-name> 和 <your-unique-keyvault-name>。 您 UPN 的格式通常是電子郵件地址 (例如,username@domain.com)。

建立新的 Go 模組並安裝封裝

執行下列 Go 命令:

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

建立範例程式碼

建立名稱為 main.go 的檔案,並將下列程式碼複製至檔案:

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)
}

執行程式碼

執行程式碼之前,請先建立名稱為 KEY_VAULT_NAME 的環境變數。 將環境變數的值設為先前所建立 Azure Key Vault 的名稱。

export KEY_VAULT_NAME=<YourKeyVaultName>

接下來,執行下列 go run 命令來執行應用程式:

go run main.go

程式碼範例

如需更多範例,請參閱課程模組文件

清除資源

若要刪除資源群組及其所有剩餘資源,請執行下列命令︰

az group delete --resource-group myResourceGroup

下一步