​ 上一节我们是通过创建Pipelinerun来触发流水线来进行构建,实际生产中完全自动化的实现需要借助tekton中的triggers。本文是上篇的拓展请先了解这篇文章

Tekton Triggers 是一个 Tekton 组件,它允许您从各种来源的事件中检测和提取信息,TaskRunsPipelineRuns 根据该信息确定性地实例化和执行。Tekton 触发器还可以将从事件中提取的信息直接传递给TaskRunsPipelineRuns

#Triggers

Tekton Triggers包含下面几个CRD来对tekton进行拓展。

  • EventListener- 在 Kubernetes 集群上的指定端口监听事件。指定一个或多个Triggers
  • Trigger- 指定当EventListener检测到事件时会发生什么。ATrigger指定 a TriggerTemplate、 aTriggerBinding和可选的 an Interceptor
  • TriggerTemplate- 指定资源的蓝图,例如TaskRunPipelineRun,当您EventListener检测到事件时要实例化和/或执行该蓝图。它公开了您可以在资源模板中的任何位置使用的参数。
  • TriggerBinding- 指定要从中提取数据的事件有效负载中的字段以及对应的字段TriggerTemplate以填充提取的值。然后,您可以使用 中的填充字段TriggerTemplate来填充关联TaskRun或中的字段PipelineRun
  • ClusterTriggerBinding- 的集群范围版本,TriggerBinding对于在集群中重用特别有用。
  • Interceptor- 用于特定平台的“包罗万象”事件处理器,在TriggerBinding您执行有效负载过滤、验证(使用机密)、转换、定义和测试触发条件以及其他有用处理之前运行。一旦事件数据通过拦截器,它就会Trigger在您将有效负载数据传递给TriggerBinding.

git clone -->> make build -->> Kaniko

在这之后,我使用的tasks跟之前相比做了修改,为了方便大家,把它贴在下面。

apiVersion: tekton.dev/v1beta1
kind: Task
metadata:name: git-clonelabels:app.kubernetes.io/version: "0.6"annotations:tekton.dev/pipelines.minVersion: "0.29.0"tekton.dev/categories: Gittekton.dev/tags: gittekton.dev/displayName: "git clone"tekton.dev/platforms: "linux/amd64,linux/s390x,linux/ppc64le,linux/arm64"
spec:description: >-These Tasks are Git tasks to work with repositories used by other tasksin your Pipeline.The git-clone Task will clone a repo from the provided url into theoutput Workspace. By default the repo will be cloned into the root ofyour Workspace. You can clone into a subdirectory by setting this Task'ssubdirectory param. This Task also supports sparse checkouts. To performa sparse checkout, pass a list of comma separated directory patterns tothis Task's sparseCheckoutDirectories param.workspaces:- name: outputdescription: The git repo will be cloned onto the volume backing this Workspace.- name: ssh-directoryoptional: truedescription: |A .ssh directory with private key, known_hosts, config, etc. Copied tothe user's home before git commands are executed. Used to authenticatewith the git remote when performing the clone. Binding a Secret to thisWorkspace is strongly recommended over other volume types.- name: basic-authoptional: truedescription: |A Workspace containing a .gitconfig and .git-credentials file. Thesewill be copied to the user's home before any git commands are run. Anyother files in this Workspace are ignored. It is strongly recommendedto use ssh-directory over basic-auth whenever possible and to bind aSecret to this Workspace over other volume types.- name: ssl-ca-directoryoptional: truedescription: |A workspace containing CA certificates, this will be used by Git toverify the peer with when fetching or pushing over HTTPS.params:- name: urldescription: Repository URL to clone from.type: string- name: revisiondescription: Revision to checkout. (branch, tag, sha, ref, etc...)type: stringdefault: ""- name: branchdescription: Branch to usedefault: "master"- name: refspecdescription: Refspec to fetch before checking out revision.default: ""- name: submodulesdescription: Initialize and fetch git submodules.type: stringdefault: "true"- name: depthdescription: Perform a shallow clone, fetching only the most recent N commits.type: stringdefault: "1"- name: sslVerifydescription: Set the `http.sslVerify` global git config. Setting this to `false` is not advised unless you are sure that you trust your git remote.type: stringdefault: "true"- name: subdirectorydescription: Subdirectory inside the `output` Workspace to clone the repo into.type: stringdefault: ""- name: sparseCheckoutDirectoriesdescription: Define the directory patterns to match or exclude when performing a sparse checkout.type: stringdefault: ""- name: deleteExistingdescription: Clean out the contents of the destination directory if it already exists before cloning.type: stringdefault: "true"- name: httpProxydescription: HTTP proxy server for non-SSL requests.type: stringdefault: ""- name: httpsProxydescription: HTTPS proxy server for SSL requests.type: stringdefault: ""- name: noProxydescription: Opt out of proxying HTTP/HTTPS requests.type: stringdefault: ""- name: verbosedescription: Log the commands that are executed during `git-clone`'s operation.type: stringdefault: "true"- name: gitInitImagedescription: The image providing the git-init binary that this Task runs.type: stringdefault: "hub.17usoft.com/tekton/tekton-pipeline-git-init:v0.38.2" - name: userHomedescription: |Absolute path to the user's home directory. Set this explicitly if you are running the image as a non-root user or have overriddenthe gitInitImage param with an image containing custom user configuration.type: stringdefault: "/tekton/home"results:- name: commitdescription: The precise commit SHA that was fetched by this Task.- name: urldescription: The precise URL that was fetched by this Task.- description: The repo name represented by 'service-name' formatname: short-branch-nametype: stringsteps:- name: cloneimage: "$(params.gitInitImage)"env:- name: HOMEvalue: "$(params.userHome)"- name: PARAM_BRANCHvalue: $(params.branch)- name: PARAM_URLvalue: $(params.url)- name: PARAM_REVISIONvalue: $(params.revision)- name: PARAM_REFSPECvalue: $(params.refspec)- name: PARAM_SUBMODULESvalue: $(params.submodules)- name: PARAM_DEPTHvalue: $(params.depth)- name: PARAM_SSL_VERIFYvalue: $(params.sslVerify)- name: PARAM_SUBDIRECTORYvalue: $(params.subdirectory)- name: PARAM_DELETE_EXISTINGvalue: $(params.deleteExisting)- name: PARAM_HTTP_PROXYvalue: $(params.httpProxy)- name: PARAM_HTTPS_PROXYvalue: $(params.httpsProxy)- name: PARAM_NO_PROXYvalue: $(params.noProxy)- name: PARAM_VERBOSEvalue: $(params.verbose)- name: PARAM_SPARSE_CHECKOUT_DIRECTORIESvalue: $(params.sparseCheckoutDirectories)- name: PARAM_USER_HOMEvalue: $(params.userHome)- name: WORKSPACE_OUTPUT_PATHvalue: $(workspaces.output.path)- name: WORKSPACE_SSH_DIRECTORY_BOUNDvalue: $(workspaces.ssh-directory.bound)- name: WORKSPACE_SSH_DIRECTORY_PATHvalue: $(workspaces.ssh-directory.path)- name: WORKSPACE_BASIC_AUTH_DIRECTORY_BOUNDvalue: $(workspaces.basic-auth.bound)- name: WORKSPACE_BASIC_AUTH_DIRECTORY_PATHvalue: $(workspaces.basic-auth.path)- name: WORKSPACE_SSL_CA_DIRECTORY_BOUNDvalue: $(workspaces.ssl-ca-directory.bound)- name: WORKSPACE_SSL_CA_DIRECTORY_PATHvalue: $(workspaces.ssl-ca-directory.path)script: |#!/usr/bin/env shset -euif [ "${PARAM_VERBOSE}" = "true" ] ; thenset -xfiif [ "${WORKSPACE_BASIC_AUTH_DIRECTORY_BOUND}" = "true" ] ; thencp "${WORKSPACE_BASIC_AUTH_DIRECTORY_PATH}/.git-credentials" "${PARAM_USER_HOME}/.git-credentials"cp "${WORKSPACE_BASIC_AUTH_DIRECTORY_PATH}/.gitconfig" "${PARAM_USER_HOME}/.gitconfig"chmod 400 "${PARAM_USER_HOME}/.git-credentials"chmod 400 "${PARAM_USER_HOME}/.gitconfig"fiif [ "${WORKSPACE_SSH_DIRECTORY_BOUND}" = "true" ] ; thencp -R "${WORKSPACE_SSH_DIRECTORY_PATH}" "${PARAM_USER_HOME}"/.sshchmod 700 "${PARAM_USER_HOME}"/.sshchmod -R 400 "${PARAM_USER_HOME}"/.ssh/*fiif [ "${WORKSPACE_SSL_CA_DIRECTORY_BOUND}" = "true" ] ; thenexport GIT_SSL_CAPATH="${WORKSPACE_SSL_CA_DIRECTORY_PATH}"fiCHECKOUT_DIR="${WORKSPACE_OUTPUT_PATH}/${PARAM_SUBDIRECTORY}"cleandir() {# Delete any existing contents of the repo directory if it exists.## We don't just "rm -rf ${CHECKOUT_DIR}" because ${CHECKOUT_DIR} might be "/"# or the root of a mounted volume.if [ -d "${CHECKOUT_DIR}" ] ; then# Delete non-hidden files and directoriesrm -rf "${CHECKOUT_DIR:?}"/*# Delete files and directories starting with . but excluding ..rm -rf "${CHECKOUT_DIR}"/.[!.]*# Delete files and directories starting with .. plus any other characterrm -rf "${CHECKOUT_DIR}"/..?*fi}if [ "${PARAM_DELETE_EXISTING}" = "true" ] ; thencleandirfitest -z "${PARAM_HTTP_PROXY}" || export HTTP_PROXY="${PARAM_HTTP_PROXY}"test -z "${PARAM_HTTPS_PROXY}" || export HTTPS_PROXY="${PARAM_HTTPS_PROXY}"test -z "${PARAM_NO_PROXY}" || export NO_PROXY="${PARAM_NO_PROXY}"/ko-app/git-init \-url="${PARAM_URL}" \-revision="${PARAM_REVISION}" \-refspec="${PARAM_REFSPEC}" \-path="${CHECKOUT_DIR}" \-sslVerify="${PARAM_SSL_VERIFY}" \-submodules="${PARAM_SUBMODULES}" \-depth="${PARAM_DEPTH}" \-sparseCheckoutDirectories="${PARAM_SPARSE_CHECKOUT_DIRECTORIES}"cd "${CHECKOUT_DIR}"RESULT_SHA="$(git rev-parse HEAD)"EXIT_CODE="$?"if [ "${EXIT_CODE}" != 0 ] ; thenexit "${EXIT_CODE}"fiprintf "%s" "${RESULT_SHA}" > "$(results.commit.path)"printf "%s" "${PARAM_URL}" > "$(results.url.path)"- env:- name: PARAM_URLvalue: $(params.url)- name: PARAM_REVISIONvalue: $(params.revision)- name: PARAM_BRANCHvalue: $(params.branch)- name: WORKSPACE_OUTPUT_PATHvalue: $(workspaces.output.path)- name: PARAM_SUBDIRECTORYvalue: $(params.subdirectory)image: $(params.gitInitImage)name: prepare-outputsresources: {}script: |set -eugit config --global --add safe.directory "*" CHECKOUT_DIR="${WORKSPACE_OUTPUT_PATH}/${PARAM_SUBDIRECTORY}"cd "${CHECKOUT_DIR}"RESULT_SHORT_BRANCH_NAME="$(basename $PARAM_BRANCH)"RESULT_SHA="$(git rev-parse --short HEAD)"echo "###Results:"echo "branch: " $RESULT_SHORT_BRANCH_NAMEecho "commit: " $RESULT_SHAecho -n $RESULT_SHORT_BRANCH_NAME | tee > "$(results.short-branch-name.path)"echo -n $RESULT_SHA | tee > "$(results.commit.path)"echo -n $PARAM_URL | tee > "$(results.url.path)"
---
apiVersion: tekton.dev/v1beta1
kind: Task
metadata:name: golang-buildlabels:app.kubernetes.io/version: "0.3"annotations:tekton.dev/pipelines.minVersion: "0.12.1"tekton.dev/categories: Build Toolstekton.dev/tags: build-tooltekton.dev/displayName: "golang build"tekton.dev/platforms: "linux/amd64,linux/s390x,linux/ppc64le"
spec:description: >-This Task is Golang task to build Go projects.params:
#  - name: package
#    description: base package to build in- name: packagesdescription: "packages to build (default: ./cmd/...)"default: "./cmd/..."- name: subdirectorydescription: subdirectory inside the "source"default: "./"- name: versiondescription: golang version to use for buildsdefault: "latest"- name: flagsdescription: flags to use for the test commanddefault: -v- name: GOOSdescription: "running program's operating system target"default: linux- name: GOARCHdescription: "running program's architecture target"default: amd64- name: GO111MODULEdescription: "value of module support"default: auto- name: GOCACHEdescription: "Go caching directory path"default: ""- name: GOMODCACHEdescription: "Go mod caching directory path"default: ""- name: CGO_ENABLEDdescription: "Toggle cgo tool during Go build. Use value '0' to disable cgo (for static builds)."default: ""- name: GOSUMDBdescription: "Go checksum database url. Use value 'off' to disable checksum validation."default: ""workspaces:- name: sourcesteps:- name: buildimage: hub.17usoft.com/gstrain/golang:v1.18.3workingDir: $(workspaces.source.path)script: |if [ ! -e $GOPATH/src/$(params.subdirectory)/go.mod ];thenSRC_PATH="$GOPATH/src/$(params.subdirectory)"mkdir -p $SRC_PATHcp -R "$(workspaces.source.path)"/$(params.subdirectory)/* $SRC_PATHcd $SRC_PATHfigo build -tags netgo  $(params.flags) $(params.packages)pwd && ls -lenv:- name: GOOSvalue: "$(params.GOOS)"- name: GOARCHvalue: "$(params.GOARCH)"- name: GO111MODULEvalue: "$(params.GO111MODULE)"- name: GOCACHEvalue: "$(params.GOCACHE)"- name: GOMODCACHEvalue: "$(params.GOMODCACHE)"- name: CGO_ENABLEDvalue: "$(params.CGO_ENABLED)"- name: GOSUMDBvalue: "$(params.GOSUMDB)"
---
apiVersion: tekton.dev/v1beta1
kind: Task
metadata:name: kanikolabels:app.kubernetes.io/version: "0.6"annotations:tekton.dev/pipelines.minVersion: "0.17.0"tekton.dev/categories: Image Buildtekton.dev/tags: image-buildtekton.dev/displayName: "Build and upload container image using Kaniko"tekton.dev/platforms: "linux/amd64"
spec:description: >-This Task builds a simple Dockerfile with kaniko and pushes to a registry.This Task stores the image name and digest as results, allowing Tekton Chains to pick upthat an image was built & sign it.params:- name: IMAGEdescription: Name (reference) of the image to build.- name: DOCKERFILEdescription: Path to the Dockerfile to build.default: ./Dockerfile- name: CONTEXTdescription: The build context used by Kaniko.default: ./- name: EXTRA_ARGStype: arraydefault: []- name: BUILDER_IMAGEdescription: The image on which builds will run (default is v1.5.1)default: hub.17usoft.com/tekton/kaniko-executor:v1.5.1workspaces:- name: sourcedescription: Holds the context and Dockerfile- name: dockerconfigdescription: Includes a docker `config.json`optional: truemountPath: /kaniko/.dockerresults:- name: IMAGE_DIGESTdescription: Digest of the image just built.- name: IMAGE_URLdescription: URL of the image just built.steps:- image: 'docker.io/library/bash:5.1.4@sha256:b208215a4655538be652b2769d82e576bc4d0a2bb132144c060efc5be8c3f5d6'name: check-dockerconfigresources: {}script: |ls -al /kaniko/.dockercat /kaniko/.docker/config.json- name: build-and-pushworkingDir: $(workspaces.source.path)image: $(params.BUILDER_IMAGE)args:- $(params.EXTRA_ARGS)- --dockerfile=$(params.DOCKERFILE)- --context=$(workspaces.source.path)/$(params.CONTEXT) # The user does not need to care the workspace and the source.- --destination=$(params.IMAGE)- --digest-file=$(results.IMAGE_DIGEST.path)securityContext:runAsUser: 0- name: write-urlimage: docker.io/library/bash:5.1.4@sha256:b208215a4655538be652b2769d82e576bc4d0a2bb132144c060efc5be8c3f5d6script: |set -eimage="$(params.IMAGE)"echo -n "${image}" | tee "$(results.IMAGE_URL.path)"

Modify listing

​ 我们上节结尾处跟大家讲了,我们会添加一个新的任务。当我们完成镜像推送后自动修改配置仓库中yaml信息。

---
apiVersion: tekton.dev/v1beta1
kind: Task
metadata:name: modify-listinglabels:app.kubernetes.io/version: "0.4"annotations:tekton.dev/pipelines.minVersion: "0.21.0"tekton.dev/categories: Gittekton.dev/tags: gittekton.dev/displayName: "git cli"tekton.dev/platforms: "linux/amd64,linux/s390x,linux/ppc64le"
spec:description: >-This task can be used to perform git operations.Git command that needs to be run can be passed as a script tothe task. This task needs authentication to git in order to pushafter the git operation.workspaces:- name: sourcedescription: A workspace that contains the fetched git repository.- name: inputoptional: truedescription: |An optional workspace that contains the files that need to be added to git. You canaccess the workspace from your script using `$(workspaces.input.path)`, for instance:cp $(workspaces.input.path)/file_that_i_want .git add file_that_i_want# etc- name: ssh-directoryoptional: truedescription: |A .ssh directory with private key, known_hosts, config, etc. Copied tothe user's home before git commands are executed. Used to authenticatewith the git remote when performing the clone. Binding a Secret to thisWorkspace is strongly recommended over other volume types.- name: basic-authoptional: truedescription: |A Workspace containing a .gitconfig and .git-credentials file. Thesewill be copied to the user's home before any git commands are run. Anyother files in this Workspace are ignored. It is strongly recommendedto use ssh-directory over basic-auth whenever possible and to bind aSecret to this Workspace over other volume types.params:- name: BASE_IMAGEdescription: |The base image for the task.type: stringdefault:  "cnych/helm-kubectl-curl-git-jq-yq "- name: GIT_USER_NAMEtype: stringdescription: |Git user name for performing git operation.default: "Administrator"- name: GIT_USER_EMAILtype: stringdescription: |Git user email for performing git operation.default: "1376252133@qq.com"- name: subdirectorytype: stringdefault: ""- name: IMAGE_URLtype: stringdescription: |The latest build imagedefault: "$(tasks.kaniko.results.IMAGE_URL)"- name: GIT_SCRIPTdescription: The git script to run.type: stringdefault: |cd web-service git clone --branch master --depth 1  http://tekton-pipelines:z7FavbPhfEGrghsdCU5h@10.177.9.244:31002/tekton/project.git repocd "repo/web-service"ls -lecho old value:cat 02-deployment.yaml | yq r - 'spec.template.spec.containers[0].image'echo replacing with new value:yq w -i 02-deployment.yaml 'spec.template.spec.containers[0].image' "${IMAGE_URL}"echo verifying new value :yq r 02-deployment.yaml spec.template.spec.containers[0].imageif ! git diff-index --quiet HEAD --; thengit statusgit add .git commit -m "auto updated yaml by tekton pipeline"git pushelseecho "no changes, git repository is up to date"fi- name: USER_HOMEdescription: |Absolute path to the user's home directory. Set this explicitly if you are running the image as a non-root user or have overriddenthe gitInitImage param with an image containing custom user configuration.type: stringdefault: "/root"- name: VERBOSEdescription: Log the commands that are executed during `git-clone`'s operation.type: stringdefault: "true"results:- name: commitdescription: The precise commit SHA after the git operation.steps:- name: gitimage: $(params.BASE_IMAGE)workingDir: $(workspaces.source.path)env:- name: HOMEvalue: $(params.USER_HOME)- name: PARAM_VERBOSEvalue: $(params.VERBOSE)- name: PARAM_USER_HOMEvalue: $(params.USER_HOME)- name: WORKSPACE_OUTPUT_PATHvalue: $(workspaces.output.path)- name: WORKSPACE_SSH_DIRECTORY_BOUNDvalue: $(workspaces.ssh-directory.bound)- name: WORKSPACE_SSH_DIRECTORY_PATHvalue: $(workspaces.ssh-directory.path)- name: WORKSPACE_BASIC_AUTH_DIRECTORY_BOUNDvalue: $(workspaces.basic-auth.bound)- name: WORKSPACE_BASIC_AUTH_DIRECTORY_PATHvalue: $(workspaces.basic-auth.path)- name: IMAGE_URLvalue: $(params.IMAGE_URL)script: |#!/usr/bin/env shset -eu# Setting up the config for the git.git config --global user.email "$(params.GIT_USER_EMAIL)"git config --global user.name "$(params.GIT_USER_NAME)"eval '$(params.GIT_SCRIPT)'

​ 聪明的朋友已经看到了,我们这个任务主要的信息定义在$ GIT_SCRIPT ,其实很简单,就是把我们的清单从git上拉去下来通过yq工具来修改image信息,修改成功之后在推送到我们的代码库中。

Triggers创建

我们通过 EventListener 指定触发器,文件如下:

EventListener

apiVersion: triggers.tekton.dev/v1beta1
kind: EventListener
metadata:name: gitlab-listener
spec:serviceAccountName: tekton-triggers-gstrain-saresources:kubernetesResource:serviceType: NodePort triggers:- name: gitlab-push-events-triggerbindings:                      #TriggerBinding 对象- name: gitrevisionvalue: $(body.checkout_sha)- name: gitrepositoryurlvalue: $(body.repository.git_http_url)  - name: service-namevalue: $(body.repository.name)- name: gitrefvalue: $(body.ref)interceptors:- name: "verify-gitlab-payload"ref:name: "gitlab"kind: ClusterInterceptorparams:- name: secretRefvalue:secretName: "gitlab-secret"secretKey: "secretToken"- name: eventTypesvalue:- "Push Hook" #接收gitlab push 事件template:ref: triggertemplate   #TriggerTemplate 对象

因为EventListener 创建完成后会生成一个Listener服务,用来接收事件的响应。我是直接选择的NodePort来对外提供服务,使用路由的可忽略。

[root@master pipeline]# kubectl get svc
NAME                                TYPE        CLUSTER-IP       EXTERNAL-IP   PORT(S)                              AGE
el-gitlab-listener                  NodePort    10.253.177.9     <none>        8080:39949/TCP,9000:47734/TCP        3d7h

Secret

通过secrets来配置gitlab发送webhook时请求的校验

apiVersion: v1
kind: Secret
metadata:name: github-secret
type: Opaque
stringData:secretToken: "tekton-pipeline-123"

gitlabToken添加流程

–>> project -->> settings -->> webhooks -->> url(Listener服务URL) -->> secret token(github-secret资源)

RBAC

triggers中各个资源的访问,需要声名RBAC

---
apiVersion: v1
kind: ServiceAccount
metadata:name: tekton-triggers-gstrain-sa
secrets:- name: gitlab-secret- name: gitlab-auth
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:name: triggers-gstrain-eventlistener-binding
subjects:
- kind: ServiceAccountname: tekton-triggers-gstrain-sa
roleRef:apiGroup: rbac.authorization.k8s.iokind: ClusterRolename: tekton-triggers-eventlistener-roles
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:name: triggers-gstrain-eventlistener-clusterbinding
subjects:
- kind: ServiceAccountname: tekton-triggers-gstrain-sanamespace: gstrain-pipeline
roleRef:apiGroup: rbac.authorization.k8s.iokind: ClusterRolename: tekton-triggers-eventlistener-clusterroles

TriggerBinding

指定要从中提取数据的事件有效负载中的字段以及对应的字段,具体指的是哪些字段呢。其实这里所说的是gitlab webhook中发送来的请求,这些字段都可以被我们拿来利用。

bindings:                        #TriggerBinding 对象- name: gitrevisionvalue: $(body.checkout_sha)- name: gitrepositoryurlvalue: $(body.repository.git_http_url)  - name: service-namevalue: $(body.repository.name)- name: gitrefvalue: $(body.ref)
{"object_kind": "push","event_name": "push","before": "68e0d3b62814596f5988d1db668df6da787f6b00","after": "6e4977fb359fdde13d3f21ed7ac739102841e4ce","ref": "refs/heads/master","checkout_sha": "6e4977fb359fdde13d3f21ed7ac739102841e4ce","message": null,"user_id": 1,"user_name": "gstrain","user_username": "gstrain","user_email": "","user_avatar": "https://www.gravatar.com/avatar/5ccc082a1092ca51760a7b3956c04abc?s=80&d=identicon","project_id": 4,"project": {"id": 4,"name": "web-service","description": "","web_url": "http://gitlab-6859ff885-96p66/gstrain/web-service","avatar_url": null,"git_ssh_url": "git@gitlab-6859ff885-96p66:gstrain/web-service.git","git_http_url": "http://10.177.9.244:31002/gstrain/web-service.git","namespace": "gstrain","visibility_level": 20,"path_with_namespace": "gstrain/web-service","default_branch": "main","ci_config_path": null,"homepage": "http://gitlab-6859ff885-96p66/gstrain/web-service","url": "git@gitlab-6859ff885-96p66:gstrain/web-service.git","ssh_url": "git@gitlab-6859ff885-96p66:gstrain/web-service.git","http_url": "http://10.177.9.244:31002/gstrain/web-service.git"},"commits": [{"id": "6e4977fb359fdde13d3f21ed7ac739102841e4ce","message": "z\n","title": "z","timestamp": "2022-08-22T17:46:04+08:00","url": "http://gitlab-6859ff885-96p66/gstrain/web-service/-/commit/6e4977fb359fdde13d3f21ed7ac739102841e4ce","author": {"name": "Administrator","email": "1376252133@qq.com"},"added": [],"modified": ["Jenkinsfile"],"removed": []}],"total_commits_count": 1,"push_options": {},"repository": {"name": "web-service","url": "git@gitlab-6859ff885-96p66:gstrain/web-service.git","description": "","homepage": "http://gitlab-6859ff885-96p66/gstrain/web-service","git_http_url": "http://10.177.9.244:31002/gstrain/web-service.git","git_ssh_url": "git@gitlab-6859ff885-96p66:gstrain/web-service.git","visibility_level": 20}
}

TriggerTemplate

接下来到了我们最重要的环节,我们可以通过读取 TriggerBinding 定义的参数,定义如下TriggerTemplate ,我们这里定义的是一个 PipelineRun 的模板,需要选定一个定义好的pipeline

---
apiVersion: triggers.tekton.dev/v1alpha1
kind: TriggerTemplate
metadata:name: triggertemplate
spec:params:- name: gitrevisiondescription: The git revisiondefault: master- name: gitrepositoryurldescription: The git repository url- name: service-namedescription: The service name- name: gitrefdescription: The branch to checkoutresourcetemplates:- apiVersion: tekton.dev/v1beta1kind: PipelineRunmetadata:generateName: $(tt.params.service-name)-pipeline-labels:service: $(tt.params.service-name)namespace: gstrain-pipelinespec:params:- name: git-http-urlvalue: $(tt.params.gitrepositoryurl)- name: git-revisionvalue: $(tt.params.gitrevision)- name: service-namevalue: $(tt.params.service-name)        - name: git-refvalue: $(tt.params.gitref)- name: subdirectoryvalue: $(tt.params.service-name)
#          - name: package
#            value: $(tt.params.service-name)serviceAccountName: tekton-triggers-gstrain-sapipelineRef:name: gstrain-pipelineworkspaces:- name: shared-datapersistentVolumeClaim:claimName: my-app- name: dockerconfigsecret:secretName: dockerconfig
#        - name: git-basic-auth
#          secret:
#            secretName: git-basic-auth

#结果

​ 最后让我们git push来触发我们的triggers,测试下我们的流程是否正常,在kubernetes集群中可查看相应的pod任务。

[root@master ~]# kubectl get pod -l triggers.tekton.dev/eventlistener=gitlab-listener
NAME                                              READY   STATUS      RESTARTS   AGE
web-service-pipeline-pcpsl-change-manifests-pod   0/1     Completed   0          4h37m
web-service-pipeline-pcpsl-fetch-repo-pod         0/2     Completed   0          4h38m
web-service-pipeline-pcpsl-golang-build-pod       0/1     Completed   0          4h38m
web-service-pipeline-pcpsl-kaniko-pod             0/3     Completed   0          4h37m

到这我们的tekton构建CI/CD就已经全部完成,

【 云原生 | kubernetes 】- tekton构建CI/CD流水线(二)相关推荐

  1. 【云原生】什么是 CI/CD ? | 摆平交付障碍的 CI/CD

    [云原生]什么是 CI/CD ?| 软件交付中常见的问题 在前文中,我们了解到了软件交付过程中的一些常见做法,以及它们所导致的一系列问题.这些问题成为了软件交付的一个又一个绊脚石,如何解决这些棘手的问 ...

  2. 使用 Kubernetes 和滴滴云 Docker 仓库构建 CI/CD 流水线

    写在前面:<Kubernetes Tutorials> 系列文章旨在帮助您从入门到高阶逐步了解并掌握kubernetes技术栈的实操.理论和最佳实践.主题将包括 Docker 基础与实操. ...

  3. 【云原生】什么是 CI/CD ?| 软件交付中常见的问题

    许多年来,一代又一代的 IT 人像西西弗斯一样,孜孜不倦地追求着一个目标--用最快的速度将质量最好的软件交付给用户.极为幸运的是,我们并没有遭遇西西弗斯式的悲剧,一次又一次在巨石就快到达山顶时前功尽弃 ...

  4. 如何使用GitLab和Rancher构建CI/CD流水线–Part 1

    介绍 GitLab核心是集成管理Git存储库的工具.比如你希望创建一个提供服务的平台,那么GitLab将提供强大的身份验证和授权机制.工作组.问题跟踪.wiki和片段,除此之外还有公有.内部和私有存储 ...

  5. 从零到一构建CI/CD的DevOps自动化流水线,需要考虑的开源项目

    构建CI/CD的DevOps自动化流水线的步骤 1.DevOps 和 CI/CD 流水线的简要介绍 2 构建CI/CD流水线需考虑的步骤 第一步:CI/CD 框架 第二步:源代码控制管理 第三步:自动 ...

  6. 如何从零开始搭建 CI/CD 流水线

    来源 | Saurabh Kulshrestha 译者 | 徐进 持续集成和持续部署成为现代 DevOps 趋势下的重要环节,很多角色岗位都要求 CI/CD 的相关技能.本文介绍了什么是 CI/CD ...

  7. 了解CI/CD流水线

    自动化流水线在CI/CD(持续集成/持续交付或持续部署)的实践中发挥着核心作用.本文将对什么是CI/CD流水线.如何构建CI/CD流水线进行讨论. *持续集成:Continuous Integrati ...

  8. 云原生应用的构建之路

    首发:巨子嘉     作者:巨子嘉 云计算的拐点已至,进入成熟期,云原生成为驱动云计算发展的新动力引擎,致力于成为新型基础设施,不仅是企业数字化转型的最佳技术路径,同时也成为新兴领域,人工智能.大数据 ...

  9. 什么是CI/CD流水线?

    在CI/CD和DevOps领域中,持续交付和持续部署是一个老生常谈的话题.持续集成这个术语最早是在1994年由Grady Booch提出.微服务提出者Martin Flower在2014年发表的论文& ...

最新文章

  1. 【tensorflow】OP_REQUIRES failed at variable_ops.cc:104 Already exists: Resource
  2. CentOS系统快捷方式设置
  3. RedHat7.1 安装Oracle12102
  4. rgb fusion检测不到显卡_买不到RX 6800XT就装不了机解不了馋?我看未必
  5. 深入理解Memory Order
  6. leetcode 寻找两个有序数组的中位数
  7. php 判断用户是否刷新,ajax php 实现无刷新用户检查是否存在
  8. PHP程序员如何突破成长瓶颈(php开发三到四年)
  9. manacher算法学习(求最长回文子串长度)
  10. Audiolatry RetroVibes for Mac - 虚拟乐器插件
  11. 按ASCII码给json对象排序
  12. ts无损剪辑合并_视频如何合并?视频合并太难?其实很简单
  13. 阿里云视频点播 和HLS加密解密
  14. 全微分里dxy是怎么化成xdy+ydx
  15. 京东2020校招数据分析工程师二面(2019.9.18)
  16. 从PC到Mac —— 写给Mac新新手的入门教程
  17. mysql没开启binlog恢复删除表_无全量备份、未开启binlog日志,利用percona工具恢复delete的数据...
  18. 奇点临近?人工智能v.s.人脑智能
  19. 上可以替代mobaxterm_电能替代 | 基于逻辑回归模型的电能替代用户辨识研究
  20. 1010: 平行四边形

热门文章

  1. Python 路径操作
  2. 嵌入式系统之ucLinux与uc/os-II的比较
  3. php redis 挂掉,redis中的宕机什么意思
  4. Angular Landing – Material Design Angular App Landing Page
  5. Android在CMD中输入adb命令,提示“'adb' 不是内部或外部命令,也不是可运行的程序”的解决方法
  6. ‘adb‘ 不是内部或外部命令,也不是可运行的程序 或批处理文件—解决方法
  7. 九章量子计算机应用,“九章”量子计算机这么牛,到底有什么用? |【经纬低调分享】...
  8. 有什么好用的gif制作软件 制作GIF表情包教程
  9. windows杀死进程
  10. jQuery弹出插件thickbox使用心得