Toidicode.com

Toidicode.com

BASIC TO ADVANCE

Bài 7: Label, selector và annotation trong Kubernetes

Ở bài trước hai Pod taskflow-api và taskflow-api-debug có chung một bộ nhãn trong metadata.labels. Bài này mình sẽ giới thiệu với mọi người về label, selector và annotation trong Kubernetes: gắn nhãn cho resource, lọc resource theo nhãn và ghi thông tin không dùng để lọc. Bài dùng lại cụm taskflow, image đã nạp ở Bài 5 và hai file manifest của Bài 6.

1. Label là gì?

Label là cặp key/value gắn vào metadata.labels của một resource để nhận diện và gom nhóm resource đó.

Kubernetes không quan tâm Pod tên gì khi cần tìm một nhóm Pod: Service tìm Pod để chuyển request tới, Deployment đếm xem đã đủ Pod chưa, tất cả đều đi qua label. Apply lại hai Pod của Bài 6 rồi xem label bằng --show-labels:

kubectl apply -f k8s/
# pod/taskflow-api-debug created
# pod/taskflow-api created
kubectl get pods --show-labels
# NAME                 READY   STATUS    RESTARTS   AGE   LABELS
# taskflow-api         1/1     Running   0          6s    app.kubernetes.io/name=taskflow-api,app.kubernetes.io/part-of=taskflow
# taskflow-api-debug   2/2     Running   0          6s    app.kubernetes.io/name=taskflow-api,app.kubernetes.io/part-of=taskflow

Quy tắc đặt key và value

Key có dạng [prefix/]name, ví dụ app.kubernetes.io/name có prefix app.kubernetes.io và name name:

  • name bắt buộc, tối đa 63 ký tự, gồm chữ, số, -, _, ., bắt đầu và kết thúc bằng chữ hoặc số.
  • prefix không bắt buộc, là một tên miền (tối đa 253 ký tự) như toidicode.com. Prefix kubernetes.io/ và k8s.io/ dành cho Kubernetes (apiserver không chặn trên Pod, nhưng label tự đặt nên dùng tên miền của mình).
  • Value tối đa 63 ký tự, cùng bộ ký tự như name, được phép rỗng. Value luôn là chuỗi, nên true hay 1.0 trong YAML phải đặt trong ngoặc kép (lỗi đã gặp ở Bài 4).

Value có dấu cách thì bị từ chối ngay (value 64 ký tự cũng vậy, lỗi must be no more than 63 bytes):

kubectl label pod taskflow-api 'team=nhom api'
# error: invalid label value: "team=nhom api": a valid label must be an empty string or consist of alphanumeric characters, '-', '_' or '.', and must start and end with an alphanumeric character ...

Giới hạn chặt như vậy vì label sinh ra để nhận diện và lọc (apiserver, controller và kubectl chọn resource theo label), không phải để chứa dữ liệu. Thông tin dài hay tự do (mô tả, URL, email) thuộc về annotation ở phần 6.

2. Label chuẩn và quy ước của series.

Kubernetes có một bộ label khuyến nghị với prefix app.kubernetes.io. Dùng chung bộ này thì Helm, Argo CD, dashboard hay công cụ monitoring đều hiểu resource thuộc ứng dụng nào:

  • app.kubernetes.io/name: tên ứng dụng, VD taskflow-api.
  • app.kubernetes.io/component: vai trò trong kiến trúc, VD api.
  • app.kubernetes.io/part-of: hệ thống lớn chứa ứng dụng, VD taskflow.
  • app.kubernetes.io/version: version của ứng dụng, VD "0.53.0".
  • app.kubernetes.io/instance: tên một lần cài đặt, phân biệt nhiều bản của cùng ứng dụng; app.kubernetes.io/managed-by: công cụ quản lý resource. Hai label này Helm tự gắn (Bài 24).

Quy ước của series từ bài này: mọi resource của TaskFlow có name, component và part-of: taskflow; Pod (và template Pod sau này) có thêm version. component cố định cho cả series:

  • taskflow-api → api, taskflow-notifier → notifier (Bài 21).
  • postgres → database, redis → cache (Bài 19).

Thêm hai label vào cả k8s/pod.yaml và k8s/pod-debug.yaml, phần metadata của hai file giống nhau trừ name:

- k8s/pod.yaml

apiVersion: v1
kind: Pod
metadata:
  name: taskflow-api
  labels:
    app.kubernetes.io/name: taskflow-api
    app.kubernetes.io/component: api
    app.kubernetes.io/part-of: taskflow
    app.kubernetes.io/version: "0.53.0"
spec:
  # ... giữ nguyên như Bài 6

version luôn ghi trong ngoặc kép: 0.53.0 không ngoặc vẫn là chuỗi, nhưng 1.0 thì thành số. Apply lại:

kubectl apply -f k8s/
# pod/taskflow-api-debug configured
# pod/taskflow-api configured
kubectl get pods -L app.kubernetes.io/component,app.kubernetes.io/version
# NAME                 READY   STATUS    RESTARTS   AGE   COMPONENT   VERSION
# taskflow-api         1/1     Running   0          32s   api         0.53.0
# taskflow-api-debug   2/2     Running   0          32s   api         0.53.0

Khác với env ở Bài 6, label nằm trong metadata nên sửa tại chỗ được: configured, AGE và RESTARTS giữ nguyên, Pod không bị tạo lại. -L (--label-columns) biến mỗi label thành một cột, gọn hơn --show-labels khi Pod có nhiều label.

3. Thêm, sửa, xóa label với kubectl label.

Lệnh kubectl label TYPE NAME KEY=VALUE thêm label cho resource đang chạy; key đã có thì phải kèm --overwrite, còn KEY- (dấu trừ ở cuối) xóa label. Thay NAME bằng -l SELECTOR hoặc --all để sửa nhiều resource một lúc.

VD: Đánh dấu Pod debug, rồi thử đổi version của Pod chính:

kubectl label pod taskflow-api-debug debug=true
# pod/taskflow-api-debug labeled
kubectl label pod taskflow-api app.kubernetes.io/version=0.54.0
# error: 'app.kubernetes.io/version' already has a value (0.53.0), and --overwrite is false
kubectl label pod taskflow-api app.kubernetes.io/version=0.54.0 --overwrite
# pod/taskflow-api labeled
kubectl get pods -l app.kubernetes.io/name=taskflow-api -L app.kubernetes.io/version,debug
# NAME                 READY   STATUS    RESTARTS   AGE   VERSION   DEBUG
# taskflow-api         1/1     Running   0          64s   0.54.0
# taskflow-api-debug   2/2     Running   0          64s   0.53.0    true

Pod taskflow-api giờ "khai" là 0.54.0 trong khi image vẫn là taskflow-api:0.53.0: Kubernetes không kiểm tra ý nghĩa của label, ghi sai là các công cụ dựa vào nó đọc sai theo. Apply lại file manifest:

kubectl apply -f k8s/pod.yaml
# pod/taskflow-api configured

Chạy lại lệnh get ở trên sẽ thấy version về 0.53.0 vì label này có trong file, còn label debug thêm bằng tay vẫn nằm đó vì file không nhắc tới nó (lý do ở phần 6). Vậy nên kubectl label chỉ dùng để thử nhanh hoặc đánh dấu tạm, label lâu dài thì ghi vào file manifest.

4. Selector trong Kubernetes.

Label selector là điều kiện lọc resource theo label, truyền cho kubectl bằng -l (--selector). Để có gì mà lọc, mình tạo thêm hai Pod tạm: Redis mang label của TaskFlow (Redis thật sẽ chạy bằng Deployment ở Bài 19) và một nginx không label gì:

kubectl run redis --image=redis:8-alpine --labels="app.kubernetes.io/name=redis,app.kubernetes.io/component=cache,app.kubernetes.io/part-of=taskflow"
# pod/redis created
kubectl run nginx --image=nginx:1.31-alpine
# pod/nginx created
kubectl get pods --show-labels
# NAME                 READY   STATUS    RESTARTS   AGE   LABELS
# nginx                1/1     Running   0          13s   run=nginx
# redis                1/1     Running   0          13s   app.kubernetes.io/component=cache,app.kubernetes.io/name=redis,app.kubernetes.io/part-of=taskflow
# ...

kubectl run tự gắn label run=<tên> khi không có --labels.

Equality-based selector

So sánh bằng = (hoặc ==) và !=, nhiều điều kiện cách nhau bằng dấu phẩy và phải thỏa cùng lúc (AND):

kubectl get pods -l app.kubernetes.io/part-of=taskflow
# NAME                 READY   STATUS    RESTARTS   AGE
# redis                1/1     Running   0          47s
# taskflow-api         1/1     Running   0          85s
# taskflow-api-debug   2/2     Running   0          85s
kubectl get pods -l app.kubernetes.io/component!=api
# NAME    READY   STATUS    RESTARTS   AGE
# nginx   1/1     Running   0          47s
# redis   1/1     Running   0          47s

Ghép -l app.kubernetes.io/part-of=taskflow,app.kubernetes.io/component=api thì còn đúng hai Pod TaskFlow API. Để ý nginx cũng khớp component!=api: != chọn cả resource không có key đó.

Set-based selector

Loại này kiểm tra value thuộc một tập hợp, hoặc chỉ kiểm tra key có tồn tại hay không:

kubectl get pods -l 'app.kubernetes.io/component in (api,cache)'
# NAME                 READY   STATUS    RESTARTS   AGE
# redis                1/1     Running   0          47s
# taskflow-api         1/1     Running   0          85s
# taskflow-api-debug   2/2     Running   0          85s
kubectl get pods -l '!app.kubernetes.io/part-of'
# NAME    READY   STATUS    RESTARTS   AGE
# nginx   1/1     Running   0          47s
kubectl get pods -l 'app.kubernetes.io/name=taskflow-api,!debug'
# NAME           READY   STATUS    RESTARTS   AGE
# taskflow-api   1/1     Running   0          85s

Trong đó:

  • in (a,b) / notin (a,b): value thuộc / không thuộc tập hợp; notin cũng chọn cả resource thiếu key, như !=.
  • KEY (chỉ ghi key, VD -l app.kubernetes.io/part-of): có key, value gì cũng được. !KEY: không có key.
  • Hai loại trộn được với nhau trong một selector. Luôn bọc selector trong dấu nháy đơn, vì shell hiểu ( ) và ! theo cách riêng.

-l dùng được với hầu hết lệnh làm việc trên nhiều resource: kubectl logs -l app.kubernetes.io/name=taskflow-api -c api --prefix in log của container api trong mọi Pod TaskFlow API, mỗi dòng có tên Pod phía trước; delete và label cũng nhận -l.

Field selector

Ngoài label, --field-selector lọc theo giá trị một số field của resource, với =, ==, !=. Thêm một Pod chạy xong rồi thoát (kubectl run once --image=busybox:1.37 --restart=Never -- echo xong) để thấy khác biệt:

kubectl get pods --field-selector status.phase!=Running
# NAME   READY   STATUS      RESTARTS   AGE
# once   0/1     Completed   0          2s
kubectl delete pod --field-selector status.phase=Succeeded
# pod "once" deleted from default namespace

Field selector chỉ hỗ trợ vài field cho từng loại resource: mọi resource có metadata.name, metadata.namespace; Pod có thêm status.phase, spec.nodeName (VD spec.nodeName=taskflow-worker liệt kê Pod trên node đó), status.podIP... Field khác như metadata.labels.debug báo lỗi field label not supported. Nó dùng để tra cứu trên dòng lệnh (kết hợp được với -l), còn Service hay Deployment luôn chọn Pod bằng label selector.

Xong phần lọc, xóa hai Pod tạm cũng bằng selector và gỡ label debug:

kubectl delete pod -l '!app.kubernetes.io/part-of'
# pod "nginx" deleted from default namespace
kubectl delete pod -l app.kubernetes.io/component=cache
# pod "redis" deleted from default namespace
kubectl label pod taskflow-api-debug debug-
# pod/taskflow-api-debug unlabeled

Chú ý: delete -l xóa mọi thứ khớp selector, gõ thiếu một điều kiện là xóa nhầm cả nhóm. Chạy get với đúng selector đó trước khi delete.

Selector trong file manifest

Service, Deployment và các controller khác ghi selector trong YAML. Service (Bài 11) chỉ có dạng equality, viết thẳng thành map dưới spec.selector. Deployment (Bài 9) dùng matchLabels (equality) và matchExpressions (set-based, operator là In, NotIn, Exists, DoesNotExist), các điều kiện cũng là AND:

spec:
  selector:
    matchLabels:
      app.kubernetes.io/name: taskflow-api
    matchExpressions:
      - key: app.kubernetes.io/component
        operator: In
        values: ["api"]
  template:
    metadata:
      labels:
        app.kubernetes.io/name: taskflow-api
        app.kubernetes.io/component: api
        # ...

Selector của Deployment phải khớp label trong template. Mình thử đổi values thành ["notifier"] trong một Deployment đầy đủ rồi kubectl apply --dry-run=server, apiserver từ chối ngay với lỗi `selector` does not match template `labels`.

Cũng vì chọn theo label, nếu có Service cho TaskFlow API thì Pod taskflow-api-debug (cùng name, component) cũng nhận request như Pod thật. Pod thử nghiệm nên mang label khác, hoặc xóa đi khi xong việc.

5. Label của node.

Node cũng có label, phần lớn do kubelet tự gắn khi node tham gia cụm:

kubectl get nodes -L kubernetes.io/hostname,kubernetes.io/arch,topology.kubernetes.io/zone
# NAME                     STATUS   ROLES           AGE     VERSION   HOSTNAME                 ARCH    ZONE
# taskflow-control-plane   Ready    control-plane   2m35s   v1.37.0   taskflow-control-plane   arm64
# taskflow-worker          Ready    <none>          2m20s   v1.37.0   taskflow-worker          arm64
# taskflow-worker2         Ready    <none>          2m20s   v1.37.0   taskflow-worker2         arm64

Tên, kiến trúc CPU và hệ điều hành của node nằm ở kubernetes.io/hostname, kubernetes.io/arch, kubernetes.io/os. topology.kubernetes.io/region và topology.kubernetes.io/zone do cloud provider gắn (EKS/GKE/AKS), kind không có nên cột ZONE trống. Cột ROLES lấy từ label node-role.kubernetes.io/<vai trò>, nên -l '!node-role.kubernetes.io/control-plane' chỉ ra hai worker. Muốn Pod chỉ chạy trên node có ổ SSD hay đúng kiến trúc thì gắn label cho node rồi dùng nodeSelector hoặc affinity (Bài 26).

6. Annotation trong Kubernetes.

Annotation cũng là cặp key/value trong metadata (metadata.annotations), cùng quy tắc đặt key như label, nhưng không có selector nào cho annotation. Đổi lại, value tự do và dài được (tổng annotation của một resource tối đa 256 KB). Annotation dùng để ghi thông tin cho người đọc (người phụ trách, link tài liệu, lý do thay đổi), làm cấu hình cho công cụ đọc resource (VD cert-manager đọc annotation trên Gateway để biết cấp chứng chỉ HTTPS từ đâu, Bài 31), và là chỗ kubectl tự lưu dữ liệu.

kubectl annotate dùng giống hệt kubectl label (--overwrite, KEY- để xóa). VD: Value có dấu cách, tiếng Việt, ký tự < mà label không cho phép:

kubectl annotate pod taskflow-api toidicode.com/owner='Nhóm backend <[email protected]>' toidicode.com/runbook='https://github.com/toidicode/taskflow-k8s#readme'
# pod/taskflow-api annotated
kubectl describe pod taskflow-api
# ...
# Annotations:      toidicode.com/owner: Nhóm backend <[email protected]>
#                   toidicode.com/runbook: https://github.com/toidicode/taskflow-k8s#readme
# ...

kubectl.kubernetes.io/last-applied-configuration

describe cố tình ẩn một annotation mà kubectl apply tự thêm vào mọi resource nó tạo. Lấy nó bằng JSONPath, dấu chấm trong key phải escape bằng \.:

kubectl get pod taskflow-api -o jsonpath='{.metadata.annotations.kubectl\.kubernetes\.io/last-applied-configuration}'
# {"apiVersion":"v1","kind":"Pod","metadata":{"annotations":{},"labels":{"app.kubernetes.io/component":"api","app.kubernetes.io/name":"taskflow-api","app.kubernetes.io/part-of":"taskflow","app.kubernetes.io/version":"0.53.0"},"name":"taskflow-api","namespace":"default"},"spec":{"containers":[{"env":[{"name":"TASKFLOW_JWT_SECRET","value":"doi-chuoi-bi-mat-nay-dai-it-nhat-32-byte"}], ...

Đó là nội dung file manifest của lần apply gần nhất, dạng JSON (kubectl apply view-last-applied pod taskflow-api in lại dạng YAML). Lần apply sau, kubectl so ba bản: file mới, bản đã apply lần trước (annotation này) và resource đang chạy:

  • Field có trong file: đặt theo file. Đó là lý do version bị sửa tay về lại 0.53.0 ở phần 3.
  • Field có trong lần apply trước nhưng đã bị bỏ khỏi file: xóa khỏi resource.
  • Field chưa từng nằm trong file (label debug, annotation toidicode.com/owner, các giá trị mặc định do apiserver điền): giữ nguyên.

Annotation này chép nguyên file manifest, kể cả giá trị TASKFLOW_JWT_SECRET: thêm một lý do để không ghi secret thẳng vào manifest (Bài 14). Resource tạo bằng kubectl create hay kubectl run thì không có annotation này.

Còn annotation kubernetes.io/change-cause ghi lý do của một lần thay đổi. Gắn vào Deployment thì kubectl rollout history hiện nó ở cột CHANGE-CAUSE, giúp biết mỗi revision đổi gì trước khi rollback; mình sẽ dùng ở Bài 10.

Cuối cùng xóa hai Pod của bài bằng selector:

kubectl delete pod -l app.kubernetes.io/part-of=taskflow
# pod "taskflow-api" deleted from default namespace
# pod "taskflow-api-debug" deleted from default namespace

Code đầy đủ của series sau bài này nằm ở tag bai-07 trên GitHub; các thay đổi của riêng bài này: so sánh bai-06...bai-07.

7. Lời kết.

Như vậy mình đã giới thiệu với mọi người về label, selector và annotation trong Kubernetes: quy tắc đặt label, bộ label app.kubernetes.io/* và quy ước component của TaskFlow, selector equality-based và set-based, field selector, label của node và annotation last-applied-configuration. Đến giờ mọi thứ vẫn nằm chung namespace default; bài sau chúng ta sẽ tìm hiểu namespace và tạo namespace taskflow riêng cho ứng dụng.

Đăng ký nhận tin.

Chúng tôi chỉ gửi tối đa 2 lần trên 1 tháng. Tuyên bố không spam mail!

Vũ Thanh Tài

About author
The best way to learn is to share
Xem tất cả bài đăng

0 Comments

Bài viết chưa có ai bình luận, hãy là người đầu tiên đi bạn!

Bình luận

Captcha