使用Bash腳本標記Kubernetes資源


問題描述

有時候,你可能會遇到給各種Kubernetes資源(包括Pods、Deployments、StatefulSets和PersistentVolumeClaims(PVCs))加標籤或者分類的挑戰。因此,你無法針對Volumes執行admission webhooks或AWS Security Control Policies。在Kubernetes資源管理中,標籤起著關鍵性的作用。標籤是附加在Kubernetes資源上的鍵值對,能夠根據各種標準有效地進行分類、組織和資源選擇。它們賦予你向資源添加元數據的能力,從而簡化操作,方便監控和加強訪問控制。

解決方案

你可以編寫一個利用Kubernetes命令行工具的bash腳本。這個解決方案需要實施一種標籤策略,使你能夠有效地分類和標籤你的Kubernetes資源。因此,你可以應用AWS Security Control Policies並更有效地管理你的資源。

為資源標籤的Bash腳本示例

你可以運行一個bash腳本,將標籤應用到命名空間內的Kubernetes資源。以下是一個示例腳本,它遍歷給定命名空間中的Deployments,並使用patch操作應用自訂標籤:

#!/bin/bash
while true; do
    for deployment in $(kubectl -n $namespace get deployment | awk '{print $1}');
    do
        kubectl patch deployment $deployment -n $namespace --patch-file="patch-labels.yaml";
    done;
done

“patch-labels.yaml”的內容可以是:

spec:
  template:
    metadata:
      labels:
        ApplicationID: APP-1234
        Environment: nonprod
        Owner: VictorLeung

一旦所有資源被patched,可以在終端機中按Ctrl + C來終止。

腳本參數說明

  • while true; do: 這啟動一個無窮迴圈,用於持續監控和更新Deployments。
  • kubectl -n $namespace get deployment: 這個命令獲取指定命名空間中的Deployments列表(將”$namespace”替換為合適的命名空間)。
  • for deployment in $(...); do: 此迴圈遍歷從前一個命令獲得的Deployments。
  • kubectl patch deployment $deployment -n $namespace --patch-file="patch-labels.yaml": 此命令對指定的變數$deployment在給定命名空間中的deployment應用patch。patch的內容在 “patch-labels.yaml”中定義。

適用於不同資源類型的改編

此腳本可以通過修改相關命令和目標資源,應用於其他Kubernetes資源類型,如StatefulSets和PVCs。例如,對於StatefulSets:

#!/bin/bash
while true; do
    for sts in $(kubectl -n $namespace get sts | awk '{print $1}');
    do
        kubectl patch sts $sts -n $namespace --patch-files="patch-labels.yaml";
    done;
done

同樣的,對於PVCs:

#!/bin/bash
while true; do
    for pvc in $(kubectl get pvc | awk '{print $1}');
    do
        kubectl patch pvc $pvc --patch-file="patch-labels.yaml";
    done;
done

“patch-labels.yaml”的內容可以是:

metadata:
  labels:
  ApplicationID: APP-1234
  Environment: nonprod
  Owner: VictorLeung

結論

將自訂標籤整合到Kubernetes資源管理中,提供了一種有效的資產標記和分類方案。利用Kubernetes的靈活標籤機制,使你能更好地組織、確保和管理你的資源。通過使用bash腳本,如所示,你可以縮短差距,提升你的整體操作能力,並確保更好的控制你的Kubernetes環境。