Tekton 0.49 云原生 CI/CD 流水线开发指南

核心概念
Tekton 是基于 Kubernetes 的开源 CI/CD 框架,通过自定义资源(CRD)定义流水线。其核心组件包括:

  • Task:单步操作(如代码编译)
  • Pipeline:组合多个 Task 的有序流程
  • PipelineRun:流水线执行实例

步骤 1:环境准备(Kubernetes 集群)
# 安装 Tekton v0.49
kubectl apply -f https://storage.googleapis.com/tekton-releases/pipeline/previous/v0.49.0/release.yaml


步骤 2:定义流水线组件
(1) 代码编译 Task(以 Java/Maven 为例)
apiVersion: tekton.dev/v1beta1
kind: Task
metadata:
  name: compile-code
spec:
  steps:
    - name: maven-compile
      image: maven:3.8.6-openjdk-11
      script: |
        mvn clean package -DskipTests
      volumeMounts:
        - name: workspace
          mountPath: /workspace
  workspaces:
    - name: workspace

(2) 镜像构建 Task(使用 Kaniko)
apiVersion: tekton.dev/v1beta1
kind: Task
metadata:
  name: build-image
spec:
  params:
    - name: IMAGE_URL
      type: string
  steps:
    - name: kaniko-build
      image: gcr.io/kaniko-project/executor:v1.9.0
      args:
        - --dockerfile=Dockerfile
        - --destination=$(params.IMAGE_URL)
  workspaces:
    - name: source


步骤 3:组合流水线 Pipeline
apiVersion: tekton.dev/v1beta1
kind: Pipeline
metadata:
  name: code-to-image
spec:
  workspaces:
    - name: shared-data
  params:
    - name: repo-url
      type: string
    - name: image-url
      type: string
  tasks:
    - name: fetch-source
      taskRef:
        name: git-clone  # 需预先部署
      params:
        - name: url
          value: $(params.repo-url)
      workspaces:
        - name: output
          workspace: shared-data

    - name: compile
      taskRef:
        name: compile-code
      runAfter: [fetch-source]
      workspaces:
        - name: workspace
          workspace: shared-data

    - name: build-image
      taskRef:
        name: build-image
      runAfter: [compile]
      params:
        - name: IMAGE_URL
          value: $(params.image-url)
      workspaces:
        - name: source
          workspace: shared-data


步骤 4:触发流水线执行
apiVersion: tekton.dev/v1beta1
kind: PipelineRun
metadata:
  generateName: code-to-image-run-
spec:
  pipelineRef:
    name: code-to-image
  params:
    - name: repo-url
      value: "https://github.com/your-org/app-repo.git"
    - name: image-url
      value: "gcr.io/your-project/app-image:latest"
  workspaces:
    - name: shared-data
      volumeClaimTemplate:
        spec:
          accessModes: [ "ReadWriteOnce" ]
          resources:
            requests:
              storage: 1Gi


关键优化技巧

  1. 增量构建
    • Kaniko 参数中添加 --cache=true 复用构建缓存
  2. 安全凭证
    • 通过 Secret 注入镜像仓库认证信息:
      env:
        - name: DOCKER_CONFIG
          value: /tekton/home/.docker
      volumeMounts:
        - name: docker-config
          mountPath: /tekton/home/.docker
      

  3. 资源限制
    • Task 中定义资源请求/限制:
      resources:
        limits:
          cpu: "1"
          memory: "2Gi"
      

验证流水线状态

kubectl get pipelineruns -w
tekton dashboard &  # 可视化监控

更多推荐