빠른 시작: Go용 Azure Key Vault 인증서 클라이언트 라이브러리
이 빠른 시작에서는 Go용 Azure SDK를 사용하여 Azure Key Vault에서 인증서를 관리하는 방법을 알아봅니다.
Azure Key Vault는 보안 비밀 저장소로 작동하는 클라우드 서비스입니다. 키, 암호, 인증서 및 기타 비밀을 안전하게 저장할 수 있습니다. Key Vault에 대한 자세한 내용을 보려면 개요를 살펴보세요.
이 가이드에 따라 azcertificates 패키지에서 Go를 사용하여 Azure Key Vault 인증서를 관리하는 방법을 알아봅니다.
필수 조건
Azure Portal에 로그인
Azure CLI에서 다음 명령을 실행합니다.
az login
Azure CLI는 기본 브라우저를 열 수 있는 경우 Azure Portal 로그인 페이지에서 열 수 있습니다.
페이지가 자동으로 열리지 않으면 https://aka.ms/devicelogin으로 이동한 다음, 터미널에 표시되는 권한 부여 코드를 입력합니다.
계정 자격 증명을 사용하여 Azure Portal에 로그인합니다.
리소스 그룹 및 키 자격 증명 모음 만들기
이 빠른 시작에서는 미리 만든 Azure Key Vault를 사용합니다. Azure CLI 빠른 시작, Azure PowerShell 빠른 시작 또는 Azure Portal 빠른 시작의 단계에 따라 키 자격 증명 모음을 만들 수 있습니다.
또는 다음의 Azure CLI 또는 Azure PowerShell 명령을 실행할 수 있습니다.
Important
각 Key Vault마다 고유한 이름이 있어야 합니다. 다음 예제에서는 <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 Certificates 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