본문으로 바로가기 본문 바로가기
WIKI 기술 지식 베이스

AzureDNS

원문 보기 위키 갱신

cert-manager는 Azure DNS에서 DNS-01 레코드를 만들고 삭제할 수 있지만, 먼저 Azure에 인증해야 해요. 네 가지 인증 방법을 하나씩 알아볼게요.

출처: 문서

본문

cert-manager는 Azure DNS에서 DNS-01 레코드를 만든 다음 삭제할 수 있지만, 먼저 Azure에 인증해야 해요. 다음 네 가지 인증 방법을 사용할 수 있습니다:

AAD Workload Identity를 사용한 Managed Identity

ℹ️ 이 기능은 cert-manager >= v1.11.0에서 사용할 수 있어요.

📖 이 인증 방법의 end-to-end 예시는 AKS + LoadBalancer + Let's Encrypt 튜토리얼을 읽어 보세요.

AKS(Azure Kubernetes Service)의 Azure AD workload identity(미리보기)를 사용하면 cert-manager가 Kubernetes ServiceAccount Token으로 Azure에 인증한 다음 Azure DNS에서 DNS-01 레코드를 관리할 수 있어요. 이는 다른 방법보다 더 안전하고 유지 관리가 쉬워 권장되는 인증 방법입니다.

클러스터 재구성 (Reconfigure the cluster)

클러스터에서 workload identity federation 기능을 활성화하세요. Azure AKS 클러스터가 있다면 다음 명령을 사용할 수 있습니다:

az aks update \
    --name ${CLUSTER} \
    --enable-oidc-issuer \
    --enable-workload-identity

ℹ️ Azure AKS를 사용하지 않는다면 다른 관리형 및 자체 관리형 클러스터에 Azure workload identity 확장을 설치할 수 있어요 (설치 문서).

📖 --enable-workload-identity 기능에 대한 자세한 내용은 AKS(Azure Kubernetes Service) 클러스터에 workload identity 배포 및 구성을 읽어 보세요.

cert-manager 재구성 (Reconfigure cert-manager)

Azure Workload Identity 웹훅이 주의를 기울이도록 cert-manager controller Pod에 라벨을 지정하세요. 그러면 cert-manager controller Pod에 Azure에 인증하는 데 사용할 Kubernetes ServiceAccount token을 포함하는 추가 볼륨이 생깁니다.

Helm으로 cert-manager를 설치했다면 Helm values로 라벨을 구성할 수 있어요:

# values.yaml
podLabels:
  azure.workload.identity/use: "true"

성공하면 cert-manager Pod에 몇 가지 새 환경 변수가 설정되고, Azure workload-identity ServiceAccount token이 projected volume으로 포함됩니다:

kubectl describe pod -n cert-manager -l app.kubernetes.io/component=controller
Containers:
    ...
    cert-manager-controller:
        ...
        Environment:
        ...
        AZURE_CLIENT_ID:
        AZURE_TENANT_ID:             f99bd6a4-665c-41cf-aff1-87a89d5c62d4
        AZURE_FEDERATED_TOKEN_FILE:  /var/run/secrets/azure/tokens/azure-identity-token
        AZURE_AUTHORITY_HOST:        https://login.microsoftonline.com/
    Mounts:
      /var/run/secrets/azure/tokens from azure-identity-token (ro)
Volumes:
   ...
  azure-identity-token:
    Type:                    Projected (a volume that contains injected data from multiple sources)
    TokenExpirationSeconds:  3600

📖 Kubernetes에서 Azure AD Workload Identity에서 Mutating Admission Webhook의 역할에 대해 읽어 보세요.

Managed Identity 생성 (Create a Managed Identity)

cert-manager가 Azure API를 사용하고 Azure DNS zone의 레코드를 조작하려면 Azure 계정이 필요하며, 사용하기 가장 좋은 계정 유형은 "Managed Identity"라고 합니다. 이 계정에는 비밀번호나 API 키가 없으며 사람이 아닌 시스템이 사용하도록 설계되었어요.

managed identity 이름을 선택하고 Managed Identity를 생성하세요:

export IDENTITY_NAME=cert-manager
export IDENTITY_RESOURCE_GROUP= # ❗ Replace with your Azure resource group
az identity create --name "${IDENTITY_NAME}" --resource-group "${IDENTITY_RESOURCE_GROUP}"

DNS zone 레코드를 수정할 수 있는 권한을 부여해요:

export IDENTITY_CLIENT_ID=$(az identity show --name "${IDENTITY_NAME}" --resource-group "${IDENTITY_RESOURCE_GROUP}" --query 'clientId' -o tsv)
az role assignment create \
    --role "DNS Zone Contributor" \
    --assignee $IDENTITY_CLIENT_ID \
    --scope $(az network dns zone show --name $DOMAIN_NAME -o tsv --query id)

📖 managed identity와 그 용도에 대한 개요는 Azure 리소스용 관리 ID란 무엇인가요?를 읽어 보세요.

📖 "DNS Zone Contributor" 역할에 대해 알아보려면 Azure 기본 제공 역할을 읽어 보세요.

📖 az identity 명령에 대해 자세히 읽어 보세요.

Federated Identity 추가 (Add a Federated Identity)

이제 앞에서 만든 managed identity와 federated identity를 연결해요. cert-manager는 수명이 짧은 Kubernetes ServiceAccount token을 사용해 Azure에 인증하게 되며, 앞 단계에서 만든 managed identity를 가장(impersonate)할 수 있게 됩니다.

export SERVICE_ACCOUNT_NAME=cert-manager # ℹ️ This is the default Kubernetes ServiceAccount used by the cert-manager controller.
export SERVICE_ACCOUNT_NAMESPACE=cert-manager # ℹ️ This is the default namespace for cert-manager.
export SERVICE_ACCOUNT_ISSUER=$(az aks show --resource-group $AZURE_DEFAULTS_GROUP --name $CLUSTER --query "oidcIssuerProfile.issuerUrl" -o tsv)
az identity federated-credential create \
  --name "cert-manager" \
  --identity-name "${IDENTITY_NAME}" \
  --resource-group "${IDENTITY_RESOURCE_GROUP}" \
  --issuer "${SERVICE_ACCOUNT_ISSUER}" \
  --subject "system:serviceaccount:${SERVICE_ACCOUNT_NAMESPACE}:${SERVICE_ACCOUNT_NAME}"
  • --subject: Kubernetes ServiceAccount의 고유 이름(distinguishing name)이에요.
  • --issuer: Azure가 JWT 서명 인증서와 기타 메타데이터를 다운로드할 URL이에요.

📖 Microsoft identity platform 문서의 Workload identity federation을 읽어 보세요.

📖 az identity federated-credential 명령에 대해 자세히 읽어 보세요.

ClusterIssuer 구성 (Configure a ClusterIssuer)

예를 들면:

apiVersion: cert-manager.io/v1
kind: ClusterIssuer
metadata:
  name: letsencrypt-staging
spec:
  acme:
    server: https://acme-staging-v02.api.letsencrypt.org/directory
    email: $EMAIL_ADDRESS
    privateKeySecretRef:
      name: letsencrypt-staging
    solvers:
    - dns01:
        azureDNS:
          hostedZoneName: $AZURE_ZONE_NAME
          resourceGroupName: $AZURE_RESOURCE_GROUP
          subscriptionID: $AZURE_SUBSCRIPTION_ID
          environment: AzurePublicCloud
          managedIdentity:
            # client ID of the managed identity; overrides AZURE_CLIENT_ID from the environment
            clientID: $IDENTITY_CLIENT_ID
            # # optional: tenant ID of the managed identity; overrides AZURE_TENANT_ID from the environment.
            # tenantID: $IDENTITY_TENANT_ID

ℹ️ managedIdentity.clientID와 managedIdentity.tenantID는 Azure Workload Identity 웹훅이 환경 변수(AZURE_CLIENT_ID, AZURE_TENANT_ID)로 주입한 값을 덮어씁니다.

다음 변수를 채워야 합니다.

# An email address to which Let's Encrypt will send renewal reminders.
export EMAIL_ADDRESS=
# The Azure DNS zone in which the DNS-01 records will be created and deleted.
export AZURE_ZONE_NAME=
# The Azure resource group containing the DNS zone.
export AZURE_RESOURCE_GROUP=
# The Azure billing account name and ID for the DNS zone.
export AZURE_SUBSCRIPTION=
export AZURE_SUBSCRIPTION_ID=$(az account show --name $AZURE_SUBSCRIPTION --query 'id' -o tsv)

⚠️ ClusterIssuer 및 Issuer 리소스에서 'Ambient Credentials' 사용하기

이 인증 방법은 cert-manager가 'ambient credentials'라고 부르는 것의 한 예시예요. Ambient credentials는 ClusterIssuer 리소스에는 기본적으로 활성화되어 있지만 Issuer 리소스에는 기본적으로 비활성화되어 있어요. 이는 Issuer 리소스를 생성할 권한이 있는 비특권 사용자가 cert-manager가 우연히 접근할 수 있는 자격 증명으로 인증서를 발급하지 못하도록 하기 위한 것입니다. ClusterIssuer 리소스는 클러스터 범위(cluster scoped)이며 플랫폼 관리자만 생성 권한을 부여받아야 해요.

이 인증 메커니즘을 사용하면서 ambient credentials가 활성화되지 않았다면 다음과 같은 오류가 표시됩니다:

error instantiating azuredns challenge solver: ClientID was omitted without providing one of `--cluster-issuer-ambient-credentials` or `--issuer-ambient-credentials`. These are necessary to enable Azure Managed Identities

⚠️ cert-manager controller에 --issuer-ambient-credentials 플래그를 true로 설정해 Issuer 리소스에 대해 이 인증 메커니즘을 활성화하는 것이 가능하지만(권장하지 않음) 그렇습니다.

AAD Pod Identities를 사용한 Managed Identity

⚠️ Azure Kubernetes Service의 오픈 소스 Azure AD pod-managed identity(미리보기)는 2022년 10월 24일부로 deprecated되었어요. 대신 Workload Identity를 사용하세요.

AAD Pod Identities를 사용하면 Managed Identity를 pod에 할당할 수 있어요. 이렇게 하면 필요한 DNS 레코드를 만들기 위해 클러스터에 명시적 자격 증명을 추가할 필요가 없습니다.

참고: Pod identity를 사용할 때 단일 pod에 여러 identity를 할당하는 것이 허용되지만, 현재 cert-manager는 어떤 identity를 사용할지 식별할 수 없어 이 기능을 지원하지 않아요.

먼저 DNS Zone에 기여할 수 있는 접근 권한이 있는 identity를 만들어야 해요.

  • azure-cli와 jq를 사용한 생성 예시:
# Choose a unique Identity name and existing resource group to create identity in.
IDENTITY=$(az identity create --name $IDENTITY_NAME --resource-group $IDENTITY_GROUP --output json)

# Gets principalId to use for role assignment
PRINCIPAL_ID=$(echo $IDENTITY | jq -r '.principalId')

# Used for identity binding
CLIENT_ID=$(echo $IDENTITY | jq -r '.clientId')
RESOURCE_ID=$(echo $IDENTITY | jq -r '.id')

# Get existing DNS Zone Id
ZONE_ID=$(az network dns zone show --name $ZONE_NAME --resource-group $ZONE_GROUP --query "id" -o tsv)

# Create role assignment
az role assignment create --role "DNS Zone Contributor" --assignee $PRINCIPAL_ID --scope $ZONE_ID
  • Terraform을 사용한 생성 예시:
variable resource_group_name {}
variable location {}
variable dns_zone_id {}

# Creates Identity
resource "azurerm_user_assigned_identity" "dns_identity" {
  name                = "cert-manager-dns01"
  resource_group_name = var.resource_group_name
  location            = var.location
}

# Creates Role Assignment
resource "azurerm_role_assignment" "dns_contributor" {
  scope                = var.dns_zone_id
  role_definition_name = "DNS Zone Contributor"
  principal_id         = azurerm_user_assigned_identity.dns_identity.principal_id
}

# Client Id Used for identity binding
output "identity_client_id" {
  value = azurerm_user_assigned_identity.dns_identity.client_id
}

# Resource Id Used for identity binding
output "identity_resource_id" {
  value = azurerm_user_assigned_identity.dns_identity.id
}

다음으로 AAD Pod Identity를 walk-through대로 설치했는지 확인해야 해요. walk-through는 identity를 할당하는 데 필요한 CRD와 deployment를 설치합니다.

이제 아래 매니페스트를 예시로 identity 리소스와 binding을 만들 수 있어요:

apiVersion: "aadpodidentity.k8s.io/v1"
kind: AzureIdentity
metadata:
  annotations:
    # recommended to use namespaced identities https://azure.github.io/aad-pod-identity/docs/configure/match_pods_in_namespace/
    aadpodidentity.k8s.io/Behavior: namespaced
  name: certman-identity
  namespace: cert-manager # change to your preferred namespace
spec:
  type: 0 # MSI
  resourceID:  # Resource Id From Previous step
  clientID:  # Client Id from previous step
---
apiVersion: "aadpodidentity.k8s.io/v1"
kind: AzureIdentityBinding
metadata:
  name: certman-id-binding
  namespace: cert-manager # change to your preferred namespace
spec:
  azureIdentity: certman-identity
  selector: certman-label # This is the label that needs to be set on cert-manager pods

다음으로 cert-manager pod에 pod identity binding을 사용하도록 관련 라벨이 있는지 확인해야 해요. 이는 deployment를 편집하고 .spec.template.metadata.labels 필드에 다음을 추가하면 됩니다:

spec:
  template:
    metadata:
      labels:
        aadpodidbinding: certman-label # must match selector in AzureIdentityBinding

또는 helm values podLabels를 사용해:

podLabels:
  aadpodidbinding: certman-label

마지막으로 certificate issuer를 만들 때 DNS zone에 대해 hostedZoneName, resourceGroupName, subscriptionID 필드만 지정하면 돼요. 예시는 아래와 같습니다:

apiVersion: cert-manager.io/v1
kind: Issuer
metadata:
  name: example-issuer
spec:
  acme:
    ...
    solvers:
    - dns01:
        azureDNS:
          subscriptionID: AZURE_SUBSCRIPTION_ID
          resourceGroupName: AZURE_DNS_ZONE_RESOURCE_GROUP
          hostedZoneName: AZURE_DNS_ZONE
          # Azure Cloud Environment, default to AzurePublicCloud
          environment: AzurePublicCloud

이 인증 메커니즘은 cert-manager가 'ambient credentials'라고 간주하는 것입니다. cert-manager Issuer에서는 ambient credentials 사용이 기본적으로 비활성화되어 있어요. 이는 issuer를 생성할 권한이 있는 비특권 사용자가 cert-manager가 우연히 접근할 수 있는 자격 증명으로 인증서를 발급할 수 없도록 하기 위한 것입니다. Issuer에 대해 이 인증 메커니즘을 활성화하려면 cert-manager controller에 --issuer-ambient-credentials 플래그를 true로 설정해야 합니다. (기본적으로 true로 설정된 대응 플래그 --cluster-issuer-ambient-credentials가 있습니다.)

이 인증 메커니즘을 사용하면서 ambient credentials가 활성화되지 않았다면 다음과 같은 오류가 표시됩니다:

error instantiating azuredns challenge solver: ClientID was omitted without providing one of `--cluster-issuer-ambient-credentials` or `--issuer-ambient-credentials`. These are necessary to enable Azure Managed Identities

AKS Kubelet Identity를 사용한 Managed Identity

Azure에서 AKS 클러스터를 만들 때 kubelet에 할당되는 managed identity를 사용하는 옵션이 있어요. 이 identity는 AKS 클러스터의 기본 노드 풀에 할당되며 cert-manager pod가 Azure Active Directory에 인증하는 데 사용할 수 있습니다.

이 방법에는 몇 가지 주의사항이 있어요, 주로 다음과 같습니다:

  • 이 identity에 부여된 권한은 Kubernetes 클러스터 내부에서 실행되는 모든 컨테이너에서도 접근할 수 있어요.
  • Kube Dashboard, Virtual Node, HTTP Application Routing 같은 AKS 확장을 사용하면(전체 목록은 여기 참고) 노드 풀에 할당되는 추가 identity가 생성됩니다. 노드 풀에 identity가 둘 이상 할당된 경우 올바른 identity를 선택하려면 clientID 또는 resourceID를 지정해야 해요.

이를 설정하려면 먼저 AKS 클러스터를 조회해 kubelet이 사용하는 identity를 검색해야 해요. 그런 다음 이를 사용해 DNS zone에 적절한 권한을 만들 수 있습니다.

  • azure-cli를 사용한 예시 명령:
# Get AKS Kubelet Identity
PRINCIPAL_ID=$(az aks show -n $CLUSTERNAME -g $CLUSTER_GROUP --query "identityProfile.kubeletidentity.objectId" -o tsv)

# Get existing DNS Zone Id
ZONE_ID=$(az network dns zone show --name $ZONE_NAME --resource-group $ZONE_GROUP --query "id" -o tsv)

# Create role assignment
az role assignment create --role "DNS Zone Contributor" --assignee $PRINCIPAL_ID --scope $ZONE_ID
  • Terraform 예시:
variable dns_zone_id {}

# Creating the AKS cluster, abbreviated.
resource "azurerm_kubernetes_cluster" "cluster" {
  ...
  # Creates Identity associated to kubelet
  identity {
    type = "SystemAssigned"
  }
  ...
}

resource "azurerm_role_assignment" "dns_contributor" {
  scope                            = var.dns_zone_id
  role_definition_name             = "DNS Zone Contributor"
  principal_id                     = azurerm_kubernetes_cluster.cluster.kubelet_identity[0].object_id
  skip_service_principal_aad_check = true # Allows skipping propagation of identity to ensure assignment succeeds.
}

그런 다음 cert-manager issuer를 만들 때 DNS zone에 대해 hostedZoneName, resourceGroupName, subscriptionID 필드를 지정해야 해요.

노드 풀에 여러 managed identity가 할당된 경우 managedIdentity.clientID 또는 managedIdentity.resourceID도 지정해야 합니다.

managedIdentity.clientID 값은 다음 명령을 실행해 가져올 수 있어요:

az aks show -n $CLUSTERNAME -g $CLUSTER_GROUP --query "identityProfile.kubeletidentity.clientId" -o tsv

예시는 아래와 같습니다:

apiVersion: cert-manager.io/v1
kind: Issuer
metadata:
  name: example-issuer
spec:
  acme:
    ...
    solvers:
    - dns01:
        azureDNS:
          subscriptionID: AZURE_SUBSCRIPTION_ID
          resourceGroupName: AZURE_DNS_ZONE_RESOURCE_GROUP
          hostedZoneName: AZURE_DNS_ZONE
          # Azure Cloud Environment, default to AzurePublicCloud
          environment: AzurePublicCloud
          # optional, only required if node pools have more than 1 managed identity assigned
          managedIdentity:
            # client id of the node pool managed identity (can not be set at the same time as resourceID)
            clientID: YOUR_MANAGED_IDENTITY_CLIENT_ID
            # resource id of the managed identity (can not be set at the same time as clientID)
            # resourceID: YOUR_MANAGED_IDENTITY_RESOURCE_ID

Service Principal

Kubernetes 클러스터에 대한 AzureDNS DNS01 Challenge를 구성하려면 Azure에서 service principal을 만들어야 해요.

service principal을 만들려면 다음 스크립트를 사용할 수 있어요(azure-cli와 jq 필요):

# Choose a name for the service principal that contacts azure DNS to present the challenge.
AZURE_CERT_MANAGER_NEW_SP_NAME=NEW_SERVICE_PRINCIPAL_NAME
# This is the name of the resource group that you have your dns zone in.
AZURE_DNS_ZONE_RESOURCE_GROUP=AZURE_DNS_ZONE_RESOURCE_GROUP
# The DNS zone name. It should be something like domain.com or sub.domain.com.
AZURE_DNS_ZONE=AZURE_DNS_ZONE

DNS_SP=$(az ad sp create-for-rbac --name $AZURE_CERT_MANAGER_NEW_SP_NAME --output json)
AZURE_CERT_MANAGER_SP_APP_ID=$(echo $DNS_SP | jq -r '.appId')
AZURE_CERT_MANAGER_SP_PASSWORD=$(echo $DNS_SP | jq -r '.password')
AZURE_TENANT_ID=$(echo $DNS_SP | jq -r '.tenant')
AZURE_SUBSCRIPTION_ID=$(az account show --output json | jq -r '.id')

보안상 RBAC를 사용해 Azure의 리소스에 대한 접근 제어를 적절히 유지하는 것이 좋아요. 이 튜토리얼에서 생성된 service principal은 지정된 특정 리소스 그룹의 DNS Zone에 대해서만 세밀한 접근 권한을 가집니다. 이 권한은 zone에 _acme_challenge TXT 레코드를 읽고 쓰기 위해 필요해요.

service principal의 권한을 낮추세요.

az role assignment delete --assignee $AZURE_CERT_MANAGER_SP_APP_ID --role Contributor

DNS Zone에 접근 권한을 부여하세요.

DNS_ID=$(az network dns zone show --name $AZURE_DNS_ZONE --resource-group $AZURE_DNS_ZONE_RESOURCE_GROUP --query "id" --output tsv)
az role assignment create --assignee $AZURE_CERT_MANAGER_SP_APP_ID --role "DNS Zone Contributor" --scope $DNS_ID

권한을 확인하세요. 다음 명령의 결과로 permissions 배열에 "DNS Zone Contributor" 역할의 객체가 하나만 보이길 원합니다.

az role assignment list --all --assignee $AZURE_CERT_MANAGER_SP_APP_ID

Azure DNS에 challenge를 제출하려면 service principal 비밀번호를 포함하는 secret을 Kubernetes에 만들어야 해요. 다음 명령으로 secret을 만들 수 있습니다:

kubectl create secret generic azuredns-config --from-literal=client-secret=$AZURE_CERT_MANAGER_SP_PASSWORD

issuer를 구성할 변수를 가져오세요.

echo "AZURE_CERT_MANAGER_SP_APP_ID: $AZURE_CERT_MANAGER_SP_APP_ID"
echo "AZURE_CERT_MANAGER_SP_PASSWORD: $AZURE_CERT_MANAGER_SP_PASSWORD"
echo "AZURE_SUBSCRIPTION_ID: $AZURE_SUBSCRIPTION_ID"
echo "AZURE_TENANT_ID: $AZURE_TENANT_ID"
echo "AZURE_DNS_ZONE: $AZURE_DNS_ZONE"
echo "AZURE_DNS_ZONE_RESOURCE_GROUP: $AZURE_DNS_ZONE_RESOURCE_GROUP"

issuer를 구성하려면 이전 스크립트의 값을 대문자 변수에 대입하세요. subscription id는 Azure portal에서 얻을 수 있어요.

apiVersion: cert-manager.io/v1
kind: Issuer
metadata:
  name: example-issuer
spec:
  acme:
    ...
    solvers:
    - dns01:
        azureDNS:
          clientID: AZURE_CERT_MANAGER_SP_APP_ID
          clientSecretSecretRef:
          # The following is the secret we created in Kubernetes. Issuer will use this to present challenge to Azure DNS.
            name: azuredns-config
            key: client-secret
          subscriptionID: AZURE_SUBSCRIPTION_ID
          tenantID: AZURE_TENANT_ID
          resourceGroupName: AZURE_DNS_ZONE_RESOURCE_GROUP
          hostedZoneName: AZURE_DNS_ZONE
          # Azure Cloud Environment, default to AzurePublicCloud
          environment: AzurePublicCloud

더 알아보기 (Learn more)