tekton之trigger触发器

trigger

监听特定的事件,并在满足条件时自动触发流水线,如git仓库的pr、push、合并代码事件

允许按需监听事件,并与pipeline连接从而实例化pipelineRun,并且可以将事件属性注入到流水线中

官方文档:https://tekton.dev/docs/triggers/

CRD资源:

  • trigger:用于监听事件,eventListener pod用于监视并筛选event使用的筛选条件,由TriggerTemplate、TriggerBinding、ClusterInterceptor组成
  • TriggerBinding:分命名空间级别和集群级别(ClusterTriggerBinding)。负责在指定事件上(由eventListener筛选)感兴趣的字段,从字段中读取数据传递给TriggerTemplate,在由TriggerTemplate将相关数据传参给taskRun、pipelineRun
  • TriggerTemplate:流水线模板,由eventListener筛选出的事件触发,从而实例化并完成资源创建,如TaskRun、PipelineRun。支持通过参数从TriggerBinding获取配置
  • eventListener:以pod形式运行在k8s上,通过监听指定端口接收事件,事件的过滤需要多个Trigger定义
  • ClusterInterceptor:负载在trigger进行事件筛选之前,接收特定平台或系统(gitlab等)上全部事件,在做进一步预处理,如过滤、校验、转换、Trigger条件测试等,预处理完成后的事件,交给Trigger筛选,符合条件的事件则传给TriggerBinding

image-20240104195617609

各资源关系

  • eventListener pod是tekton trigger的物理表现形式,主要由1到多个Trigger组成
  • 各crd资源可以单独定义,也可以直接在eventlistener中直接定义
  • 每个trigger由1个template(配置TriggerTemplate)、1组binding(配置TriggerBinding)、1组interceptor(配置ClusterInterceptor)组成

变量传递

event --> TriggerBinding(parameters定义,获取值)--> 赋值给TriggerTemplate (Parameters传参) --> pipelinerun(传参) --> task(传参)

image-20240104201905801

配置

EventListener

apiVersion: triggers.tekton.dev/v1beta1
kind: EventListener
metadata:
  annotations:
    tekton.dev/payload-validation: "false"      #语法验证关闭
spec:
  serviceAccountName: sa    #事件监听器使用此sa,部署后默认创建了2个sa:tekton-triggers-eventlistener-roles(ns级)、tekton-triggers-eventlistener-clusterroles(集群级),如果使用spec.namespaceSelector,则必须配置为tekton-triggers-eventlistener-roles
  triggers:     #检测到事件后执行的触发器列表
  - name: str
    interceptors:     #用于过滤事件的拦截器配置
    - github:
        eventTypes:
        - "pull_request"
    bindings:       #Trigger的TriggerBindings 列表;您可以引用现有的 TriggerBindings 或直接嵌入其定义
    - name: str
      value: str
      ref: pipeline-clusterbinding
      kind: ClusterTriggerBinding
    template:
    - ref: str
    triggerRef:   #对外部 Trigger 的引用
  cloudEventURI:    #指定cloudevent接收的uri
  resources:        #用于事件侦听服务的资源
    kubernetesResource:
      serviceType: NodePort
      servicePort: 80
      spec:
        template:
          metadata:
            labels:
              key: "value"
            annotations:
              key: "value"
          spec:
            serviceAccountName: tekton-triggers-github-sa
            nodeSelector:
              app: test
            tolerations:
            - key: key
              value: value
              operator: Equal
              effect: NoSchedule
    customResource:
      apiVersion: serving.knative.dev/v1
      kind: Service
      spec:
        template:
          spec:
            serviceAccountName: tekton-triggers-example-sa
            containers:
            - resources:
                requests:
                  memory: "64Mi"
                  cpu: "250m"
                limits:
                  memory: "128Mi"
                  cpu: "500m"
  namespaceSelector:      #
  labelSelector:
  TriggerGroups:
  - name: str
    interceptors:
    - name: "validate GitHub payload and filter on eventType"
      ref:
        name: "github"
      params:
      - name: "secretRef"
        value:
          secretName: github-secret
          secretKey: secretToken
      - name: "eventTypes"
        value: ["pull_request"]
      - name: "filter"
        value: "body.action in ['opened', 'reopened']"
    triggerSelector:
      namespaceSelector:
        matchNames:
        - foo
      labelSelector:
        matchLabels:
          type: cel-preprocessed
        matchExpressions:
        - {key: environment, operator: In, values: [dev,stage]}
        - {key: trigger-phase, operator: NotIn, values: [testing]}

TriggerTemplate

apiVersion: triggers.tekton.dev/v1beta1
kind: TriggerTemplate
metadata:
  name: pipeline-template
spec:
  params:     #当前触发器模板的参数,从triggerbinding获取
  - name: gitrevision
    description: The git revision
    default: main
  resourcetemplates:  #定义资源模板,一般用于定义pipelineRun、taskRun资源
  - apiVersion: tekton.dev/v1beta1
    kind: PipelineRun
    metadata:
      generateName: simple-pipeline-run-    #资源名,必须使用此字段定义
    spec:
      pipelineRef:
        name: simple-pipeline
      params:       #参数引用:$(tt.params.变量名)
      - name: message
        value: $(tt.params.message)
      workspaces:
      - name: git-source
        emptyDir: {}

Trigger

apiVersion: triggers.tekton.dev/v1beta1
kind: Trigger
metadata:
  name: push-trigger
spec:
  bindings:
  - ref: pipeline-binding
  template:
    ref: git-clone-template
  interceptors:		#引用哪个解析器
    - name: add-truncated-sha
      ref:
        name: "cel"
      params:
        - name: "overlays"
          value:
          - key: truncated_sha
            expression: "body.pull_request.head.sha.truncate(7)"
  ref:
  - name: str
    kind: str
  serviceAccountName: str

TriggerBinding

可以在Trigger资源中内嵌定义,或ClusterTriggerBinding做统一定义
将event中特定属性值传给TriggerTemplate上的参数

apiVersion: triggers.tekton.dev/v1beta1
kind: TriggerBinding
metadata:
  name: pipeline-binding
spec:
  params:		
  - name: gitrevision		#同一个trigger中引用的TriggerTemplate上声明的某个参数的名称
    value: $(body.head_commit.id)	#通常要引用event中特定的属性,如:$(body.repository.clone_url)
  - name: gitrepositoryurl
    value: $(body.repository.url)
  - name: contenttype
    value: $(header.Content-Type)

ClusterTriggerBinding

集群级TriggerBinding,资源格式与TriggerBinding类似,在Trigger.spec.bindings中引用ClusterTriggerBinding时,必须指明kind字段

apiVersion: triggers.tekton.dev/v1beta1
kind: ClusterTriggerBinding
metadata:
  name: pipeline-clusterbinding
spec:
  params:
    - name: gitrevision
      value: $(body.head_commit.id)
    - name: gitrepositoryurl
      value: $(body.repository.url)
    - name: contenttype
      value: $(header.Content-Type)

Interceptor

apiVersion: triggers.tekton.dev/v1alpha1
kind: Interceptor
metadata:
spec:

ClusterInterceptor

对事件源进行预处理

默认创建的ci:

  • bitbucket
  • cel
  • github
  • gitlab
  • slack
apiVersion: triggers.tekton.dev/v1alpha1
kind: ClusterInterceptor
metadata:
spec:
  clientConfig:
    caBundle: <cert data>
    service:
      name: "my-interceptor-svc"
      namespace: "default"
      path: "/optional-path" # optional
      port: 8443

案例

通过webhook从gitlab中获取事件,定义triggerbinding资源负责读取push事件并完成参数复制

  • 将事件上checkout_sha属性的值传给git-revision参数
  • 将事件上repository.git_http_url属性的值传给git-repo-url参数

定义triggertemplate资源从triggerbinding中接收传递的参数值并根据模板定义的资源完成taskrun实例化(创建taskrun运行)

例1:简单示例

1)运行模板

apiVersion: triggers.tekton.dev/v1alpha1
kind: TriggerTemplate
metadata:
  name: pipeline-template-demo
spec:
  params:
    - name: image-url
      default: ikubernetes/spring-boot-helloworld
    - name: git-revision
      description: The git revision (SHA)
      default: master
    - name: git-url
      description: The git repository url ("https://github.com/foo/bar.git")
    - name: version
      description: The version of application
  resourcetemplates:
    - apiVersion: tekton.dev/v1beta1
      kind: PipelineRun
      metadata:
        generateName: pipeline-run-
      spec:
        pipelineRef:
          name: source-to-image
        params:
          - name: git-url
            value: $(tt.params.git-url)
          - name: image-url
            value: $(tt.params.image-url)
          - name: version
            value: $(tt.params.version)
        workspaces:
          - name: codebase
            volumeClaimTemplate:
              spec:
                accessModes:
                  - ReadWriteOnce
                resources:
                  requests:
                    storage: 1Gi
                storageClassName: nfs-csi
          - name: docker-config
            secret:
              secretName: docker-config

2)事件触发器过滤关键信息

apiVersion: triggers.tekton.dev/v1beta1
kind: TriggerBinding
metadata:
  name: pipeline-binding-demo
spec:
  params:
  - name: git-url
    value: $(body.head_commit.id)
  - name: image-url
    value: $(body.repository.url)
  - name: version
    value: $(header.Content-Type)

例2:gitlab事件监听

1)gitlab webhook回调token

访问gitlab的token需要手动生成

apiVersion: v1
kind: Secret
metadata:
  name: gitlab-webhook-token
type: Opaque
stringData:
  #生成命令:"openssl rand -base64 12"
  webhookToken: "DXeqvozMlTA67aQB"

2)配置tekton-trigger的rbac授权

允许事件监听器访问tekton-trigger的相关组件,确保有权限访问

如果遇到sa的rbac授权问题,参考官方文档:

直接查看clusterrole资源定义内容也行:

  • ClusterRole:tekton-triggers-eventlistener-roles
  • ClusterRole:tekton-triggers-eventlistener-clusterroles
apiVersion: v1
kind: ServiceAccount
metadata:
  name: tekton-triggers-gitlab-sa
secrets:
- name: gitlab-webhook-token
---
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: tekton-triggers-gitlab-minimal
rules:
  # Permissions for every EventListener deployment to function
- apiGroups: ["triggers.tekton.dev"]
  resources: 
  - eventlisteners
  - triggerbindings
  - interceptors
  - triggertemplates
  - triggers
  verbs:
  - get
  - list
  - watch
- apiGroups: [""]
    # secrets are only needed for Github/Gitlab interceptors, serviceaccounts only for per trigger authorization
  resources: 
  - "configmaps"
  - "secrets"
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - ""
  resources:
  - serviceaccounts
  verbs:
  - impersonate
- apiGroups:
  - ""
  resources:
  - events
  verbs:
  - create
  - patch
  # Permissions to create resources in associated TriggerTemplates
- apiGroups: ["tekton.dev"]
  resources:
  - pipelineruns
  - pipelineresources
  - taskruns
  verbs: ["create"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: tekton-triggers-gitlab-binding
subjects:
  - kind: ServiceAccount
    name: tekton-triggers-gitlab-sa
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: Role
  name: tekton-triggers-gitlab-minimal
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: tekton-triggers-gitlab-minimal
rules:
- apiGroups:
  - triggers.tekton.dev
  resources:
  - clustertriggerbindings
  - clusterinterceptors
  verbs:
  - get
  - list
  - watch
- apiGroups:
  - ""
  resources:
  - secrets
  verbs:
  - get
  - list
  - watch
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: tekton-triggers-gitlab-binding
subjects:
  - kind: ServiceAccount
    name: tekton-triggers-gitlab-sa
    namespace: default
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: tekton-triggers-gitlab-minimal

3)定义事件触发器

获取事件信息,并定义为参数,方便后面TriggerTemplate引用这里的参数

apiVersion: triggers.tekton.dev/v1beta1
kind: TriggerBinding
metadata:
  name: gitlab-push-binding
spec:
  params:
  - name: git-revision
    value: $(body.checkout_sha)
  - name: git-repo-url
    value: $(body.repository.git_http_url)

4)事件触发后,运行taskrun

apiVersion: triggers.tekton.dev/v1beta1
kind: TriggerTemplate
metadata:
  name: gitlab-trigger-template
spec:
  params:  # 定义参数
  - name: git-revision
  - name: git-repo-url
  resourcetemplates:
  - apiVersion: tekton.dev/v1beta1
    kind: TaskRun
    metadata:
      generateName: gitlab-trigger-run-  # TaskRun 名称前缀
    spec:
      serviceAccountName: tekton-triggers-gitlab-sa
      params:
        - name: git-revision
          value: $(tt.params.git-revision)
        - name: git-repo-url
          value: $(tt.params.git-repo-url)
      workspaces:
        - name: source
          emptyDir: {}
      taskSpec:
        workspaces:
          - name: source
        params:
          - name: git-revision
          - name: git-repo-url
        steps:
          - name: fetch-from-git-repo
            image: alpine/git:v2.36.1
            script: |
              git clone -v $(params.git-repo-url) $(workspaces.source.path)/source
              cd $(workspaces.source.path)/source && git reset --hard $(params.git-revision)
          - name: list-files
            image: alpine:3.16
            script: ls -la $(workspaces.source.path)/source

5)监听事件

事件触发后由模板运行相关资源,运行模板为第4步

apiVersion: triggers.tekton.dev/v1beta1
kind: EventListener
metadata:
  name: gitlab-event-listener
spec:
  serviceAccountName: tekton-triggers-gitlab-sa
  triggers:
  - name: gitlab-push-events-trigger
    interceptors:
    - ref:
        name: "gitlab"
      params:
      - name: "secretRef"
        value:
          secretName: gitlab-webhook-token 
          secretKey: webhookToken
      - name: "eventTypes"
        value: ["Push Hook"]
    bindings:
    - ref: gitlab-push-binding
    template:
      ref: gitlab-trigger-template

运行的事件监听器pod
image-20240105005125945

6)将事件侦听器解析给外部gitlab

由于事件监听器是k8s运行,且创建svc是clusterIP,所以这里使用端口暴露到宿主机ip访问,生产环境应该在ingress暴露

#转发端口到外部(没ingress时,临时用此)
kubectl port-forward deploy/el-gitlab-event-listener --address 0.0.0.0 8080

#为tekton配置一个虚拟ip
ip link a vip0 type dummy
ip add a 2.2.2.67/32 dev vip0


#gitlab主机中添加hosts解析,解析tekton的事件监听器地址
echo 2.2.2.67 el-gitlab-event-listener.default.svc.cluster.local >> /etc/hosts
curl el-gitlab-event-listener.default.svc.cluster.local:8080


手动在gitlab上,在指定的项目中,创建webhook,开启推送、标签、合并事件,secret令牌就是第一步中的token:DXeqvozMlTA67aQB,我这里是这个,这个需要手动生成image-20240105004118704

image-20240105004136636

tekton的web界面中,查看最新的taskrun,已经可以正常获取gitlab的仓库
image-20240105004708147

例3:基于事件自动触发cicd流水线

image-20240105123146812

1)参考例2,完成1、2步骤

定义gitlab回调token、sa账号rbac授权

2)配置镜像仓库登录信息

#docker login -u suyanhj https://hub.docker.com/

#此处登录阿里云
docker login -u 那是你的猫 registry.cn-hangzhou.aliyuncs.com
kubectl create secret generic docker-config --from-file=/root/.docker/config.json

3)创建业务应用运行sa

apiVersion: v1
kind: ServiceAccount
metadata:
  name: helloworld-admin
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: helloworld-admin
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: cluster-admin
subjects:
- kind: ServiceAccount
  name: helloworld-admin
  namespace: default

4)申请mvn使用的pvc

用于缓存共享

kubectl apply -f - <<eof
apiVersion: v1
kind: PersistentVolumeClaim
metadata:
  name: mvn-cache
spec:
  storageClassName: nfs-csi
  accessModes:
  - ReadWriteMany
  resources:
    requests:
      storage: 1Gi
eof

5)创建cicd运行任务

# 克隆
apiVersion: tekton.dev/v1
kind: Task
metadata:
  name: git-clone
spec:
  description: Clone the code repository to the workspace.
  params:
  - name: url
    type: string
    default: ""
  - name: branch
    type: string
    default: "main"
  results:
  - name: version
  workspaces:
  - name: source
  steps:
  - name: git-clone
    image: alpine/git:2.40.1
    script: |
      sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories
      apk add tzdata
      cp /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
      echo "Asia/Shanghai" > /etc/timezone
      date
      echo "$(params.branch) -- $(params.url) -- $(workspaces.source.path)"
      git clone -b $(params.branch) -v $(params.url) $(workspaces.source.path)
      cd $(workspaces.source.path)
      latest_tag=`git tag --sort=-v:refname |head -n1`
      echo -n $latest_tag | tee $(results.version.path)
---
# 打包
apiVersion: tekton.dev/v1
kind: Task
metadata:
  name: build-to-pkg
spec:
  description: build application and package the files to image
  workspaces:
  - name: source
  steps:
  - name: build
    image: maven:3.8.7-openjdk-18-slim
    workingDir: $(workspaces.source.path)
    script: |
      ls -hltr
      sed -i -e '/\/mirrors/i\    <mirror>' \
      -e '/\/mirrors/i\      <id>aliyunmaven</id>' \
      -e '/\/mirrors/i\      <mirrorOf>*</mirrorOf>' \
      -e '/\/mirrors/i\      <name>阿里云公共仓库</name>' \
      -e '/\/mirrors/i\      <url>https://maven.aliyun.com/repository/public</url>' \
      -e '/\/mirrors/i\    </mirror>' \
      /usr/share/maven/conf/settings.xml
      mvn clean install
    volumeMounts:
    - name: mvn-cache
      mountPath: /root/.m2
  volumes:
  - name: mvn-cache
    persistentVolumeClaim:
      claimName: mvn-cache
---
# 生成镜像版本id
apiVersion: tekton.dev/v1
kind: Task
metadata:
  name: generate-build-id
spec:
  params:
  - name: version
    type: string
  results:
  - name: datetime
  - name: buildId
  steps:
  - name: generate-datetime
    image: busybox
    script: |
      #!/bin/sh
      datetime=`date +%Y%m%d-%H%M%S`
      echo -n ${datetime} | tee $(results.datetime.path)
  - name: generate-buildid
    image: busybox
    script: |
      #!/bin/sh
      buildDatetime=`cat $(results.datetime.path)`
      buildId="$(params.version)-${buildDatetime}"
      echo -n ${buildId} |tee $(results.buildId.path)
---
# 镜像构建上传
apiVersion: tekton.dev/v1
kind: Task
metadata:
  name: img-build
spec:
  description: package the application files to image
  params:
  - name: dockerfile
    default: Dockerfile
  - name: image-url
  - name: image-tag
    default: latest
  workspaces:
  - name: source
  - name: dockerconfig
    #将docker账号信息,挂载到kaniko容器中,用于推送镜像到仓库
    mountPath: /kaniko/.docker
  steps:
  - name: build-and-push-img
    image: m.daocloud.io/gcr.io/kaniko-project/executor:debug
    securityContext:
      runAsUser: 0
    command:
    - /kaniko/executor
    args:
    #选项解释:https://github.com/GoogleContainerTools/kaniko#additional-flags
    - --dockerfile=$(params.dockerfile)		#dockefile文件名
    - --context=$(workspaces.source.path)		#构建镜像时的工作目录
    - --destination=$(params.image-url):$(params.image-tag)	#镜像上传路径与标签
    #- --build-arg
    #- --cache
    #- --cache-dir
    #- --cache-repo
    #- --cache-copy-layers
    #- --cache-run-layers
    #- --cache-ttl duration
    #- --cleanup
    #- --compressed-caching
    #- --context-sub-path
    #- --custom-platform
    #- --digest-file
    #- --force
    #- --git
    #- --image-name-with-digest-file
    #- --image-name-tag-with-digest-file
    #- --insecure
    #- --insecure-pull
    #- --insecure-registry
    #- --label
    #- --log-format
    #- --log-timestamp
    #- --oci-layout-path
    #- --push-retry
    #- --registry-certificate
    #- --registry-client-cert
    #- --registry-mirror		#镜像下载加速地址,不需要写访问协议,只需写域名
    #- --skip-default-registry-fallback
    #- --reproducible
    #- --single-snapshot
    #- --skip-tls-verify
    #- --skip-push-permission-check
    #- --skip-tls-verify-pull
    #- --skip-tls-verify-registry
    #- --skip-unused-stages
    #- --snapshot-mode
    #- --tar-path
    #- --target
    #- --use-new-run
    #- --verbosity
    #- --ignore-var-run
    #- --ignore-path
    #- --image-fs-extract-retry
    #- --image-download-retry
---
# kubectl部署到集群
apiVersion: tekton.dev/v1
kind: Task
metadata:
  name: deploy-using-kubectl
spec:
  workspaces:
  - name: source
    description: The git repo
  params:
  - name: deploy-config-file
    description: The path to the yaml file to deploy within the git source
  - name: image-url
  - name: image-tag
  steps:
  - name: update-yaml
    image: alpine:3.16
    command: ["sed"]
    args:
    - "-i"
    - "-e"
    - "s@__IMAGE__@$(params.image-url):$(params.image-tag)@g"
    - "$(workspaces.source.path)/deploy/$(params.deploy-config-file)"
  - name: run-kubectl
    image: lachlanevenson/k8s-kubectl
    command: ["kubectl"]
    args:
    #当前部署的集群与kubectl相同集群,所以不需要传递kubeconfig
    - "apply"
    - "-f"
    - "$(workspaces.source.path)/deploy/$(params.deploy-config-file)"

6)创建pipeline,编排任务

apiVersion: tekton.dev/v1
kind: Pipeline
metadata:
  name: source-to-img
spec:
  params:
  - name: git-url
  - name: git-revision
    type: string
    default: main
  - name: img-build-context
    default: .
  - name: image-url
  - name: deploy-config-file
    default: all-in-one.yaml
  #- name: version
  #  type: string
  #  default: "v0.9"
  workspaces:
  - name: codebase
  - name: docker-config
  tasks:
  - name: git-clone
    taskRef:
      name: git-clone
    params:
    - name: url
      value: "$(params.git-url)"
    workspaces:
    - name: source
      workspace: codebase
  - name: build-to-pkg
    taskRef:
      name: build-to-pkg
    workspaces:
    - name: source
      workspace: codebase
    runAfter:
    - git-clone
  - name: generate-build-id
    taskRef:
      name: generate-build-id
    params:
    #直接从git-clone任务中获取最新的tag标签,然后生成镜像id。被注释的是手动执行版本
    - name: version
      value: "$(tasks.git-clone.results.version)"
      #value: "$(params.version)"
    runAfter: 
    - git-clone
  - name: img-build-push
    taskRef:
      name: img-build
    params:
    - name: image-url
      value: "$(params.image-url)"
    - name: image-tag
      value: "$(tasks.generate-build-id.results.buildId)"
    workspaces:
    - name: source
      workspace: codebase
    - name: dockerconfig
      workspace: docker-config
    runAfter:
    - build-to-pkg
    - generate-build-id
  - name: deploy-to-cluster
    taskRef:
      name: deploy-using-kubectl
    workspaces:
    - name: source
      workspace: codebase
    params:
    - name: deploy-config-file
      value: "$(params.deploy-config-file)"
    - name: image-url
      value: "$(params.image-url)"
    - name: image-tag
      value: "$(tasks.generate-build-id.results.buildId)"
    runAfter:
    - img-build-push

7)事件信息过滤触发器

对事件进行过滤,获取有效信息,并当做参数传给模板

apiVersion: triggers.tekton.dev/v1beta1
kind: TriggerBinding
metadata:
  name: gitlab-binding
spec:
  params:
  - name: git-revision
    value: $(body.checkout_sha)
  - name: git-repo-url
    value: $(body.repository.git_http_url)
  - name: image-url
    value: registry.cn-hangzhou.aliyuncs.com/suyanhj/spring-boot-helloworld
  #部署的版本,实际场景中应该从gitlab事件源中提取tag最新标签,而非手动指定
  #- name: version
  #  value: v0.9

8)触发器执行任务模板

事件侦听器通过触发器过滤事件后,获取到有效信息,转为参数传给触发器模板,然后实例化模板,运行实际的cicd流水线任务

apiVersion: triggers.tekton.dev/v1beta1
kind: TriggerTemplate
metadata:
  name: gitlab-trigger-tt
spec:
  params:  # 定义参数
  - name: git-revision
  - name: git-repo-url
  - name: image-url
  #- name: version
  resourcetemplates:
  - apiVersion: tekton.dev/v1beta1
    kind: PipelineRun
    metadata:
      generateName: gitlab-trigger-run-  # PipelineRun 名称前缀
    spec:
      serviceAccountName: default
      pipelineRef:
        name: source-to-img
      taskRunSpecs:
        - pipelineTaskName: deploy-to-cluster
          taskServiceAccountName: helloworld-admin
      #    taskPodTemplate:
      #      nodeSelector:
      #        disktype: ssd
      params:
        - name: git-url
          value: $(tt.params.git-repo-url)
        - name: git-revision
          value: $(tt.params.git-revision)
        - name: image-url
          value: $(tt.params.image-url)
        #- name: version
        #  value: $(tt.params.version)
      workspaces:
        - name: codebase
          volumeClaimTemplate:
            spec:
              accessModes:
                - ReadWriteMany
              resources:
                requests:
                  storage: 100Mi
              storageClassName: nfs-csi
        - name: docker-config
          secret:
            secretName: docker-config

9)定义事件侦听器

监听事件,过滤事件,并将过滤的有效事件交给触发器获取信息,再调用模板运行任务

apiVersion: triggers.tekton.dev/v1beta1
kind: EventListener
metadata:
  name: gitlab-event-listener 
spec:
  serviceAccountName: tekton-triggers-gitlab-sa
  triggers:
  - name: gitlab-push-events-trigger
    interceptors:
    - ref:
        name: "gitlab"
      params:
      - name: "secretRef"
        value:
          secretName: gitlab-webhook-token 
          secretKey: webhookToken
      - name: "eventTypes"
        value: 		#监听push、tag、合并事件
          - "Push Hook"
          - "Tag Push Hook"
          - "Merge Request Hook"
    bindings:
    - ref: gitlab-binding
    template:
      ref: gitlab-trigger-tt

10)解析gitlab webhook地址

kubectl port-forward deploy/el-gitlab-event-listener --address 0.0.0.0 8080

#为tekton配置一个虚拟ip
ip link a vip0 type dummy
ip add a 2.2.2.67/32 dev vip0


#gitlab主机中添加hosts解析,解析tekton的事件监听器地址
echo 2.2.2.67 el-gitlab-event-listener.default.svc.cluster.local >> /etc/hosts
curl el-gitlab-event-listener.default.svc.cluster.local:8080

在自己的本地gitlab中导入案例git仓库,地址:https://gitee.com/mageedu/spring-boot-helloWorld.git

image-20240105150822918

https、ssh协议自选,并配置为公开项目(此处是测试,所以配置方便访问,生产环境一般是私有,则需要配置访问gitlab的secret)image-20240105150950119

文件如下
image-20240105151732399

手动在仓库中创建webhook,我这里手动生成的token是:DXeqvozMlTA67aQB
订阅事件:推送、标签、合并请求image-20240105152008650

关闭tls验证image-20240105152055800

11)测试

#创建标签后,查看流水线运行情况
tkn pipelinerun ls
tkn pipelinerun logs -f gitlab-trigger-run-mnfpb

新建一个tag标签image-20240105160431714

新建标签后,事件监听器监听到tag事件,自动触发流水线构建任务image-20240105162727852

image-20240105162926993

pod运行成功
image-20240105163005434

镜像也是最新的镜像,此时,基于事件自动触发cicd流水线部署应用就完成了
image-20240105163115397

例4:例3的进阶版,更接近生产环境的示例

对获取最新tag方式做了调整,加入私有harbor配置

参考稀土掘金文章:基于tekton实现cicd流水线自动发布

posted @ 2024-01-06 23:24  suyanhj  阅读(77)  评论(0编辑  收藏  举报