了解適用於 Kubernetes 叢集的 Azure 原則 (部分機器翻譯)Understand Azure Policy for Kubernetes clusters

Azure 原則會延伸 Gatekeeper v3 (Open Policy Agent (OPA) 的 許可控制站 Webhook),以集中且一致的方式,對叢集進行大規模的政策實施和保護。Azure Policy extends Gatekeeper v3, an admission controller webhook for Open Policy Agent (OPA), to apply at-scale enforcements and safeguards on your clusters in a centralized, consistent manner. Azure 原則可以從單一位置管理和報告 Kubernetes 叢集的合規性狀態。Azure Policy makes it possible to manage and report on the compliance state of your Kubernetes clusters from one place. 附加元件會制定下列功能:The add-on enacts the following functions:

  • 向 Azure 原則服務確認以了解叢集的原則指派。Checks with Azure Policy service for policy assignments to the cluster.
  • 將原則定義部署至叢集中,作為條件約束範本條件約束自訂資源。Deploys policy definitions into the cluster as constraint template and constraint custom resources.
  • 將稽核和合規性詳細資料回報給 Azure 原則服務。Reports auditing and compliance details back to Azure Policy service.

適用於 Kubernetes 的 Azure 原則支援下列叢集環境:Azure Policy for Kubernetes supports the following cluster environments:

重要

適用于 AKS 引擎和已啟用 Arc 之 Kubernetes 的附加元件現供 預覽The add-ons for AKS Engine and Arc enabled Kubernetes are in preview. 適用于 Kubernetes 的 Azure 原則僅支援 Linux 節點集區和內建原則定義。Azure Policy for Kubernetes only supports Linux node pools and built-in policy definitions. 內建的原則定義位在 Kubernetes 類別中。Built-in policy definitions are in the Kubernetes category. 具有 EnforceOPAConstraintEnforceRegoPolicy 效果的有限預覽原則定義和相關的 Kubernetes 服務 類別已被 取代The limited preview policy definitions with EnforceOPAConstraint and EnforceRegoPolicy effect and the related Kubernetes Service category are deprecated. 相反地,請使用對資源提供者模式進行 auditdeny 的效果 Microsoft.Kubernetes.DataInstead, use the effects audit and deny with Resource Provider mode Microsoft.Kubernetes.Data.

概觀Overview

若要啟用和使用 Azure 原則搭配 Kubernetes 叢集,請採取下列動作:To enable and use Azure Policy with your Kubernetes cluster, take the following actions:

  1. 設定 Kubernetes 叢集並安裝附加元件:Configure your Kubernetes cluster and install the add-on:

    注意

    如需安裝的常見問題,請參閱 疑難排解-Azure 原則附加元件。For common issues with installation, see Troubleshoot - Azure Policy Add-on.

  2. 了解適用於 Kubernetes 的 Azure 原則語言Understand the Azure Policy language for Kubernetes

  3. 將內建定義指派給您的 Kubernetes 叢集Assign a built-in definition to your Kubernetes cluster

  4. 等待驗證Wait for validation

限制Limitations

下列一般限制適用于 Kubernetes 叢集的 Azure 原則附加元件:The following general limitations apply to the Azure Policy Add-on for Kubernetes clusters:

  • Kubernetes 1.14 版或更高版本支援 Kubernetes 的 Azure 原則附加元件。Azure Policy Add-on for Kubernetes is supported on Kubernetes version 1.14 or higher.
  • Kubernetes 的 Azure 原則附加元件只能部署至 Linux 節點集區Azure Policy Add-on for Kubernetes can only be deployed to Linux node pools
  • 僅支援內建原則定義Only built-in policy definitions are supported
  • 每個叢集每個原則的不符合規範記錄數目上限: 500Maximum number of Non-compliant records per policy per cluster: 500
  • 每一訂用帳戶不符合規範的記錄數目上限: 1000000Maximum number of Non-compliant records per subscription: 1 million
  • 不支援在 Azure 原則附加元件之外安裝閘道管理員。Installations of Gatekeeper outside of the Azure Policy Add-on aren't supported. 先卸載先前的閘道管理員安裝所安裝的任何元件,再啟用 Azure 原則附加元件。Uninstall any components installed by a previous Gatekeeper installation before enabling the Azure Policy Add-on.
  • 不符合規範的原因不適用於 Microsoft.Kubernetes.Data 資源提供者模式Reasons for non-compliance aren't available for the Microsoft.Kubernetes.Data Resource Provider mode. 使用 元件詳細資料Use Component details.
  • 資源提供者模式不支援豁免Exemptions aren't supported for Resource Provider modes.

下列限制僅適用于 AKS 的 Azure 原則附加元件:The following limitations apply only to the Azure Policy Add-on for AKS:

  • AKS Pod 安全性原則 和 AKS 的 Azure 原則附加元件無法同時啟用。AKS Pod security policy and the Azure Policy Add-on for AKS can't both be enabled. 如需詳細資訊,請參閱 AKS pod 安全性限制For more information, see AKS pod security limitation.
  • 評估的 Azure 原則附加元件會自動排除命名空間: kube-system閘道管理員系統aks-periscopeNamespaces automatically excluded by Azure Policy Add-on for evaluation: kube-system, gatekeeper-system, and aks-periscope.

建議Recommendations

以下是使用 Azure 原則附加元件的一般建議:The following are general recommendations for using the Azure Policy Add-on:

  • Azure 原則附加元件需要執行三個閘道管理員元件:1個 audit pod 和2個 webhook pod 複本。The Azure Policy Add-on requires three Gatekeeper components to run: 1 audit pod and 2 webhook pod replicas. 這些元件耗用更多資源,因為叢集中的 Kubernetes 資源和原則指派的計數會增加,因此需要進行審核和強制操作。These components consume more resources as the count of Kubernetes resources and policy assignments increases in the cluster, which requires audit and enforcement operations.

    • 針對單一叢集中小於500的 pod,最多可有20個條件約束:每個元件2個 vcpu 和 350 MB 的記憶體。For fewer than 500 pods in a single cluster with a max of 20 constraints: 2 vCPUs and 350 MB memory per component.
    • 在單一叢集中,有500個以上的 pod,最大為40限制:每個元件3個 vcpu 和 600 MB 的記憶體。For more than 500 pods in a single cluster with a max of 40 constraints: 3 vCPUs and 600 MB memory per component.
  • Windows pod 不支援安全性內容。Windows pods don't support security contexts. 因此,某些 Azure 原則定義(例如不允許根許可權)無法在 Windows pod 中提升,而且只適用于 Linux pod。Thus, some of the Azure Policy definitions, such as disallowing root privileges, can't be escalated in Windows pods and only apply to Linux pods.

下列建議僅適用于 AKS 和 Azure 原則附加元件:The following recommendation applies only to AKS and the Azure Policy Add-on:

  • 使用具有污點的系統節點集區 CriticalAddonsOnly 來排程閘道管理員。Use system node pool with CriticalAddonsOnly taint to schedule Gatekeeper pods. 如需詳細資訊,請參閱 使用系統節點集區。For more information, see Using system node pools.
  • 保護來自 AKS 叢集的輸出流量。Secure outbound traffic from your AKS clusters. 如需詳細資訊,請參閱 控制叢集節點的輸出流量For more information, see Control egress traffic for cluster nodes.
  • 如果叢集已 aad-pod-identity 啟用,節點受控身分識別 (NMI) pod 會修改節點的 iptables,以攔截對 Azure 實例中繼資料端點的呼叫。If the cluster has aad-pod-identity enabled, Node Managed Identity (NMI) pods modify the nodes' iptables to intercept calls to the Azure Instance Metadata endpoint. 這項設定表示即使 pod 不使用,對中繼資料端點所提出的任何要求都會被 NMI 攔截 aad-pod-identityThis configuration means any request made to the Metadata endpoint is intercepted by NMI even if the pod doesn't use aad-pod-identity. 您可以設定 AzurePodIdentityException .CRD,以通知 aad-pod-identity 來自符合 .crd 中所定義標籤之中繼資料端點的任何要求,都應該是 proxy,而不需要在 NMI 中處理。AzurePodIdentityException CRD can be configured to inform aad-pod-identity that any requests to the Metadata endpoint originating from a pod that matches labels defined in CRD should be proxied without any processing in NMI. kubernetes.azure.com/managedby: aks kube 系統命名空間中具有標籤的系統 pod,應設定 aad-pod-identity AzurePodIdentityException .crd 來排除。The system pods with kubernetes.azure.com/managedby: aks label in kube-system namespace should be excluded in aad-pod-identity by configuring the AzurePodIdentityException CRD. 如需詳細資訊,請參閱 停用 aad-pod-特定 pod 或應用程式的身分識別。For more information, see Disable aad-pod-identity for a specific pod or application. 若要設定例外狀況,請安裝 mic 例外狀況 YAMLTo configure an exception, install the mic-exception YAML.

安裝 AKS 的 Azure 原則附加元件Install Azure Policy Add-on for AKS

在安裝 Azure 原則附加元件或啟用任何服務功能之前,您的訂用帳戶必須啟用 microsoft.policyinsights 資源提供者。Before installing the Azure Policy Add-on or enabling any of the service features, your subscription must enable the Microsoft.PolicyInsights resource providers.

  1. 您需要安裝並設定 Azure CLI 2.12.0 版或更新版本。You need the Azure CLI version 2.12.0 or later installed and configured. 執行 az --version 以尋找版本。Run az --version to find the version. 如果您需要安裝或升級,請參閱安裝 Azure CLIIf you need to install or upgrade, see Install the Azure CLI.

  2. 註冊資源提供者和預覽功能。Register the resource providers and preview features.

    • Azure 入口網站:Azure portal:

      註冊 microsoft.policyinsights 資源提供者。Register the Microsoft.PolicyInsights resource providers. 如需相關步驟,請參閱資源提供者和類型For steps, see Resource providers and types.

    • Azure CLI:Azure CLI:

      # Log in first with az login if you're not using Cloud Shell
      
      # Provider register: Register the Azure Policy provider
      az provider register --namespace Microsoft.PolicyInsights
      
  3. 如果已安裝有限的預覽原則定義,請在 [原則] 頁面下的 AKS 叢集上,使用 [ 用] 按鈕移除附加元件。If limited preview policy definitions were installed, remove the add-on with the Disable button on your AKS cluster under the Policies page.

  4. AKS 叢集必須是 1.14 版或更新版本。The AKS cluster must be version 1.14 or higher. 使用下列指令碼來驗證您的 AKS 叢集版本:Use the following script to validate your AKS cluster version:

    # Log in first with az login if you're not using Cloud Shell
    
    # Look for the value in kubernetesVersion
    az aks list
    
  5. 安裝版本 2.12.0 或更高版本的 Azure CLI。Install version 2.12.0 or higher of the Azure CLI. 如需詳細資訊,請參閱 安裝 Azure CLIFor more information, see Install the Azure CLI.

完成上述先決條件步驟後,請在您想要管理的 AKS 叢集中安裝 Azure 原則附加元件。Once the above prerequisite steps are completed, install the Azure Policy Add-on in the AKS cluster you want to manage.

  • Azure 入口網站Azure portal

    1. 選取 [ 所有服務],然後搜尋並選取 [ Kubernetes 服務],以啟動 Azure 入口網站中的 AKS 服務。Launch the AKS service in the Azure portal by selecting All services, then searching for and selecting Kubernetes services.

    2. 選取您的其中一個 AKS 叢集。Select one of your AKS clusters.

    3. 選取 [Kubernetes 服務] 頁面左側的 [ 原則 ]。Select Policies on the left side of the Kubernetes service page.

    4. 在主頁面中,選取 [啟用附加元件] 按鈕。In the main page, select the Enable add-on button.

      注意

      如果 [ 停用附加 元件] 按鈕已啟用,且顯示「遷移警告 v2」訊息,則會安裝 v1 附加元件,並在指派 v2 原則定義之前,必須先將其移除。If the Disable add-on button is enabled and a migration warning v2 message is displayed, v1 add-on is installed and must be removed prior to assigning v2 policy definitions. 淘汰 的 v1 附加元件將會在8月24日起,自動取代為 v2 附加元件The deprecated v1 add-on will automatically be replaced with the v2 add-on starting August 24, 2020. 接著,必須指派原則定義的新 v2 版本。New v2 versions of the policy definitions must then be assigned. 若要立即升級,請遵循下列步驟:To upgrade now, follow these steps:

      1. 造訪 AKS 叢集上的 [ 原則 ] 頁面,並將 [目前的叢集使用 Azure 原則附加元件 v1 ...],以驗證您的 AKS 叢集是否已安裝 v1 附加元件消息。Validate your AKS cluster has the v1 add-on installed by visiting the Policies page on your AKS cluster and has the "The current cluster uses Azure Policy add-on v1..." message.
      2. 移除附加元件。Remove the add-on.
      3. 選取 [ 啟用附加 元件] 按鈕以安裝 v2 版本的附加元件。Select the Enable add-on button to install the v2 version of the add-on.
      4. 指派 v1 內建原則定義的 v2 版本Assign v2 versions of your v1 built-in policy definitions
  • Azure CLIAzure CLI

    # Log in first with az login if you're not using Cloud Shell
    
    az aks enable-addons --addons azure-policy --name MyAKSCluster --resource-group MyResourceGroup
    

若要驗證附加元件安裝是否成功,以及 azure-policygatekeeper Pod 是否正在執行,請執行下列命令:To validate that the add-on installation was successful and that the azure-policy and gatekeeper pods are running, run the following command:

# azure-policy pod is installed in kube-system namespace
kubectl get pods -n kube-system

# gatekeeper pod is installed in gatekeeper-system namespace
kubectl get pods -n gatekeeper-system

最後,請執行此 Azure CLI 命令,並將 <rg> 取代為您的資源群組名稱,然後將 <cluster-name> 取代為您的 AKS 叢集名稱:az aks show --query addonProfiles.azurepolicy -g <rg> -n <cluster-name>,以確認是否已安裝最新的附加元件。Lastly, verify that the latest add-on is installed by running this Azure CLI command, replacing <rg> with your resource group name and <cluster-name> with the name of your AKS cluster: az aks show --query addonProfiles.azurepolicy -g <rg> -n <cluster-name>. 結果看起來應該會類似下列輸出,且 config.version 應為 v2The result should look similar to the following output and config.version should be v2:

"addonProfiles": {
    "azurepolicy": {
        "config": {
            "version": "v2"
        },
        "enabled": true,
        "identity": null
    },
}

針對已啟用 Azure Arc 的 Kubernetes 安裝 Azure 原則附加元件 (preview) Install Azure Policy Add-on for Azure Arc enabled Kubernetes (preview)

在安裝 Azure 原則附加元件或啟用任何服務功能之前,您的訂用帳戶必須啟用 Microsoft.PolicyInsights 資源提供者,並建立叢集服務主體的角色指派。Before installing the Azure Policy Add-on or enabling any of the service features, your subscription must enable the Microsoft.PolicyInsights resource provider and create a role assignment for the cluster service principal.

  1. 您需要安裝並設定 Azure CLI 2.12.0 版或更新版本。You need the Azure CLI version 2.12.0 or later installed and configured. 執行 az --version 以尋找版本。Run az --version to find the version. 如果您需要安裝或升級,請參閱安裝 Azure CLIIf you need to install or upgrade, see Install the Azure CLI.

  2. 若要啟用資源提供者,請遵循資源提供者和類型中的步驟,或執行 Azure CLI 或 Azure PowerShell 命令:To enable the resource provider, follow the steps in Resource providers and types or run either the Azure CLI or Azure PowerShell command:

    • Azure CLIAzure CLI

      # Log in first with az login if you're not using Cloud Shell
      
      # Provider register: Register the Azure Policy provider
      az provider register --namespace 'Microsoft.PolicyInsights'
      
    • Azure PowerShellAzure PowerShell

      # Log in first with Connect-AzAccount if you're not using Cloud Shell
      
      # Provider register: Register the Azure Policy provider
      Register-AzResourceProvider -ProviderNamespace 'Microsoft.PolicyInsights'
      
  3. Kubernetes 叢集必須是 1.14 版或更新版本。The Kubernetes cluster must be version 1.14 or higher.

  4. 安裝 Helm 3Install Helm 3.

  5. 您的 Kubernetes 叢集已針對 Azure Arc 啟用。如需詳細資訊,請參閱將 Kubernetes 叢集上架至 Azure ArcYour Kubernetes cluster enabled for Azure Arc. For more information, see onboarding a Kubernetes cluster to Azure Arc.

  6. 具備已啟用 Azure Arc 的 Kubernetes 叢集之完整 Azure 資源識別碼。Have the fully qualified Azure Resource ID of the Azure Arc enabled Kubernetes cluster.

  7. 開啟附加元件的連接埠。Open ports for the add-on. Azure 原則附加元件會使用這些網域和連接埠擷取原則定義和指派,並將叢集的合規性回報給 Azure 原則。The Azure Policy Add-on uses these domains and ports to fetch policy definitions and assignments and report compliance of the cluster back to Azure Policy.

    網域Domain 連接埠Port
    gov-prod-policy-data.trafficmanager.net 443
    raw.githubusercontent.com 443
    login.windows.net 443
    dc.services.visualstudio.com 443
  8. 將「原則見解資料寫入者 (預覽)」角色指派指派給已啟用 Azure Arc 的 Kubernetes 叢集。Assign 'Policy Insights Data Writer (Preview)' role assignment to the Azure Arc enabled Kubernetes cluster. <subscriptionId> 取代為您的訂用帳戶識別碼、<rg> 取代為已啟用 Azure Arc 的 Kubernetes 叢集的資源群組,並將 <clusterName> 取代為啟用 Azure Arc 的 Kubernetes 叢集名稱。Replace <subscriptionId> with your subscription ID, <rg> with the Azure Arc enabled Kubernetes cluster's resource group, and <clusterName> with the name of the Azure Arc enabled Kubernetes cluster. 針對安裝步驟,追蹤 appIdpasswordtenant 的傳回值。Keep track of the returned values for appId, password, and tenant for the installation steps.

    • Azure CLIAzure CLI

      az ad sp create-for-rbac --role "Policy Insights Data Writer (Preview)" --scopes "/subscriptions/<subscriptionId>/resourceGroups/<rg>/providers/Microsoft.Kubernetes/connectedClusters/<clusterName>"
      
    • Azure PowerShellAzure PowerShell

      $sp = New-AzADServicePrincipal -Role "Policy Insights Data Writer (Preview)" -Scope "/subscriptions/<subscriptionId>/resourceGroups/<rg>/providers/Microsoft.Kubernetes/connectedClusters/<clusterName>"
      
      @{ appId=$sp.ApplicationId;password=[System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($sp.Secret));tenant=(Get-AzContext).Tenant.Id } | ConvertTo-Json
      

    上述命令的範例輸出:Sample output of the above commands:

    {
        "appId": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa",
        "password": "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb",
        "tenant": "cccccccc-cccc-cccc-cccc-cccccccccccc"
    }
    

完成上述先決條件步驟後,請在已啟用 Azure Arc 的 Kubernetes 叢集中安裝 Azure 原則附加元件:Once the above prerequisite steps are completed, install the Azure Policy Add-on in your Azure Arc enabled Kubernetes cluster:

  1. 將 Azure 原則附加元件存放庫新增至 Helm:Add the Azure Policy Add-on repo to Helm:

    helm repo add azure-policy https://raw.githubusercontent.com/Azure/azure-policy/master/extensions/policy-addon-kubernetes/helm-charts
    
  2. 使用 Helm Chart 安裝 Azure 原則附加元件:Install the Azure Policy Add-on using Helm Chart:

    # In below command, replace the following values with those gathered above.
    #    <AzureArcClusterResourceId> with your Azure Arc enabled Kubernetes cluster resource Id. For example: /subscriptions/<subscriptionId>/resourceGroups/<rg>/providers/Microsoft.Kubernetes/connectedClusters/<clusterName>
    #    <ServicePrincipalAppId> with app Id of the service principal created during prerequisites.
    #    <ServicePrincipalPassword> with password of the service principal created during prerequisites.
    #    <ServicePrincipalTenantId> with tenant of the service principal created during prerequisites.
    helm install azure-policy-addon azure-policy/azure-policy-addon-arc-clusters \
        --set azurepolicy.env.resourceid=<AzureArcClusterResourceId> \
        --set azurepolicy.env.clientid=<ServicePrincipalAppId> \
        --set azurepolicy.env.clientsecret=<ServicePrincipalPassword> \
        --set azurepolicy.env.tenantid=<ServicePrincipalTenantId>
    

    如需有關 Helm Chart 會安裝哪些附加元件的詳細資訊,請參閱 GitHub 上的 Azure 原則附加元件 Helm Chart 定義For more information about what the add-on Helm Chart installs, see the Azure Policy Add-on Helm Chart definition on GitHub.

若要驗證附加元件安裝是否成功,以及 azure-policygatekeeper Pod 是否正在執行,請執行下列命令:To validate that the add-on installation was successful and that the azure-policy and gatekeeper pods are running, run the following command:

# azure-policy pod is installed in kube-system namespace
kubectl get pods -n kube-system

# gatekeeper pod is installed in gatekeeper-system namespace
kubectl get pods -n gatekeeper-system

安裝適用于 AKS Engine (preview 的 Azure 原則附加元件) Install Azure Policy Add-on for AKS Engine (preview)

在安裝 Azure 原則附加元件或啟用任何服務功能之前,您的訂用帳戶必須啟用 Microsoft.PolicyInsights 資源提供者,並建立叢集服務主體的角色指派。Before installing the Azure Policy Add-on or enabling any of the service features, your subscription must enable the Microsoft.PolicyInsights resource provider and create a role assignment for the cluster service principal.

  1. 您必須安裝並設定 Azure CLI 2.0.62 版或更新版本。You need the Azure CLI version 2.0.62 or later installed and configured. 執行 az --version 以尋找版本。Run az --version to find the version. 如果您需要安裝或升級,請參閱安裝 Azure CLIIf you need to install or upgrade, see Install the Azure CLI.

  2. 若要啟用資源提供者,請遵循資源提供者和類型中的步驟,或執行 Azure CLI 或 Azure PowerShell 命令:To enable the resource provider, follow the steps in Resource providers and types or run either the Azure CLI or Azure PowerShell command:

    • Azure CLIAzure CLI

      # Log in first with az login if you're not using Cloud Shell
      
      # Provider register: Register the Azure Policy provider
      az provider register --namespace 'Microsoft.PolicyInsights'
      
    • Azure PowerShellAzure PowerShell

      # Log in first with Connect-AzAccount if you're not using Cloud Shell
      
      # Provider register: Register the Azure Policy provider
      Register-AzResourceProvider -ProviderNamespace 'Microsoft.PolicyInsights'
      
  3. 建立叢集服務主體的角色指派。Create a role assignment for the cluster service principal.

    • 如果您不知道叢集服務主體的應用程式識別碼,請使用下列命令來查閱。If you don't know the cluster service principal app ID, look it up with the following command.

      # Get the kube-apiserver pod name
      kubectl get pods -n kube-system
      
      # Find the aadClientID value
      kubectl exec <kube-apiserver pod name> -n kube-system cat /etc/kubernetes/azure.json
      
    • 使用 Azure CLI,對叢集服務主體的應用程式識別碼 (上一個步驟中的 aadClientID) 指派「原則見解資料寫入者 (預覽)」角色指派。Assign 'Policy Insights Data Writer (Preview)' role assignment to the cluster service principal app ID (value aadClientID from previous step) with Azure CLI. <subscriptionId> 取代為您的訂用帳戶識別碼,並將 <aks engine cluster resource group> 取代為 AKS 引擎自我管理 Kubernetes 叢集所在的資源群組。Replace <subscriptionId> with your subscription ID and <aks engine cluster resource group> with the resource group the AKS Engine self-managed Kubernetes cluster is in.

      az role assignment create --assignee <cluster service principal app ID> --scope "/subscriptions/<subscriptionId>/resourceGroups/<aks engine cluster resource group>" --role "Policy Insights Data Writer (Preview)"
      

完成上述先決條件步驟後,安裝 Azure 原則附加元件。Once the above prerequisite steps are completed, install the Azure Policy Add-on. 安裝可以在 AKS 引擎建立或更新週期期間進行,或是在現有叢集上作為獨立動作來進行。The installation can be during the creation or update cycle of an AKS Engine or as an independent action on an existing cluster.

  • 在建立或更新循環期間安裝Install during creation or update cycle

    若要在建立新的自我管理叢集或更新現有叢集時啟用 Azure 原則附加元件,請包含 AKS 引擎的附加元件屬性叢集定義。To enable the Azure Policy Add-on during the creation of a new self-managed cluster or as an update to an existing cluster, include the addons property cluster definition for AKS Engine.

    "addons": [{
        "name": "azure-policy",
        "enabled": true
    }]
    

    如需相關詳細資訊,請參閱 AKS 引擎叢集定義的外部指南。For more information about, see the external guide AKS Engine cluster definition.

  • 使用 Helm Chart 在現有叢集中進行安裝Install in existing cluster with Helm Charts

    使用下列步驟來準備叢集並安裝附加元件:Use the following steps to prepare the cluster and install the add-on:

    1. 安裝 Helm 3Install Helm 3.

    2. 將 Azure 原則存放庫新增至 Helm。Add the Azure Policy repo to Helm.

      helm repo add azure-policy https://raw.githubusercontent.com/Azure/azure-policy/master/extensions/policy-addon-kubernetes/helm-charts
      

      如需詳細資訊,請參閱 Helm Chart - 快速入門指南For more information, see Helm Chart - Quickstart Guide.

    3. 以 Helm Chart 安裝附加元件。Install the add-on with a Helm Chart. <subscriptionId> 取代為您的訂用帳戶識別碼,並將 <aks engine cluster resource group> 取代為 AKS 引擎自我管理 Kubernetes 叢集所在的資源群組。Replace <subscriptionId> with your subscription ID and <aks engine cluster resource group> with the resource group the AKS Engine self-managed Kubernetes cluster is in.

      helm install azure-policy-addon azure-policy/azure-policy-addon-aks-engine --set azurepolicy.env.resourceid="/subscriptions/<subscriptionId>/resourceGroups/<aks engine cluster resource group>"
      

      如需有關 Helm Chart 會安裝哪些項目的詳細資訊,請參閱 GitHub 上的 Azure 原則附加元件 Helm Chart 定義For more information about what the add-on Helm Chart installs, see the Azure Policy Add-on Helm Chart definition on GitHub.

      注意

      由於 Azure 原則附加元件與資源群組識別碼之間的關聯性,Azure 原則每個資源群組只支援一個 AKS 引擎叢集。Because of the relationship between Azure Policy Add-on and the resource group ID, Azure Policy supports only one AKS Engine cluster for each resource group.

若要驗證附加元件安裝是否成功,以及 azure-policygatekeeper Pod 是否正在執行,請執行下列命令:To validate that the add-on installation was successful and that the azure-policy and gatekeeper pods are running, run the following command:

# azure-policy pod is installed in kube-system namespace
kubectl get pods -n kube-system

# gatekeeper pod is installed in gatekeeper-system namespace
kubectl get pods -n gatekeeper-system

原則語言Policy language

用於管理 Kubernetes 的 Azure 原則語言結構會遵循現有原則定義的結構。The Azure Policy language structure for managing Kubernetes follows that of existing policy definitions. 使用的 資源提供者模式 Microsoft.Kubernetes.Data ,會使用 auditDeny 效果來管理您的 Kubernetes 叢集。With a Resource Provider mode of Microsoft.Kubernetes.Data, the effects audit and deny are used to manage your Kubernetes clusters. Auditdeny 必須提供使用 OPA 條件約束架構和閘道管理員 v3 的特定 詳細資料 屬性。Audit and deny must provide details properties specific to working with OPA Constraint Framework and Gatekeeper v3.

在原則定義中的 details.constraintTemplatedetails.constraint 屬性中,Azure 原則會將這些 CustomResourceDefinitions (CRD) 的 URI 傳遞至附加元件。As part of the details.constraintTemplate and details.constraint properties in the policy definition, Azure Policy passes the URIs of these CustomResourceDefinitions (CRD) to the add-on. Rego 是 OPA 和 Gatekeeper 向 Kubernetes 叢集驗證要求時的支援語言。Rego is the language that OPA and Gatekeeper support to validate a request to the Kubernetes cluster. 藉由支援現有的 Kubernetes 管理標準,Azure 原則可讓您重複使用現有的規則,並可將其與 Azure 原則結合,以取得統一的雲端合規性報告體驗。By supporting an existing standard for Kubernetes management, Azure Policy makes it possible to reuse existing rules and pair them with Azure Policy for a unified cloud compliance reporting experience. 如需詳細資訊,請參閱什麼是 Rego?For more information, see What is Rego?.

指派內建原則定義Assign a built-in policy definition

若要將原則定義指派給您的 Kubernetes 叢集,您必須將適當的 Azure 角色型存取控制指派給您 (Azure RBAC) 原則指派作業。To assign a policy definition to your Kubernetes cluster, you must be assigned the appropriate Azure role-based access control (Azure RBAC) policy assignment operations. Azure 內建角色的 資源原則參與者擁有 者具有這些作業。The Azure built-in roles Resource Policy Contributor and Owner have these operations. 若要深入瞭解,請參閱 Azure 原則中的 AZURE RBAC 許可權To learn more, see Azure RBAC permissions in Azure Policy.

使用 Azure 入口網站搭配下列步驟,尋找用於管理叢集的內建原則定義:Find the built-in policy definitions for managing your cluster using the Azure portal with the following steps:

  1. 在 Azure 入口網站中啟動 Azure 原則服務。Start the Azure Policy service in the Azure portal. 在左側窗格中選取 [所有服務],然後搜尋並選取 [原則]。Select All services in the left pane and then search for and select Policy.

  2. 在 [Azure 原則] 頁面的左窗格中,選取 [定義]。In the left pane of the Azure Policy page, select Definitions.

  3. 從 [類別] 下拉式清單方塊中,使用 [ 全選 ] 清除篩選,然後選取 [ Kubernetes]。From the Category dropdown list box, use Select all to clear the filter and then select Kubernetes.

  4. 選取原則定義,然後選取 [指派] 按鈕。Select the policy definition, then select the Assign button.

  5. 將 [範圍] 設定為將套用原則指派所在 Kubernetes 叢集的管理群組、訂用帳戶或資源群組。Set the Scope to the management group, subscription, or resource group of the Kubernetes cluster where the policy assignment will apply.

    注意

    指派 Kubernetes 適用的 Azure 原則定義時,範圍 必須包含叢集資源。When assigning the Azure Policy for Kubernetes definition, the Scope must include the cluster resource. 若為 AKS 引擎叢集,範圍 必須是叢集的資源群組。For an AKS Engine cluster, the Scope must be the resource group of the cluster.

  6. 為原則指派賦予 名稱描述,讓您能夠輕鬆識別該原則。Give the policy assignment a Name and Description that you can use to identify it easily.

  7. 強制執行的原則 設定為下列其中一個值。Set the Policy enforcement to one of the values below.

    • 已啟用 - 在叢集上強制執行原則。Enabled - Enforce the policy on the cluster. 具有違規的 Kubernetes 許可要求會遭到拒絕。Kubernetes admission requests with violations are denied.

    • 已停用 - 在叢集上不強制執行原則。Disabled - Don't enforce the policy on the cluster. 具有違規的 Kubernetes 許可要求不會遭到拒絕。Kubernetes admission requests with violations aren't denied. 合規性評估結果仍然可供使用。Compliance assessment results are still available. 將新的原則定義推出到執行中的叢集時,[已停用] 選項有助於測試原則定義,因為具有違規的許可要求不會遭到拒絕。When rolling out new policy definitions to running clusters, Disabled option is helpful for testing the policy definition as admission requests with violations aren't denied.

  8. 選取 [下一步] 。Select Next.

  9. 設定 參數值Set parameter values

    • 若要從原則評估中排除 Kubernetes 命名空間,請在 [命名空間排除] 參數中指定命名空間的清單。To exclude Kubernetes namespaces from policy evaluation, specify the list of namespaces in parameter Namespace exclusions. 建議您排除:kube-systemgatekeeper-systemazure-arcIt's recommended to exclude: kube-system, gatekeeper-system, and azure-arc.
  10. 選取 [檢閱 + 建立]。Select Review + create.

或者,使用指派原則 - 入口網站快速入門來尋找並指派 Kubernetes 原則。Alternately, use the Assign a policy - Portal quickstart to find and assign a Kubernetes policy. 搜尋 Kubernetes 原則定義,而不是 'audit vms' 範例。Search for a Kubernetes policy definition instead of the sample 'audit vms'.

重要

內建原則定義適用於 Kubernetes 類別中的 Kubernetes 叢集。Built-in policy definitions are available for Kubernetes clusters in category Kubernetes. 如需內建原則定義的清單,請參閱 Kubernetes 範例For a list of built-in policy definitions, see Kubernetes samples.

原則評估Policy evaluation

此附加元件會每隔 15 分鐘向 Azure 原則服務檢查原則指派中的變更。The add-on checks in with Azure Policy service for changes in policy assignments every 15 minutes. 在此重新整理週期期間,附加元件會檢查是否有變更。During this refresh cycle, the add-on checks for changes. 這些變更會觸發條件約束範本和條件約束的建立、更新或刪除。These changes trigger creates, updates, or deletes of the constraint templates and constraints.

在 Kubernetes 叢集中,如果命名空間有下列其中一個標籤,則不會拒絕具有違規的許可要求。In a Kubernetes cluster, if a namespace has either of the following labels, the admission requests with violations aren't denied. 合規性評估結果仍然可供使用。Compliance assessment results are still available.

  • control-plane
  • admission.policy.azure.com/ignore

注意

雖然叢集管理員可能具備建立和更新 Azure 原則附加元件所安裝之條件約束範本和條件約束資源的權限,但這些不是支援的案例,因為手動更新會遭到覆寫。While a cluster admin may have permission to create and update constraint templates and constraints resources install by the Azure Policy Add-on, these aren't supported scenarios as manual updates are overwritten. Gatekeeper 會繼續評估安裝附加元件並指派 Azure 原則的原則定義之前已存在的原則。Gatekeeper continues to evaluate policies that existed prior to installing the add-on and assigning Azure Policy policy definitions.

每隔 15 分鐘,附加元件就會呼叫叢集的完整掃描。Every 15 minutes, the add-on calls for a full scan of the cluster. 在收集完整掃描的詳細資料以及嘗試變更叢集的任何即時評估 (由 Gatekeeper 執行) 之後,此附加元件會將結果回報給 Azure 原則以納入合規性詳細資料,例如任何 Azure 原則指派。After gathering details of the full scan and any real-time evaluations by Gatekeeper of attempted changes to the cluster, the add-on reports the results back to Azure Policy for inclusion in compliance details like any Azure Policy assignment. 在稽核週期期間,只會傳回作用中原則指派的結果。Only results for active policy assignments are returned during the audit cycle. 稽核結果也可以視為失敗條件約束 [狀態] 欄位中所列的違規Audit results can also be seen as violations listed in the status field of the failed constraint. 如需 不符合規範 之資源的詳細資訊,請參閱 資源提供者模式的元件詳細資料For details on Non-compliant resources, see Component details for Resource Provider modes.

注意

在 Kubernetes 叢集 Azure 原則中,每個合規性報告都包含過去 45 分鐘內的所有違規。Each compliance report in Azure Policy for your Kubernetes clusters include all violations within the last 45 minutes. 時間戳記會指出違規發生的時間。The timestamp indicates when a violation occurred.

其他考慮事項:Some other considerations:

  • 如果叢集訂用帳戶已向 Azure 資訊安全中心登錄,則會自動在叢集上套用 Azure 資訊安全中心 Kubernetes 原則。If the cluster subscription is registered with Azure Security Center, then Azure Security Center Kubernetes policies are applied on the cluster automatically.

  • 在具有現有 Kubernetes 資源的叢集上套用拒絕原則時,任何與新原則不相容的預先存在資源都會繼續執行。When a deny policy is applied on cluster with existing Kubernetes resources, any pre-existing resource that is not compliant with the new policy continues to run. 當不符合規範的資源在不同的節點上重新排程時,閘道管理員會封鎖資源的建立。When the non-compliant resource gets rescheduled on a different node the Gatekeeper blocks the resource creation.

  • 當叢集具有可驗證資源的拒絕原則時,使用者將不會在建立部署時看到拒絕訊息。When a cluster has a deny policy that validates resources, the user will not see a rejection message when creating a deployment. 例如,請考慮包含 replicaset 和 pod 的 Kubernetes 部署。For example, consider a Kubernetes deployment that contains replicasets and pods. 當使用者執行時 kubectl describe deployment $MY_DEPLOYMENT ,它不會傳回拒絕訊息作為事件的一部分。When a user executes kubectl describe deployment $MY_DEPLOYMENT, it does not return a rejection message as part of events. 但是,會傳回 kubectl describe replicasets.apps $MY_DEPLOYMENT 與拒絕相關聯的事件。However, kubectl describe replicasets.apps $MY_DEPLOYMENT returns the events associated with rejection.

記錄Logging

作為 Kubernetes 控制器/容器, azure 原則閘道管理員 pod 都會將記錄保留在 Kubernetes 叢集中。As a Kubernetes controller/container, both the azure-policy and gatekeeper pods keep logs in the Kubernetes cluster. 記錄可以在 Kubernetes 叢集的 [見解] 頁面中公開。The logs can be exposed in the Insights page of the Kubernetes cluster. 如需詳細資訊,請參閱使用適用於容器的 Azure 監視器來監視您的 Kubernetes 叢集效能For more information, see Monitor your Kubernetes cluster performance with Azure Monitor for containers.

若要檢視附加元件記錄,請使用 kubectlTo view the add-on logs, use kubectl:

# Get the azure-policy pod name installed in kube-system namespace
kubectl logs <azure-policy pod name> -n kube-system

# Get the gatekeeper pod name installed in gatekeeper-system namespace
kubectl logs <gatekeeper pod name> -n gatekeeper-system

如需詳細資訊,請參閱 Gatekeeper 文件中的 Gatekeeper 偵錯For more information, see Debugging Gatekeeper in the Gatekeeper documentation.

針對附加元件進行疑難排解Troubleshooting the add-on

如需 Kubernetes 的附加元件疑難排解的詳細資訊,請參閱 Azure 原則疑難排解文章中的 Kubernetes 一節For more information about troubleshooting the Add-on for Kubernetes, see the Kubernetes section of the Azure Policy troubleshooting article.

移除附加元件Remove the add-on

從 AKS 移除附加元件Remove the add-on from AKS

若要從 AKS 叢集中移除 Azure 原則附加元件,請使用 Azure 入口網站或 Azure CLI:To remove the Azure Policy Add-on from your AKS cluster, use either the Azure portal or Azure CLI:

  • Azure 入口網站Azure portal

    1. 選取 [ 所有服務],然後搜尋並選取 [ Kubernetes 服務],以啟動 Azure 入口網站中的 AKS 服務。Launch the AKS service in the Azure portal by selecting All services, then searching for and selecting Kubernetes services.

    2. 選取您想要停用 Azure 原則附加元件的 AKS 叢集。Select your AKS cluster where you want to disable the Azure Policy Add-on.

    3. 選取 [Kubernetes 服務] 頁面左側的 [ 原則 ]。Select Policies on the left side of the Kubernetes service page.

    4. 在主頁面中,選取 [停用附加元件] 按鈕。In the main page, select the Disable add-on button.

  • Azure CLIAzure CLI

    # Log in first with az login if you're not using Cloud Shell
    
    az aks disable-addons --addons azure-policy --name MyAKSCluster --resource-group MyResourceGroup
    

從已啟用 Azure Arc 的 Kubernetes 中移除附加元件Remove the add-on from Azure Arc enabled Kubernetes

若要從已啟用 Azure Arc 的 Kubernetes 叢集中移除 Azure 原則附加元件和 Gatekeeper,請執行下列 Helm 命令:To remove the Azure Policy Add-on and Gatekeeper from your Azure Arc enabled Kubernetes cluster, run the following Helm command:

helm uninstall azure-policy-addon

從 AKS 引擎移除附加元件Remove the add-on from AKS Engine

若要從 AKS 引擎叢集中移除 Azure 原則附加元件和 Gatekeeper,請使用與安裝附加元件時一致的方法:To remove the Azure Policy Add-on and Gatekeeper from your AKS Engine cluster, use the method that aligns with how the add-on was installed:

  • 如果您藉由在 AKS 引擎的叢集定義中設定 addons 屬性來進行安裝:If installed by setting the addons property in the cluster definition for AKS Engine:

    azure-policyaddons 屬性變更為 false 之後,將叢集定義重新部署至 AKS 引擎:Redeploy the cluster definition to AKS Engine after changing the addons property for azure-policy to false:

    "addons": [{
        "name": "azure-policy",
        "enabled": false
    }]
    

    如需詳細資訊,請參閱 AKS 引擎 - 停用 Azure 原則附加元件 (英文)。For more information, see AKS Engine - Disable Azure Policy Add-on.

  • 如果使用 Helm Charts 安裝,請執行下列 Helm 命令:If installed with Helm Charts, run the following Helm command:

    helm uninstall azure-policy-addon
    

Azure 原則附加元件所收集的診斷資料Diagnostic data collected by Azure Policy Add-on

適用於 Kubernetes 的 Azure 原則附加元件會收集有限的叢集診斷資料。The Azure Policy Add-on for Kubernetes collects limited cluster diagnostic data. 此診斷資料是與軟體和效能相關的重要技術資料。This diagnostic data is vital technical data related to software and performance. 其使用方式如下:It's used in the following ways:

  • 讓 Azure 原則附加元件保持在最新狀態Keep Azure Policy Add-on up to date
  • 確保 Azure 原則附加元件安全、可靠、高效能Keep Azure Policy Add-on secure, reliable, performant
  • 改善 Azure 原則附加元件 - 透過使用附加元件時的彙總分析Improve Azure Policy Add-on - through the aggregate analysis of the use of the add-on

附加元件所收集的資訊不是個人資料。The information collected by the add-on isn't personal data. 目前會收集下列詳細資料:The following details are currently collected:

  • Azure 原則附加元件代理程式版本Azure Policy Add-on agent version
  • 叢集類型Cluster type
  • 叢集區域Cluster region
  • 叢集資源群組Cluster resource group
  • 叢集資源識別碼Cluster resource ID
  • 叢集訂用帳戶識別碼Cluster subscription ID
  • 叢集作業系統 (範例:LINUX)Cluster OS (Example: Linux)
  • 叢集城市 (例如:西雅圖)Cluster city (Example: Seattle)
  • 叢集的州或省 (例如:華盛頓州)Cluster state or province (Example: Washington)
  • 叢集的國家或地區 (例如:美國)Cluster country or region (Example: United States)
  • 在原則評估上安裝代理程式期間,Azure 原則附加元件所遇到的例外狀況/錯誤Exceptions/errors encountered by Azure Policy Add-on during agent installation on policy evaluation
  • Azure 原則附加元件未安裝的 Gatekeeper 原則定義數目Number of Gatekeeper policy definitions not installed by Azure Policy Add-on

後續步驟Next steps