Skip to content

注解

概述

注解(Annotations)是附加在Kubernetes对象上的键值对,用于存储非标识性的元数据。与标签不同,注解不支持选择和查询,主要用于存储描述性信息、配置数据和自动化工具所需的元数据。

核心概念

注解的特点

  • 键值对形式:key: value格式
  • 容量大:单个注解最多256KB
  • 不可查询:不支持选择器筛选
  • 灵活性强:可存储任意非标识性数据

注解与标签的区别

特性标签注解
用途标识和选择对象存储元数据
查询支持选择器查询不支持查询
数据量较小(63字符限制)较大(256KB限制)
使用场景分组、调度、服务发现描述、配置、自动化

注解的用途

  • 存储构建、发布、镜像信息
  • 记录负责人、联系方式
  • 存储配置和策略信息
  • 支持自动化工具集成
  • 保存监控和告警配置

注解用途

基本注解示例

yaml
apiVersion: v1
kind: Pod
metadata:
  name: nginx-pod
  annotations:
    # 描述信息
    description: "Nginx web server for production"
    
    # 构建信息
    buildVersion: "1.0.0"
    buildDate: "2024-01-15T10:30:00Z"
    gitCommit: "abc123def456"
    gitBranch: "main"
    
    # 镜像信息
    imageRegistry: "docker.io"
    imageDigest: "sha256:abc123..."
    
    # 负责人信息
    owner: "platform-team@company.com"
    contact: "ops-team@company.com"
    
    # 文档链接
    documentation: "https://wiki.company.com/nginx"
    runbook: "https://runbook.company.com/nginx"
spec:
  containers:
  - name: nginx
    image: nginx:1.20

注解命名规范

yaml
# 注解键格式:<prefix>/<name>
# prefix:可选,必须是DNS子域名,最长253字符
# name:必需,最长63字符,以字母数字开头和结尾

annotations:
  # Kubernetes注解
  kubernetes.io/change-cause: "Update nginx version to 1.20"
  kubernetes.io/description: "Nginx web server"
  
  # kubectl注解
  kubectl.kubernetes.io/last-applied-configuration: |
    {"apiVersion":"v1","kind":"Pod",...}
  
  # 自定义注解
  mycompany.com/owner: "platform-team"
  mycompany.com/environment: "production"
  mycompany.com/cost-center: "CC-001"
  
  # 工具注解
  prometheus.io/scrape: "true"
  prometheus.io/port: "9090"
  prometheus.io/path: "/metrics"

元数据管理

构建和发布信息

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: webapp
  annotations:
    # 构建信息
    build.company.com/version: "1.0.0"
    build.company.com/number: "123"
    build.company.com/date: "2024-01-15T10:30:00Z"
    build.company.com/url: "https://jenkins.company.com/job/webapp/123"
    
    # Git信息
    git.company.com/commit: "abc123def456"
    git.company.com/branch: "main"
    git.company.com/tag: "v1.0.0"
    git.company.com/author: "John Doe <john@company.com>"
    git.company.com/message: "Fix critical bug in authentication"
    
    # 镜像信息
    image.company.com/registry: "docker.io"
    image.company.com/repository: "mycompany/webapp"
    image.company.com/tag: "v1.0.0"
    image.company.com/digest: "sha256:abc123def456..."
    
    # 发布信息
    release.company.com/environment: "production"
    release.company.com/timestamp: "2024-01-15T11:00:00Z"
    release.company.com/approved-by: "release-manager@company.com"
spec:
  replicas: 3
  selector:
    matchLabels:
      app: webapp
  template:
    metadata:
      labels:
        app: webapp
    spec:
      containers:
      - name: webapp
        image: mycompany/webapp:v1.0.0

负责人和联系信息

yaml
apiVersion: v1
kind: Service
metadata:
  name: api-service
  annotations:
    # 负责人信息
    owner: "API Team"
    owner-contact: "api-team@company.com"
    owner-slack: "#api-team"
    
    # 运维信息
    ops-team: "Platform Team"
    ops-contact: "platform-team@company.com"
    ops-slack: "#platform-support"
    
    # 值班信息
    oncall-team: "SRE Team"
    oncall-contact: "sre-team@company.com"
    oncall-pagerduty: "https://pagerduty.com/services/ABC123"
    
    # 业务信息
    business-owner: "Product Team"
    business-contact: "product-team@company.com"
    cost-center: "CC-001"
    project-code: "PROJ-2024-001"
spec:
  selector:
    app: api
  ports:
  - port: 8080
    targetPort: 8080

文档和链接

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: webapp
  annotations:
    # 文档链接
    documentation: "https://docs.company.com/webapp"
    api-docs: "https://api.company.com/docs"
    swagger-ui: "https://api.company.com/swagger"
    
    # 运维文档
    runbook: "https://runbook.company.com/webapp"
    troubleshooting: "https://wiki.company.com/webapp/troubleshooting"
    disaster-recovery: "https://wiki.company.com/webapp/dr"
    
    # 监控链接
    grafana-dashboard: "https://grafana.company.com/d/webapp"
    prometheus-rules: "https://prometheus.company.com/rules"
    alertmanager: "https://alertmanager.company.com"
    
    # 日志链接
    log-dashboard: "https://kibana.company.com/app/webapp"
    log-index: "webapp-*"
    
    # CI/CD链接
    jenkins-job: "https://jenkins.company.com/job/webapp"
    git-repository: "https://gitlab.company.com/webapp"
    docker-registry: "https://registry.company.com/webapp"
spec:
  replicas: 3
  selector:
    matchLabels:
      app: webapp
  template:
    metadata:
      labels:
        app: webapp
    spec:
      containers:
      - name: webapp
        image: webapp:v1.0.0

自动化集成

Prometheus监控集成

yaml
apiVersion: v1
kind: Pod
metadata:
  name: webapp
  annotations:
    # Prometheus监控配置
    prometheus.io/scrape: "true"
    prometheus.io/port: "9090"
    prometheus.io/path: "/metrics"
    prometheus.io/scheme: "http"
    
    # 自定义监控配置
    monitoring.company.com/enabled: "true"
    monitoring.company.com/interval: "30s"
    monitoring.company.com/timeout: "10s"
    
    # 告警配置
    alerting.company.com/enabled: "true"
    alerting.company.com/team: "platform"
    alerting.company.com/severity: "critical"
spec:
  containers:
  - name: webapp
    image: webapp:v1.0.0
    ports:
    - containerPort: 9090
      name: metrics

Ingress控制器集成

yaml
apiVersion: networking.k8s.io/v1
kind: Ingress
metadata:
  name: webapp-ingress
  annotations:
    # Nginx Ingress配置
    nginx.ingress.kubernetes.io/rewrite-target: /
    nginx.ingress.kubernetes.io/ssl-redirect: "true"
    nginx.ingress.kubernetes.io/proxy-body-size: "10m"
    nginx.ingress.kubernetes.io/proxy-connect-timeout: "30"
    nginx.ingress.kubernetes.io/proxy-send-timeout: "300"
    nginx.ingress.kubernetes.io/proxy-read-timeout: "300"
    
    # 速率限制
    nginx.ingress.kubernetes.io/limit-rps: "100"
    nginx.ingress.kubernetes.io/limit-connections: "50"
    
    # 认证配置
    nginx.ingress.kubernetes.io/auth-type: "basic"
    nginx.ingress.kubernetes.io/auth-secret: "basic-auth"
    nginx.ingress.kubernetes.io/auth-realm: "Authentication Required"
    
    # CORS配置
    nginx.ingress.kubernetes.io/enable-cors: "true"
    nginx.ingress.kubernetes.io/cors-allow-origin: "*"
    nginx.ingress.kubernetes.io/cors-allow-methods: "GET, POST, PUT, DELETE, OPTIONS"
    
    # WAF配置
    nginx.ingress.kubernetes.io/modsecurity-snippet: |
      SecRuleEngine On
      SecRule ARGS "@rx attack" "deny,log,status:403"
spec:
  ingressClassName: nginx
  rules:
  - host: webapp.company.com
    http:
      paths:
      - path: /
        pathType: Prefix
        backend:
          service:
            name: webapp-service
            port:
              number: 80

服务网格集成

yaml
apiVersion: v1
kind: Pod
metadata:
  name: webapp
  annotations:
    # Istio配置
    sidecar.istio.io/inject: "true"
    sidecar.istio.io/proxyCPU: "500m"
    sidecar.istio.io/proxyMemory: "512Mi"
    sidecar.istio.io/proxyCPULimit: "1"
    sidecar.istio.io/proxyMemoryLimit: "1Gi"
    
    # 流量管理
    traffic.sidecar.istio.io/includeOutboundIPRanges: "*"
    traffic.sidecar.istio.io/excludeOutboundIPRanges: ""
    traffic.sidecar.istio.io/includeInboundPorts: "*"
    traffic.sidecar.istio.io/excludeInboundPorts: ""
    
    # 监控配置
    sidecar.istio.io/statsInclusionPrefixes: "cluster.outbound,cluster_manager,listener_manager,http_mixer_filter,tcp_mixer_filter,server,cluster.xds-grpc"
    
    # 安全配置
    sidecar.istio.io/userVolumeMount: '{"name":"certs","mountPath":"/etc/certs","readOnly":true}'
spec:
  containers:
  - name: webapp
    image: webapp:v1.0.0

自动扩缩容集成

yaml
apiVersion: autoscaling/v2
kind: HorizontalPodAutoscaler
metadata:
  name: webapp-hpa
  annotations:
    # HPA配置说明
    description: "Auto-scaling for webapp based on CPU and memory usage"
    
    # 扩缩容策略
    autoscaling.alpha.kubernetes.io/conditions: |
      [
        {
          "type": "AbleToScale",
          "status": "True",
          "reason": "ReadyForNewScale",
          "message": "recommended size matches current size"
        }
      ]
    
    # 自定义指标配置
    metric-config.custom.googleapis.com/request-rate: |
      {
        "metricName": "request-rate",
        "metricSelector": {
          "matchLabels": {
            "app": "webapp"
          }
        }
      }
spec:
  scaleTargetRef:
    apiVersion: apps/v1
    kind: Deployment
    name: webapp
  minReplicas: 3
  maxReplicas: 10
  metrics:
  - type: Resource
    resource:
      name: cpu
      target:
        type: Utilization
        averageUtilization: 70

实用kubectl操作命令

注解管理命令

bash
# 添加注解
kubectl annotate pod nginx-pod description="Nginx web server"
kubectl annotate deployment webapp owner="platform-team@company.com"

# 修改注解
kubectl annotate pod nginx-pod description="Updated description" --overwrite

# 删除注解
kubectl annotate pod nginx-pod description-

# 查看注解
kubectl get pod nginx-pod -o jsonpath='{.metadata.annotations}'
kubectl describe pod nginx-pod | grep -A 20 Annotations

# 查看特定注解
kubectl get pod nginx-pod -o jsonpath='{.metadata.annotations.description}'

# 批量添加注解
kubectl annotate pods -l app=nginx team=platform

# 导出注解
kubectl get pods -o json | jq -r '.items[].metadata.annotations' > annotations.json

注解查询命令

bash
# 查看所有注解
kubectl get pods -o custom-columns=\
'NAME:.metadata.name,\
ANNOTATIONS:.metadata.annotations'

# 查看特定注解的值
kubectl get pods -o jsonpath='{range .items[*]}{.metadata.name}{"\t"}{.metadata.annotations.owner}{"\n"}{end}'

# 按注解过滤(需要jq)
kubectl get pods -o json | jq -r '.items[] | select(.metadata.annotations.owner=="platform-team") | .metadata.name'

# 统计注解使用情况
kubectl get pods --all-namespaces -o json | \
  jq -r '.items[].metadata.annotations | keys[]' | \
  sort | uniq -c | sort -rn

# 查找包含特定注解的资源
kubectl get pods --all-namespaces -o json | \
  jq -r '.items[] | select(.metadata.annotations["prometheus.io/scrape"]=="true") | .metadata.name'

高级操作命令

bash
# 添加JSON格式注解
kubectl annotate pod nginx-pod config='{"key":"value","number":123}'

# 添加多行注解
kubectl annotate pod nginx-pod multiline="line1
line2
line3"

# 从文件添加注解
kubectl annotate pod nginx-pod --from-file=config.json

# 批量更新注解
kubectl get pods -l app=nginx -o name | \
  xargs -I {} kubectl annotate {} updated-date=$(date +%Y-%m-%d)

# 导出注解到YAML
kubectl get pod nginx-pod -o yaml | grep -A 20 annotations

# 比较注解差异
kubectl diff -f pod.yaml

# 查看注解历史
kubectl get pod nginx-pod -o jsonpath='{.metadata.annotations.kubectl.kubernetes.io/last-applied-configuration}'

实践示例

示例1:完整的应用元数据管理

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: webapp
  annotations:
    # 应用信息
    app.company.com/name: "WebApp"
    app.company.com/description: "Main web application for customer portal"
    app.company.com/version: "1.0.0"
    app.company.com/tier: "frontend"
    
    # 构建信息
    build.company.com/id: "12345"
    build.company.com/url: "https://jenkins.company.com/job/webapp/12345"
    build.company.com/date: "2024-01-15T10:30:00Z"
    
    # Git信息
    git.company.com/repository: "https://gitlab.company.com/webapp"
    git.company.com/commit: "abc123def456"
    git.company.com/branch: "main"
    git.company.com/tag: "v1.0.0"
    
    # 镜像信息
    image.company.com/name: "mycompany/webapp"
    image.company.com/tag: "v1.0.0"
    image.company.com/digest: "sha256:abc123def456..."
    
    # 负责人信息
    owner.company.com/team: "Platform Team"
    owner.company.com/email: "platform-team@company.com"
    owner.company.com/slack: "#platform-team"
    
    # 运维信息
    ops.company.com/oncall: "SRE Team"
    ops.company.com/pagerduty: "https://pagerduty.com/services/ABC123"
    ops.company.com/runbook: "https://runbook.company.com/webapp"
    
    # 监控信息
    monitoring.company.com/enabled: "true"
    monitoring.company.com/dashboard: "https://grafana.company.com/d/webapp"
    monitoring.company.com/alerts: "https://alertmanager.company.com"
    
    # 日志信息
    logging.company.com/enabled: "true"
    logging.company.com/index: "webapp-*"
    logging.company.com/dashboard: "https://kibana.company.com/app/webapp"
    
    # 业务信息
    business.company.com/owner: "Product Team"
    business.company.com/cost-center: "CC-001"
    business.company.com/project: "PROJ-2024-001"
    
    # 合规信息
    compliance.company.com/data-classification: "confidential"
    compliance.company.com/pci-dss: "true"
    compliance.company.com/gdpr: "true"
spec:
  replicas: 3
  selector:
    matchLabels:
      app: webapp
  template:
    metadata:
      labels:
        app: webapp
      annotations:
        prometheus.io/scrape: "true"
        prometheus.io/port: "9090"
        prometheus.io/path: "/metrics"
    spec:
      containers:
      - name: webapp
        image: mycompany/webapp:v1.0.0
        ports:
        - containerPort: 8080
        - containerPort: 9090
          name: metrics

应用场景:为应用添加完整的元数据,支持运维、监控、合规等多方面需求。

示例2:多环境配置管理

yaml
# 开发环境
apiVersion: v1
kind: Pod
metadata:
  name: webapp-dev
  annotations:
    # 环境信息
    environment: "development"
    environment.company.com/name: "Development"
    environment.company.com/owner: "Dev Team"
    environment.company.com/cost-center: "CC-DEV-001"
    
    # 资源信息
    resources.company.com/tier: "low"
    resources.company.com/budget: "1000"
    
    # 监控配置
    monitoring.company.com/enabled: "false"
    alerting.company.com/enabled: "false"
    
    # 访问控制
    access.company.com/public: "false"
    access.company.com/vpn-required: "true"
spec:
  containers:
  - name: webapp
    image: webapp:dev
---
# 测试环境
apiVersion: v1
kind: Pod
metadata:
  name: webapp-staging
  annotations:
    # 环境信息
    environment: "staging"
    environment.company.com/name: "Staging"
    environment.company.com/owner: "QA Team"
    environment.company.com/cost-center: "CC-QA-001"
    
    # 资源信息
    resources.company.com/tier: "medium"
    resources.company.com/budget: "5000"
    
    # 监控配置
    monitoring.company.com/enabled: "true"
    alerting.company.com/enabled: "true"
    alerting.company.com/severity: "warning"
    
    # 访问控制
    access.company.com/public: "false"
    access.company.com/vpn-required: "true"
spec:
  containers:
  - name: webapp
    image: webapp:staging
---
# 生产环境
apiVersion: v1
kind: Pod
metadata:
  name: webapp-prod
  annotations:
    # 环境信息
    environment: "production"
    environment.company.com/name: "Production"
    environment.company.com/owner: "Ops Team"
    environment.company.com/cost-center: "CC-PROD-001"
    
    # 资源信息
    resources.company.com/tier: "high"
    resources.company.com/budget: "50000"
    
    # 监控配置
    monitoring.company.com/enabled: "true"
    alerting.company.com/enabled: "true"
    alerting.company.com/severity: "critical"
    
    # 访问控制
    access.company.com/public: "true"
    access.company.com/vpn-required: "false"
    
    # 合规信息
    compliance.company.com/audit-enabled: "true"
    compliance.company.com/retention-days: "90"
spec:
  containers:
  - name: webapp
    image: webapp:v1.0.0

应用场景:使用注解管理不同环境的配置和策略。

示例3:自动化工具集成

yaml
apiVersion: apps/v1
kind: Deployment
metadata:
  name: webapp
  annotations:
    # CI/CD集成
    ci.company.com/enabled: "true"
    ci.company.com/provider: "jenkins"
    ci.company.com/job: "https://jenkins.company.com/job/webapp"
    ci.company.com/webhook: "https://jenkins.company.com/webhook/webapp"
    
    # GitOps集成
    gitops.company.com/enabled: "true"
    gitops.company.com/provider: "argocd"
    gitops.company.com/application: "webapp"
    gitops.company.com/sync-policy: "automated"
    
    # 密钥管理集成
    secrets.company.com/provider: "vault"
    secrets.company.com/path: "secret/data/webapp"
    secrets.company.com/template: "webapp-secrets"
    
    # 配置管理集成
    config.company.com/provider: "consul"
    config.company.com/path: "webapp/config"
    config.company.com/refresh-interval: "60s"
    
    # 服务发现集成
    discovery.company.com/enabled: "true"
    discovery.company.com/provider: "consul"
    discovery.company.com/service-name: "webapp"
    discovery.company.com/health-check: "/health"
    
    # 自动扩缩容集成
    autoscaling.company.com/enabled: "true"
    autoscaling.company.com/min-replicas: "3"
    autoscaling.company.com/max-replicas: "10"
    autoscaling.company.com/target-cpu: "70"
    
    # 备份集成
    backup.company.com/enabled: "true"
    backup.company.com/schedule: "0 2 * * *"
    backup.company.com/retention: "30d"
    backup.company.com/storage: "s3://backups/webapp"
    
    # 灾难恢复集成
    dr.company.com/enabled: "true"
    dr.company.com/rpo: "1h"
    dr.company.com/rto: "15m"
    dr.company.com/backup-location: "us-west-2"
spec:
  replicas: 3
  selector:
    matchLabels:
      app: webapp
  template:
    metadata:
      labels:
        app: webapp
    spec:
      containers:
      - name: webapp
        image: webapp:v1.0.0

应用场景:通过注解集成各种自动化工具,实现DevOps自动化。

故障排查指南

常见问题诊断

1. 注解格式错误

bash
# 错误示例:注解值包含特殊字符
kubectl annotate pod nginx-pod description="This is a "test""

# 正确示例:使用转义或单引号
kubectl annotate pod nginx-pod description='This is a "test"'
kubectl annotate pod nginx-pod description="This is a \"test\""

# 查看注解格式
kubectl get pod nginx-pod -o jsonpath='{.metadata.annotations}' | jq .

# 验证注解格式
kubectl apply -f pod.yaml --dry-run=client

2. 注解大小限制

bash
# 查看注解大小
kubectl get pod nginx-pod -o json | jq '.metadata.annotations | to_entries | .[] | {key: .key, size: (.value | length)}'

# 错误信息
The Pod "nginx-pod" is invalid: metadata.annotations: Too long: must have at most 262144 characters

# 解决方案
# 1. 压缩注解内容
# 2. 分割大注解为多个小注解
# 3. 使用外部存储(ConfigMap/Secret)

3. 注解键冲突

bash
# 查看重复的注解键
kubectl get pod nginx-pod -o json | jq '.metadata.annotations | keys' | sort | uniq -d

# 解决方案
# 1. 使用唯一的前缀
# 2. 使用命名规范
# 3. 避免覆盖系统注解

4. 注解更新失败

bash
# 查看注解更新错误
kubectl annotate pod nginx-pod key=value
# Error from server (Conflict): pods "nginx-pod" cannot be updated

# 解决方案
# 1. 使用--overwrite强制更新
kubectl annotate pod nginx-pod key=value --overwrite

# 2. 检查资源版本
kubectl get pod nginx-pod -o jsonpath='{.metadata.resourceVersion}'

# 3. 使用kubectl apply而不是kubectl edit

注解管理脚本

bash
#!/bin/bash
# 注解管理脚本

echo "=== 注解使用统计 ==="
kubectl get pods --all-namespaces -o json | \
  jq -r '.items[].metadata.annotations | keys[]' | \
  sort | uniq -c | sort -rn | head -20

echo -e "\n=== 注解大小统计 ==="
kubectl get pods --all-namespaces -o json | \
  jq -r '.items[] | {name: .metadata.name, annotations: (.metadata.annotations | to_entries | map({key: .key, size: (.value | length)}) | sort_by(.size) | reverse)} | select(.annotations | length > 0) | {name: .name, largest: .annotations[0]}'

echo -e "\n=== 缺少必要注解的Pod ==="
kubectl get pods --all-namespaces -o json | \
  jq -r '.items[] | select(.metadata.annotations.owner == null) | .metadata.name'

echo -e "\n=== Prometheus监控注解 ==="
kubectl get pods --all-namespaces -o json | \
  jq -r '.items[] | select(.metadata.annotations["prometheus.io/scrape"]=="true") | {name: .metadata.name, namespace: .metadata.namespace, port: .metadata.annotations["prometheus.io/port"], path: .metadata.annotations["prometheus.io/path"]}'

echo -e "\n=== 注解键冲突检查 ==="
kubectl get pods --all-namespaces -o json | \
  jq -r '.items[].metadata.annotations | keys[]' | \
  sort | uniq -d | while read key; do
    echo "Duplicate key: $key"
    kubectl get pods --all-namespaces -o json | \
      jq -r ".items[] | select(.metadata.annotations[\"$key\"] != null) | .metadata.name"
  done

最佳实践建议

1. 注解命名规范

yaml
# 推荐的注解命名规范
annotations:
  # 使用域名前缀
  mycompany.com/owner: "platform-team"
  mycompany.com/environment: "production"
  
  # 使用一致的命名风格
  build.company.com/version: "1.0.0"
  build.company.com/date: "2024-01-15"
  build.company.com/url: "https://jenkins.company.com/job/123"
  
  # 避免使用保留前缀
  # kubernetes.io/* - Kubernetes保留
  # kubectl.kubernetes.io/* - kubectl保留

2. 注解内容规范

yaml
annotations:
  # 使用JSON格式存储结构化数据
  config.company.com/settings: |
    {
      "timeout": 30,
      "retries": 3,
      "enabled": true
    }
  
  # 使用YAML格式存储配置
  config.company.com/yaml: |
    timeout: 30
    retries: 3
    enabled: true
  
  # 使用URL存储外部资源
  documentation: "https://docs.company.com/webapp"
  runbook: "https://runbook.company.com/webapp"
  
  # 使用时间戳格式
  created-date: "2024-01-15T10:30:00Z"
  updated-date: "2024-01-20T15:45:00Z"

3. 注解管理策略

yaml
# 必需注解
annotations:
  # 应用信息
  app.company.com/name: "webapp"
  app.company.com/version: "1.0.0"
  
  # 负责人信息
  owner: "platform-team@company.com"
  
  # 环境信息
  environment: "production"

# 推荐注解
annotations:
  # 文档链接
  documentation: "https://docs.company.com/webapp"
  runbook: "https://runbook.company.com/webapp"
  
  # 监控配置
  prometheus.io/scrape: "true"
  prometheus.io/port: "9090"
  
  # Git信息
  git.company.com/commit: "abc123"
  git.company.com/branch: "main"

# 可选注解
annotations:
  # 业务信息
  business.company.com/cost-center: "CC-001"
  business.company.com/project: "PROJ-2024-001"
  
  # 合规信息
  compliance.company.com/data-classification: "confidential"

4. 注解文档化

markdown
## 注解使用规范

### 必需注解
- `app.company.com/name`: 应用名称
- `app.company.com/version`: 应用版本
- `owner`: 负责人邮箱
- `environment`: 环境标识

### 推荐注解
- `documentation`: 文档链接
- `runbook`: 运维手册链接
- `prometheus.io/scrape`: Prometheus监控开关

### 注解值规范
- 使用标准格式(JSON/YAML/URL)
- 避免存储敏感信息
- 控制注解大小(建议<1KB)

5. 注解安全最佳实践

yaml
# 不要在注解中存储敏感信息
annotations:
  # ❌ 错误示例
  password: "my-password-123"
  api-key: "secret-api-key"
  
  # ✅ 正确示例
  secret-ref: "secret-name"
  vault-path: "secret/data/webapp"

# 使用注解引用外部资源
annotations:
  # 引用Secret
  secret.company.com/name: "webapp-secrets"
  
  # 引用Vault
  vault.company.com/path: "secret/data/webapp"
  vault.company.com/template: "webapp-template"
  
  # 引用ConfigMap
  config.company.com/name: "webapp-config"

总结

核心要点

  1. 注解基础

    • 键值对形式,用于存储元数据
    • 不支持选择器查询
    • 单个注解最多256KB
  2. 注解用途

    • 存储构建、发布、镜像信息
    • 记录负责人、联系方式
    • 支持自动化工具集成
  3. 自动化集成

    • Prometheus监控集成
    • Ingress控制器集成
    • 服务网格集成
    • CI/CD工具集成
  4. 最佳实践

    • 使用规范的命名前缀
    • 避免存储敏感信息
    • 控制注解大小
    • 文档化注解规范

常用命令速查

bash
# 注解管理
kubectl annotate pod <name> key=value
kubectl annotate pod <name> key-  # 删除注解
kubectl get pod <name> -o jsonpath='{.metadata.annotations}'

# 注解查询
kubectl describe pod <name> | grep -A 20 Annotations
kubectl get pods -o custom-columns='NAME:.metadata.name,ANNOTATIONS:.metadata.annotations'

# 批量操作
kubectl annotate pods -l app=nginx team=platform

下一步学习

参考资源