在名稱空間級別應用 Pod 安全標準
注意
本教程僅適用於新叢集。Pod Security Admission 是一個准入控制器,用於在建立 Pod 時應用 Pod 安全標準。它是一個在 v1.25 中 GA 的特性。在本教程中,你將一次一個名稱空間地強制執行 baseline
Pod 安全標準。
你還可以在叢集級別一次性對多個名稱空間應用 Pod 安全標準。有關說明,請參閱 在叢集級別應用 Pod 安全標準。
準備工作
在你的工作站上安裝以下內容
建立叢集
按如下方式建立一個
kind
叢集kind create cluster --name psa-ns-level
輸出類似於:
Creating cluster "psa-ns-level" ... ✓ Ensuring node image (kindest/node:v1.34.0) 🖼 ✓ Preparing nodes 📦 ✓ Writing configuration 📜 ✓ Starting control-plane 🕹️ ✓ Installing CNI 🔌 ✓ Installing StorageClass 💾 Set kubectl context to "kind-psa-ns-level" You can now use your cluster with: kubectl cluster-info --context kind-psa-ns-level Not sure what to do next? 😅 Check out https://kind.sigs.k8s.io/docs/user/quick-start/
將 kubectl 上下文設定為新叢集
kubectl cluster-info --context kind-psa-ns-level
輸出類似於:
Kubernetes control plane is running at https://127.0.0.1:50996 CoreDNS is running at https://127.0.0.1:50996/api/v1/namespaces/kube-system/services/kube-dns:dns/proxy To further debug and diagnose cluster problems, use 'kubectl cluster-info dump'.
建立名稱空間
建立一個名為 example
的新名稱空間
kubectl create ns example
輸出類似於:
namespace/example created
啟用該名稱空間的 Pod 安全標準檢查
使用內建 Pod 安全准入支援的標籤在該名稱空間上啟用 Pod 安全標準。在此步驟中,你將配置一個檢查,以對不符合最新版 baseline Pod 安全標準的 Pod 發出警告。
kubectl label --overwrite ns example \ pod-security.kubernetes.io/warn=baseline \ pod-security.kubernetes.io/warn-version=latest
你可以使用標籤在任何名稱空間上配置多個 Pod 安全標準檢查。以下命令將
enforce
baseline
Pod 安全標準,但會根據最新版本(預設值)對restricted
Pod 安全標準發出warn
和audit
警告。kubectl label --overwrite ns example \ pod-security.kubernetes.io/enforce=baseline \ pod-security.kubernetes.io/enforce-version=latest \ pod-security.kubernetes.io/warn=restricted \ pod-security.kubernetes.io/warn-version=latest \ pod-security.kubernetes.io/audit=restricted \ pod-security.kubernetes.io/audit-version=latest
驗證 Pod 安全標準執行
在
example
名稱空間中建立一個 baseline Podkubectl apply -n example -f https://k8s.io/examples/security/example-baseline-pod.yaml
Pod 啟動正常;輸出包含警告。例如
Warning: would violate PodSecurity "restricted:latest": allowPrivilegeEscalation != false (container "nginx" must set securityContext.allowPrivilegeEscalation=false), unrestricted capabilities (container "nginx" must set securityContext.capabilities.drop=["ALL"]), runAsNonRoot != true (pod or container "nginx" must set securityContext.runAsNonRoot=true), seccompProfile (pod or container "nginx" must set securityContext.seccompProfile.type to "RuntimeDefault" or "Localhost") pod/nginx created
在
default
名稱空間中建立一個 baseline Podkubectl apply -n default -f https://k8s.io/examples/security/example-baseline-pod.yaml
輸出類似於此
pod/nginx created
Pod 安全標準的強制執行和警告設定僅應用於 example
名稱空間。你可以在 default
名稱空間中建立相同的 Pod,而不會收到任何警告。
清理
現在透過執行以下命令刪除你上面建立的叢集
kind delete cluster --name psa-ns-level
下一步
執行 shell 指令碼,一次性執行所有上述步驟。
- 建立 Kind 叢集
- 建立新名稱空間
- 以
enforce
模式應用baseline
Pod 安全標準,同時以warn
和audit
模式應用restricted
Pod 安全標準。 - 建立一個應用了以下 Pod 安全標準的新 Pod
上次修改時間:2023 年 11 月 8 日晚上 10:12 PST: 修復英文文件中的 KinD 拼寫錯誤。(ad52e828b5)