kubernetes的DevOps业务(五):Jenkins,GitLab,Harbor,Tekton,GitOps

触发器和事件监听器

前面我们都是通过创建一个 TaskRun 或者一个 PipelineRun 对象来触发任务,但是在实际的工作中更多的是开发人员提交代码过后来触发任务,这个时候就需要用到 Tekton 里面的 Triggers 概念了。(就是手动和自动的区别)
在这里插入图片描述
Triggers 同样通过下面的几个 CRD 对象对 Tekton 进行了一些扩展:

1.TriggerTemplate: 创建资源的模板,比如用来创建 PipelineResource 和 PipelineRun
2.TriggerBinding: 校验事件并提取相关字段属性
3.ClusterTriggerBinding: 和 TriggerBinding 类似,只是是全局的
4.Interceptor: 处理事件以进行自定义验证或过滤
5.EventListener: 连接 TriggerBinding 和 TriggerTemplate 到事件接收器,使用从各个 TriggerBinding 中提取的参数来创建 TriggerTemplate 中指定的 resources,同样通过 interceptor 字段来指定外部服务对事件属性进行预处理
(trigger触发,intercept拦截)

在这里插入图片描述
同样要使用 Tekton Triggers 就需要安装对应的控制器,可以直接通过 tektoncd/triggers 的 GitHub 仓库说明进行安装,如下所示的命令(需要注意 v0.14.2 版本需要安装两个资源清单)

kubectl apply --filename https://storage.googleapis.com/tekton-releases/triggers/previous/v0.14.2/release.yaml
kubectl apply -f https://storage.googleapis.com/tekton-releases/triggers/previous/v0.14.2/interceptors.yaml

同样由于官方使用的镜像是 gcr 的镜像,所以正常情况下我们是获取不到的,如果你的集群由于某些原因获取不到镜像,可以使用阿里云或者dockerhub.com下的镜像,然后打标签,或者直接改稳进中的镜像地址

放上我修改后的文件(1231行开始是interceptors.yaml)
release.yaml:
# Copyright 2019 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: policy/v1beta1
kind: PodSecurityPolicy
metadata:
  name: tekton-triggers
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
spec:
  privileged: false
  allowPrivilegeEscalation: false
  volumes:
    - 'emptyDir'
    - 'configMap'
    - 'secret'
  hostNetwork: false
  hostIPC: false
  hostPID: false
  runAsUser:
    rule: 'MustRunAsNonRoot'
  seLinux:
    rule: 'RunAsAny'
  supplementalGroups:
    rule: 'MustRunAs'
    ranges:
      - min: 1
        max: 65535
  fsGroup:
    rule: 'MustRunAs'
    ranges:
      - min: 1
        max: 65535

---
# Copyright 2019 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: tekton-triggers-admin
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
rules:
  - apiGroups: [""]
    resources: ["configmaps", "services", "events"]
    verbs: ["get", "list", "create", "update", "delete", "patch", "watch"]
  - apiGroups: ["apps"]
    resources: ["deployments", "deployments/finalizers"]
    verbs: ["get", "list", "create", "update", "delete", "patch", "watch"]
  - apiGroups: ["admissionregistration.k8s.io"]
    resources: ["mutatingwebhookconfigurations", "validatingwebhookconfigurations"]
    verbs: ["get", "list", "create", "update", "delete", "patch", "watch"]
  - apiGroups: ["triggers.tekton.dev"]
    resources: ["clustertriggerbindings", "clusterinterceptors", "eventlisteners", "triggerbindings", "triggertemplates", "triggers", "eventlisteners/finalizers"]
    verbs: ["get", "list", "create", "update", "delete", "patch", "watch"]
  - apiGroups: ["triggers.tekton.dev"]
    resources: ["clustertriggerbindings/status", "clusterinterceptors/status", "eventlisteners/status", "triggerbindings/status", "triggertemplates/status", "triggers/status"]
    verbs: ["get", "list", "create", "update", "delete", "patch", "watch"]
  # We uses leases for leaderelection
  - apiGroups: ["coordination.k8s.io"]
    resources: ["leases"]
    verbs: ["get", "list", "create", "update", "delete", "patch", "watch"]
  - apiGroups: ["serving.knative.dev"]
    resources: ["*", "*/status", "*/finalizers"]
    verbs: ["get", "list", "create", "update", "delete", "deletecollection", "patch", "watch"]
---
kind: ClusterRole
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: tekton-triggers-core-interceptors
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
rules:
  - apiGroups: [""]
    resources: ["secrets"]
    verbs: ["get", "list", "watch"]

---
# Copyright 2020 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# NOTE:  when multi-tenant EventListener progresses, moving this Role
# to a ClusterRole is not the advisable path.  Additional Roles that
# adds access to Secrets to the Namespaces managed by the multi-tenant
# EventListener is what should be done.  While not as simple, it avoids
# giving access to K8S system level, cluster admin privileged level Secrets

kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: tekton-triggers-admin
  namespace: tekton-pipelines
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
rules:
  - apiGroups: ["policy"]
    resources: ["podsecuritypolicies"]
    resourceNames: ["tekton-triggers"]
    verbs: ["use"]
---
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: tekton-triggers-admin-webhook
  namespace: tekton-pipelines
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
rules:
  - apiGroups: ["policy"]
    resources: ["podsecuritypolicies"]
    resourceNames: ["tekton-triggers"]
    verbs: ["use"]
  - apiGroups: [""]
    resources: ["secrets"]
    verbs: ["get", "list", "create", "update", "delete", "patch", "watch"]
---
kind: Role
apiVersion: rbac.authorization.k8s.io/v1
metadata:
  name: tekton-triggers-core-interceptors
  namespace: tekton-pipelines
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
rules:
  - apiGroups: ["policy"]
    resources: ["podsecuritypolicies"]
    resourceNames: ["tekton-triggers"]
    verbs: ["use"]
  - apiGroups: [""]
    resources: ["configmaps"]
    verbs: ["get", "list", "watch"]

---
# Copyright 2019 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: v1
kind: ServiceAccount
metadata:
  name: tekton-triggers-controller
  namespace: tekton-pipelines
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: tekton-triggers-webhook
  namespace: tekton-pipelines
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: tekton-triggers-core-interceptors
  namespace: tekton-pipelines
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers

---
# Copyright 2019 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: tekton-triggers-controller-admin
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
subjects:
  - kind: ServiceAccount
    name: tekton-triggers-controller
    namespace: tekton-pipelines
roleRef:
  kind: ClusterRole
  name: tekton-triggers-admin
  apiGroup: rbac.authorization.k8s.io
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: tekton-triggers-webhook-admin
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
subjects:
  - kind: ServiceAccount
    name: tekton-triggers-webhook
    namespace: tekton-pipelines
roleRef:
  kind: ClusterRole
  name: tekton-triggers-admin
  apiGroup: rbac.authorization.k8s.io
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: tekton-triggers-core-interceptors
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
subjects:
  - kind: ServiceAccount
    name: tekton-triggers-core-interceptors
    namespace: tekton-pipelines
roleRef:
  kind: ClusterRole
  name: tekton-triggers-core-interceptors
  apiGroup: rbac.authorization.k8s.io

---
# Copyright 2020 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: tekton-triggers-controller-admin
  namespace: tekton-pipelines
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
subjects:
  - kind: ServiceAccount
    name: tekton-triggers-controller
    namespace: tekton-pipelines
roleRef:
  kind: Role
  name: tekton-triggers-admin
  apiGroup: rbac.authorization.k8s.io
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: tekton-triggers-webhook-admin
  namespace: tekton-pipelines
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
subjects:
  - kind: ServiceAccount
    name: tekton-triggers-webhook
    namespace: tekton-pipelines
roleRef:
  kind: Role
  name: tekton-triggers-admin-webhook
  apiGroup: rbac.authorization.k8s.io
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
  name: tekton-triggers-core-interceptors
  namespace: tekton-pipelines
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
subjects:
  - kind: ServiceAccount
    name: tekton-triggers-core-interceptors
    namespace: tekton-pipelines
roleRef:
  kind: Role
  name: tekton-triggers-core-interceptors
  apiGroup: rbac.authorization.k8s.io

---
# Copyright 2021 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: clusterinterceptors.triggers.tekton.dev
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
    triggers.tekton.dev/release: "v0.14.2"
    version: "v0.14.2"
spec:
  group: triggers.tekton.dev
  scope: Cluster
  names:
    kind: ClusterInterceptor
    plural: clusterinterceptors
    singular: clusterinterceptor
    shortNames:
      - ci
    categories:
      - tekton
      - tekton-triggers
  versions:
    - name: v1alpha1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          # One can use x-kubernetes-preserve-unknown-fields: true
          # at the root of the schema (and inside any properties, additionalProperties)
          # to get the traditional CRD behaviour that nothing is pruned, despite
          # setting spec.preserveUnknownProperties: false.
          #
          # See https://kubernetes.io/blog/2019/06/20/crd-structural-schema/
          # See issue: https://github.com/knative/serving/issues/912
          x-kubernetes-preserve-unknown-fields: true
      # Opt into the status subresource so metadata.generation
      # starts to increment
      subresources:
        status: {
    
    }

---
# Copyright 2019 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: clustertriggerbindings.triggers.tekton.dev
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
    triggers.tekton.dev/release: "v0.14.2"
    version: "v0.14.2"
spec:
  group: triggers.tekton.dev
  scope: Cluster
  names:
    kind: ClusterTriggerBinding
    plural: clustertriggerbindings
    singular: clustertriggerbinding
    shortNames:
      - ctb
    categories:
      - tekton
      - tekton-triggers
  versions:
    - name: v1alpha1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          # One can use x-kubernetes-preserve-unknown-fields: true
          # at the root of the schema (and inside any properties, additionalProperties)
          # to get the traditional CRD behaviour that nothing is pruned, despite
          # setting spec.preserveUnknownProperties: false.
          #
          # See https://kubernetes.io/blog/2019/06/20/crd-structural-schema/
          # See issue: https://github.com/knative/serving/issues/912
          x-kubernetes-preserve-unknown-fields: true
      subresources:
        status: {
    
    }

---
# Copyright 2019 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: eventlisteners.triggers.tekton.dev
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
    triggers.tekton.dev/release: "v0.14.2"
    version: "v0.14.2"
spec:
  group: triggers.tekton.dev
  scope: Namespaced
  names:
    kind: EventListener
    plural: eventlisteners
    singular: eventlistener
    shortNames:
      - el
    categories:
      - tekton
      - tekton-triggers
  versions:
    - name: v1alpha1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          # One can use x-kubernetes-preserve-unknown-fields: true
          # at the root of the schema (and inside any properties, additionalProperties)
          # to get the traditional CRD behaviour that nothing is pruned, despite
          # setting spec.preserveUnknownProperties: false.
          #
          # See https://kubernetes.io/blog/2019/06/20/crd-structural-schema/
          # See issue: https://github.com/knative/serving/issues/912
          x-kubernetes-preserve-unknown-fields: true
      # Opt into the status subresource so metadata.generation
      # starts to increment
      subresources:
        status: {
    
    }
      additionalPrinterColumns:
        - name: Address
          type: string
          jsonPath: .status.address.url
        - name: Available
          type: string
          jsonPath: ".status.conditions[?(@.type=='Available')].status"
        - name: Reason
          type: string
          jsonPath: ".status.conditions[?(@.type=='Available')].reason"
        - name: Ready
          type: string
          jsonPath: ".status.conditions[?(@.type=='Ready')].status"
        - name: Reason
          type: string
          jsonPath: ".status.conditions[?(@.type=='Ready')].reason"

---
# Copyright 2019 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: triggers.triggers.tekton.dev
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
    triggers.tekton.dev/release: "v0.14.2"
    version: "v0.14.2"
spec:
  group: triggers.tekton.dev
  scope: Namespaced
  names:
    kind: Trigger
    plural: triggers
    singular: trigger
    shortNames:
      - tri
    categories:
      - tekton
      - tekton-triggers
  versions:
    - name: v1alpha1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          # One can use x-kubernetes-preserve-unknown-fields: true
          # at the root of the schema (and inside any properties, additionalProperties)
          # to get the traditional CRD behaviour that nothing is pruned, despite
          # setting spec.preserveUnknownProperties: false.
          #
          # See https://kubernetes.io/blog/2019/06/20/crd-structural-schema/
          # See issue: https://github.com/knative/serving/issues/912
          x-kubernetes-preserve-unknown-fields: true
      # Opt into the status subresource so metadata.generation
      # starts to increment
      subresources:
        status: {
    
    }

---
# Copyright 2019 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: triggerbindings.triggers.tekton.dev
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
    triggers.tekton.dev/release: "v0.14.2"
    version: "v0.14.2"
spec:
  group: triggers.tekton.dev
  scope: Namespaced
  names:
    kind: TriggerBinding
    plural: triggerbindings
    singular: triggerbinding
    shortNames:
      - tb
    categories:
      - tekton
      - tekton-triggers
  versions:
    - name: v1alpha1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          # One can use x-kubernetes-preserve-unknown-fields: true
          # at the root of the schema (and inside any properties, additionalProperties)
          # to get the traditional CRD behaviour that nothing is pruned, despite
          # setting spec.preserveUnknownProperties: false.
          #
          # See https://kubernetes.io/blog/2019/06/20/crd-structural-schema/
          # See issue: https://github.com/knative/serving/issues/912
          x-kubernetes-preserve-unknown-fields: true
      # Opt into the status subresource so metadata.generation
      # starts to increment
      subresources:
        status: {
    
    }

---
# Copyright 2019 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: apiextensions.k8s.io/v1
kind: CustomResourceDefinition
metadata:
  name: triggertemplates.triggers.tekton.dev
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
    triggers.tekton.dev/release: "v0.14.2"
    version: "v0.14.2"
spec:
  group: triggers.tekton.dev
  scope: Namespaced
  names:
    kind: TriggerTemplate
    plural: triggertemplates
    singular: triggertemplate
    shortNames:
      - tt
    categories:
      - tekton
      - tekton-triggers
  versions:
    - name: v1alpha1
      served: true
      storage: true
      schema:
        openAPIV3Schema:
          type: object
          # One can use x-kubernetes-preserve-unknown-fields: true
          # at the root of the schema (and inside any properties, additionalProperties)
          # to get the traditional CRD behaviour that nothing is pruned, despite
          # setting spec.preserveUnknownProperties: false.
          #
          # See https://kubernetes.io/blog/2019/06/20/crd-structural-schema/
          # See issue: https://github.com/knative/serving/issues/912
          x-kubernetes-preserve-unknown-fields: true
      # Opt into the status subresource so metadata.generation
      # starts to increment
      subresources:
        status: {
    
    }

---
# Copyright 2020 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: v1
kind: Secret
metadata:
  name: triggers-webhook-certs
  namespace: tekton-pipelines
  labels:
    app.kubernetes.io/component: webhook
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
    triggers.tekton.dev/release: "v0.14.2"
# The data is populated at install time.
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
  name: validation.webhook.triggers.tekton.dev
  labels:
    app.kubernetes.io/component: webhook
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
    triggers.tekton.dev/release: "v0.14.2"
webhooks:
  - admissionReviewVersions:
      - v1beta1
      - v1
    clientConfig:
      service:
        name: tekton-triggers-webhook
        namespace: tekton-pipelines
    failurePolicy: Fail
    sideEffects: None
    name: validation.webhook.triggers.tekton.dev
---
apiVersion: admissionregistration.k8s.io/v1
kind: MutatingWebhookConfiguration
metadata:
  name: webhook.triggers.tekton.dev
  labels:
    app.kubernetes.io/component: webhook
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
    triggers.tekton.dev/release: "v0.14.2"
webhooks:
  - admissionReviewVersions:
      - v1beta1
      - v1
    clientConfig:
      service:
        name: tekton-triggers-webhook
        namespace: tekton-pipelines
    failurePolicy: Fail
    sideEffects: None
    name: webhook.triggers.tekton.dev
---
apiVersion: admissionregistration.k8s.io/v1
kind: ValidatingWebhookConfiguration
metadata:
  name: config.webhook.triggers.tekton.dev
  labels:
    app.kubernetes.io/component: webhook
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
    triggers.tekton.dev/release: "v0.14.2"
webhooks:
  - admissionReviewVersions:
      - v1beta1
      - v1
    clientConfig:
      service:
        name: tekton-triggers-webhook
        namespace: tekton-pipelines
    failurePolicy: Fail
    sideEffects: None
    name: config.webhook.triggers.tekton.dev
    namespaceSelector:
      matchExpressions:
        - key: triggers.tekton.dev/release
          operator: Exists

---
# Copyright 2019 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: tekton-triggers-aggregate-edit
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
    rbac.authorization.k8s.io/aggregate-to-edit: "true"
    rbac.authorization.k8s.io/aggregate-to-admin: "true"
rules:
  - apiGroups:
      - triggers.tekton.dev
    resources:
      - clustertriggerbindings
      - clusterinterceptors
      - eventlisteners
      - triggers
      - triggerbindings
      - triggertemplates
    verbs:
      - create
      - delete
      - deletecollection
      - get
      - list
      - patch
      - update
      - watch

---
# Copyright 2019 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
  name: tekton-triggers-aggregate-view
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
    rbac.authorization.k8s.io/aggregate-to-view: "true"
rules:
  - apiGroups:
      - triggers.tekton.dev
    resources:
      - clustertriggerbindings
      - clusterinterceptors
      - eventlisteners
      - triggers
      - triggerbindings
      - triggertemplates
    verbs:
      - get
      - list
      - watch

---
# Copyright 2019 Tekton Authors LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: v1
kind: ConfigMap
metadata:
  name: config-logging-triggers
  namespace: tekton-pipelines
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
data:
  # Common configuration for all knative codebase
  zap-logger-config: |
    {
    
    
      "level": "info",
      "development": false,
      "sampling": {
    
    
        "initial": 100,
        "thereafter": 100
      },
      "outputPaths": ["stdout"],
      "errorOutputPaths": ["stderr"],
      "encoding": "json",
      "encoderConfig": {
    
    
        "timeKey": "ts",
        "levelKey": "level",
        "nameKey": "logger",
        "callerKey": "caller",
        "messageKey": "msg",
        "stacktraceKey": "stacktrace",
        "lineEnding": "",
        "levelEncoder": "",
        "timeEncoder": "iso8601",
        "durationEncoder": "",
        "callerEncoder": ""
      }
    }
  # Log level overrides
  loglevel.controller: "info"
  loglevel.webhook: "info"
  loglevel.eventlistener: "info"

---
# Copyright 2019 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: v1
kind: ConfigMap
metadata:
  name: config-observability-triggers
  namespace: tekton-pipelines
  labels:
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers
data:
  _example: |
    ################################
    #                              #
    #    EXAMPLE CONFIGURATION     #
    #                              #
    ################################

    # This block is not actually functional configuration,
    # but serves to illustrate the available configuration
    # options and document them in a way that is accessible
    # to users that `kubectl edit` this config map.
    #
    # These sample configuration options may be copied out of
    # this example block and unindented to be in the data block
    # to actually change the configuration.

    # metrics.backend-destination field specifies the system metrics destination.
    # It supports either prometheus (the default) or stackdriver.
    # Note: Using stackdriver will incur additional charges
    metrics.backend-destination: prometheus

    # metrics.stackdriver-project-id field specifies the stackdriver project ID. This
    # field is optional. When running on GCE, application default credentials will be
    # used if this field is not provided.
    metrics.stackdriver-project-id: "<your stackdriver project id>"

    # metrics.allow-stackdriver-custom-metrics indicates whether it is allowed to send metrics to
    # Stackdriver using "global" resource type and custom metric type if the
    # metrics are not supported by "knative_revision" resource type. Setting this
    # flag to "true" could cause extra Stackdriver charge.
    # If metrics.backend-destination is not Stackdriver, this is ignored.
    metrics.allow-stackdriver-custom-metrics: "false"

---
# Copyright 2019 Tekton Authors LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: v1
kind: Service
metadata:
  labels:
    app.kubernetes.io/name: controller
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: default
    app.kubernetes.io/version: "v0.14.2"
    app.kubernetes.io/part-of: tekton-triggers
    triggers.tekton.dev/release: "v0.14.2"
    app: tekton-triggers-controller
    version: "v0.14.2"
  name: tekton-triggers-controller
  namespace: tekton-pipelines
spec:
  ports:
    - name: http-metrics
      port: 9000
      protocol: TCP
      targetPort: 9000
  selector:
    app.kubernetes.io/name: controller
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers

---
# Copyright 2019 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: tekton-triggers-controller
  namespace: tekton-pipelines
  labels:
    app.kubernetes.io/name: controller
    app.kubernetes.io/component: controller
    app.kubernetes.io/instance: default
    app.kubernetes.io/version: "v0.14.2"
    app.kubernetes.io/part-of: tekton-triggers
    # tekton.dev/release value replaced with inputs.params.versionTag in triggers/tekton/publish.yaml
    triggers.tekton.dev/release: "v0.14.2"
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: controller
      app.kubernetes.io/component: controller
      app.kubernetes.io/instance: default
      app.kubernetes.io/part-of: tekton-triggers
  template:
    metadata:
      annotations:
        cluster-autoscaler.kubernetes.io/safe-to-evict: "false"
      labels:
        app.kubernetes.io/name: controller
        app.kubernetes.io/component: controller
        app.kubernetes.io/instance: default
        app.kubernetes.io/version: "v0.14.2"
        app.kubernetes.io/part-of: tekton-triggers
        app: tekton-triggers-controller
        triggers.tekton.dev/release: "v0.14.2"
        # version value replaced with inputs.params.versionTag in triggers/tekton/publish.yaml
        version: "v0.14.2"
    spec:
      serviceAccountName: tekton-triggers-controller
      containers:
        - name: tekton-triggers-controller
         # image: "gcr.io/tekton-releases/github.com/tektoncd/triggers/cmd/controller:v0.14.2@sha256:58baa0aa0eaca368b8090bcb6e88024847d14df2952cdfe7f22be6132a7732c9"
          image: tektondev/triggers-controller:v0.14.2
          args: ["-logtostderr", "-stderrthreshold", "INFO", "-el-image", "gcr.io/tekton-releases/github.com/tektoncd/triggers/cmd/eventlistenersink:v0.14.2@sha256:b653776331a65a239df4bf833fc91bd0fe4dc28008ff4475f4cdd19415d93e55", "-el-port", "8080", "-el-readtimeout", "5", "-el-writetimeout", "40", "-el-idletimeout", "120", "-el-timeouthandler", "30", "-period-seconds", "10", "-failure-threshold", "1"]
          env:
            - name: SYSTEM_NAMESPACE
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
            - name: CONFIG_LOGGING_NAME
              value: config-logging-triggers
            - name: CONFIG_OBSERVABILITY_NAME
              value: config-observability-triggers
            - name: METRICS_DOMAIN
              value: tekton.dev/triggers
            - name: METRICS_PROMETHEUS_PORT
              value: "9000"
          securityContext:
            allowPrivilegeEscalation: false
            # User 65532 is the distroless nonroot user ID
            runAsUser: 65532

---
# Copyright 2019 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: v1
kind: Service
metadata:
  name: tekton-triggers-webhook
  namespace: tekton-pipelines
  labels:
    app.kubernetes.io/name: webhook
    app.kubernetes.io/component: webhook
    app.kubernetes.io/instance: default
    app.kubernetes.io/version: "v0.14.2"
    app.kubernetes.io/part-of: tekton-triggers
    app: tekton-triggers-webhook
    version: "v0.14.2"
    triggers.tekton.dev/release: "v0.14.2"
spec:
  ports:
    - name: https-webhook
      port: 443
      targetPort: 8443
  selector:
    app.kubernetes.io/name: webhook
    app.kubernetes.io/component: webhook
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers

---
# Copyright 2019 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: tekton-triggers-webhook
  namespace: tekton-pipelines
  labels:
    app.kubernetes.io/name: webhook
    app.kubernetes.io/component: webhook
    app.kubernetes.io/instance: default
    app.kubernetes.io/version: "v0.14.2"
    app.kubernetes.io/part-of: tekton-triggers
    # tekton.dev/release value replaced with inputs.params.versionTag in triggers/tekton/publish.yaml
    triggers.tekton.dev/release: "v0.14.2"
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: webhook
      app.kubernetes.io/component: webhook
      app.kubernetes.io/instance: default
      app.kubernetes.io/part-of: tekton-triggers
  template:
    metadata:
      annotations:
        cluster-autoscaler.kubernetes.io/safe-to-evict: "false"
      labels:
        app.kubernetes.io/name: webhook
        app.kubernetes.io/component: webhook
        app.kubernetes.io/instance: default
        app.kubernetes.io/version: "v0.14.2"
        app.kubernetes.io/part-of: tekton-triggers
        app: tekton-triggers-webhook
        triggers.tekton.dev/release: "v0.14.2"
        # version value replaced with inputs.params.versionTag in triggers/tekton/publish.yaml
        version: "v0.14.2"
    spec:
      serviceAccountName: tekton-triggers-webhook
      containers:
        - name: webhook
          # This is the Go import path for the binary that is containerized
          # and substituted here.
          #image: "gcr.io/tekton-releases/github.com/tektoncd/triggers/cmd/webhook:v0.14.2@sha256:2f1e8b38fef204d5f6c0ecafbd8be930f7c86666ee512d89908093336dd59c2c"
          image: tektondev/trigger-webhook:v0.14.2 
          env:
            - name: SYSTEM_NAMESPACE
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
            - name: CONFIG_LOGGING_NAME
              value: config-logging-triggers
            - name: WEBHOOK_SERVICE_NAME
              value: tekton-triggers-webhook
            - name: WEBHOOK_SECRET_NAME
              value: triggers-webhook-certs
            - name: METRICS_DOMAIN
              value: tekton.dev/triggers
          ports:
            - name: metrics
              containerPort: 9000
            - name: profiling
              containerPort: 8008
            - name: https-webhook
              containerPort: 8443
          securityContext:
            allowPrivilegeEscalation: false
            # User 65532 is the distroless nonroot user ID
            runAsUser: 65532

---

interceptor:
# Copyright 2020 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: apps/v1
kind: Deployment
metadata:
  name: tekton-triggers-core-interceptors
  namespace: tekton-pipelines
  labels:
    app.kubernetes.io/name: core-interceptors
    app.kubernetes.io/component: interceptors
    app.kubernetes.io/instance: default
    app.kubernetes.io/version: "v0.14.2"
    app.kubernetes.io/part-of: tekton-triggers
    # tekton.dev/release value replaced with inputs.params.versionTag in triggers/tekton/publish.yaml
    triggers.tekton.dev/release: "v0.14.2"
spec:
  replicas: 1
  selector:
    matchLabels:
      app.kubernetes.io/name: core-interceptors
      app.kubernetes.io/component: interceptors
      app.kubernetes.io/instance: default
      app.kubernetes.io/part-of: tekton-triggers
  template:
    metadata:
      labels:
        app.kubernetes.io/name: core-interceptors
        app.kubernetes.io/component: interceptors
        app.kubernetes.io/instance: default
        app.kubernetes.io/version: "v0.14.2"
        app.kubernetes.io/part-of: tekton-triggers
        app: tekton-triggers-core-interceptors
        triggers.tekton.dev/release: "v0.14.2"
        # version value replaced with inputs.params.versionTag in triggers/tekton/publish.yaml
        version: "v0.14.2"
    spec:
      serviceAccountName: tekton-triggers-core-interceptors
      containers:
        - name: tekton-triggers-core-interceptors
          #image: "gcr.io/tekton-releases/github.com/tektoncd/triggers/cmd/interceptors:v0.14.2@sha256:d62beb1410c8200837176799f6424da6eafebc577af067743399a31360cca63e"
          image: tektondev/trigger-interceptors:v0.14.2
          args: ["-logtostderr", "-stderrthreshold", "INFO"]
          env:
            - name: SYSTEM_NAMESPACE
              valueFrom:
                fieldRef:
                  fieldPath: metadata.namespace
            - name: CONFIG_LOGGING_NAME
              value: config-logging-triggers
            - name: CONFIG_OBSERVABILITY_NAME
              value: config-observability-triggers
            - name: METRICS_DOMAIN
              value: tekton.dev/triggers
          securityContext:
            allowPrivilegeEscalation: false
            # User 65532 is the distroless nonroot user ID
            runAsUser: 65532
            runAsGroup: 65532
            capabilities:
              drop:
                - all
---
apiVersion: v1
kind: Service
metadata:
  labels:
    app.kubernetes.io/name: tekton-triggers-core-interceptors
    app.kubernetes.io/component: interceptors
    app.kubernetes.io/instance: default
    app.kubernetes.io/version: "v0.14.2"
    app.kubernetes.io/part-of: tekton-triggers
    triggers.tekton.dev/release: "v0.14.2"
    app: tekton-triggers-core-interceptors
    version: "v0.14.2"
  name: tekton-triggers-core-interceptors
  namespace: tekton-pipelines
spec:
  ports:
    - name: "http"
      port: 80
      targetPort: 8082
  selector:
    app.kubernetes.io/name: core-interceptors
    app.kubernetes.io/component: interceptors
    app.kubernetes.io/instance: default
    app.kubernetes.io/part-of: tekton-triggers

---
# Copyright 2021 The Tekton Authors
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

apiVersion: triggers.tekton.dev/v1alpha1
kind: ClusterInterceptor
metadata:
  name: cel
spec:
  clientConfig:
    service:
      name: tekton-triggers-core-interceptors
      namespace: tekton-pipelines
      path: "cel"
---
apiVersion: triggers.tekton.dev/v1alpha1
kind: ClusterInterceptor
metadata:
  name: bitbucket
spec:
  clientConfig:
    service:
      name: tekton-triggers-core-interceptors
      namespace: tekton-pipelines
      path: "bitbucket"
---
apiVersion: triggers.tekton.dev/v1alpha1
kind: ClusterInterceptor
metadata:
  name: github
spec:
  clientConfig:
    service:
      name: tekton-triggers-core-interceptors
      namespace: tekton-pipelines
      path: "github"
---
apiVersion: triggers.tekton.dev/v1alpha1
kind: ClusterInterceptor
metadata:
  name: gitlab
spec:
  clientConfig:
    service:
      name: tekton-triggers-core-interceptors
      namespace: tekton-pipelines
      path: "gitlab"

---
[root@master1 ~]# kubectl get pod -n tekton-pipelines
NAME                                                 READY   STATUS    RESTARTS   AGE
tekton-dashboard-85fbcbdcdd-lmh5h                    1/1     Running   2          35h
tekton-pipelines-controller-6fd67c849f-vmlvd         1/1     Running   0          35h
tekton-pipelines-webhook-7dc48bc5f7-k4cv5            1/1     Running   0          35h
tekton-triggers-controller-9d9ff98b8-7lwkf           1/1     Running   0          19m
tekton-triggers-core-interceptors-747dc7b7c8-plbnm   1/1     Running   0          13m
tekton-triggers-webhook-d5bbdcdf6-4bgtt              1/1     Running   0          19m

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

现在我们来将前面的 Jenkins Pipeline 流水线转换成使用 Tekton 来构建,代码我们已经推送到了私有仓库 GitLab,地址为:http://git.k8s.local/course/devops-demo.git

首先我们需要完成触发器的配置,当我们提交源代码到 GitLab 的时候,需要触发 Tekton 的任务运行,所以首先需要完成这个触发器。这里就可以通过 EventListener 这个资源对象来完成,创建一个名为 gitlab-listener 的 EventListener 资源对象

# gitlab-push-listener.yaml
apiVersion: triggers.tekton.dev/v1alpha1
kind: EventListener
metadata:
  name: gitlab-listener  # 该事件监听器会创建一个名为el-gitlab-listener的Service对象
spec:
  serviceAccountName: tekton-triggers-gitlab-sa
  triggers:
  - name: gitlab-push-events-trigger
    interceptors:
    - ref:
        name: gitlab
      params:
      - name: secretRef  # 引用 gitlab-secret 的 Secret 对象中的 secretToken 的值
        value:
          secretName: gitlab-secret
          secretKey: secretToken
      - name: eventTypes
        value:
          - Push Hook # 只接收 GitLab Push 事件
    bindings:
    - ref: devops-demo-binding
    template:
      ref: devops-demo-template

由于 EventListener 创建完成后会生成一个 Listener 的服务,用来对外暴露用于接收事件响应,比如上面我们创建的对象名为 gitlab-listener,创建完成后会生成一个名为 el-gitlab-listener 的 Service 对象,由于我们 GitLab 本身就在集群内部,所以我们用 Service 的 DNS 形式来访问 EventListener 即可,如果你想暴露到集群外部则可以使用 NodePort 或者 Ingress 的形式。

另外需要注意的是在上面的 EventListener 对象中我们添加了 interceptors 属性,其中有一个内置的 gitlab 拦截器,GitLab 拦截器包含验证和过滤来自 GitLab 的请求逻辑, 比如我们可以配置 WebHook 的 Secret Token,可以通过 Secret 对象引入

interceptors:
- ref:
    name: gitlab
  params:
  - name: secretRef  # 引用 gitlab-secret 的 Secret 对象中的 secretToken 的值
    value:
      secretName: gitlab-secret
      secretKey: secretToken
  - name: eventTypes
    value:
      - Push Hook # 只接收 GitLab Push 事件

对应的 Secret 资源对象如下所示,一个用于 WebHook 的 Secret Token,另外一个是用于 GitLab 登录认证使用的

# gitlab-secret.yaml
apiVersion: v1
kind: Secret
metadata:
  name: gitlab-secret
type: Opaque
stringData:
  secretToken: '1234567'
---
apiVersion: v1
kind: Secret
metadata:
  name: gitlab-auth
  annotations:
    tekton.dev/git-0: http://git.k8s.local
type: kubernetes.io/basic-auth
stringData:
  username: root
  password: admin321

由于 EventListener 对象需要访问其他资源对象,所以需要声明 RBAC,如下所示

# event-listener-rbac.yaml
apiVersion: v1
kind: ServiceAccount
metadata:
  name: tekton-triggers-gitlab-sa
secrets:
  - name: gitlab-secret
  - name: gitlab-auth
  - name: harbor-auth
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
  name: tekton-triggers-gitlab-minimal
rules:
  # EventListeners need to be able to fetch all namespaced resources
  - apiGroups: ['triggers.tekton.dev']
    resources:
      ['eventlisteners', 'triggerbindings', 'triggertemplates', 'triggers']
    verbs: ['get', 'list', 'watch']
  - apiGroups: ['']
    # configmaps is needed for updating logging config
    resources: ['configmaps']
    verbs: ['get', 'list', 'watch']
  # Permissions to create resources in associated TriggerTemplates
  - apiGroups: ['tekton.dev']
    resources: ['pipelineruns', 'pipelineresources', 'taskruns']
    verbs: ['create']
  - apiGroups: ['']
    resources: ['serviceaccounts']
    verbs: ['impersonate']
  - apiGroups: ['policy']
    resources: ['podsecuritypolicies']
    resourceNames: ['tekton-triggers']
    verbs: ['use']
---
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-clusterrole
rules:
  # EventListeners need to be able to fetch any clustertriggerbindings
  - apiGroups: ['triggers.tekton.dev']
    resources: ['clustertriggerbindings', 'clusterinterceptors']
    verbs: ['get', 'list', 'watch']
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: tekton-triggers-gitlab-clusterbinding
subjects:
  - kind: ServiceAccount
    name: tekton-triggers-gitlab-sa
    namespace: default
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: tekton-triggers-gitlab-clusterrole

然后接下来就是最重要的 TriggerBinding 和 TriggerTemplate 对象了,我们在上面的 EventListener 对象中将两个对象组合在一起

bindings:
  - ref: gitlab-push-binding # TriggerBinding 对象
template:
  ref: gitlab-echo-template # TriggerTemplate 对象

这样就可以将 TriggerBinding 中的参数传递到 TriggerTemplate 对象中进行模板化。比如这里我们定义一个如下所示的 TriggerBinding 对象

apiVersion: triggers.tekton.dev/v1alpha1
kind: TriggerBinding
metadata:
  name: devops-demo-binding
spec:
  params:
    - name: gitrevision
      value: $(body.checkout_sha)
    - name: gitrepositoryurl
      value: $(body.repository.git_http_url)

这里需要注意的是参数的值我们是通过读取 GitLab WebHook 发送过来的数据值,通过 $() 包裹的 JSONPath 表达式来提取的,关于表达式的更多用法可以查看官方文档https://github.com/tektoncd/triggers/blob/main/docs/triggerbindings.md#event-variable-interpolation说明,至于能够提取哪些参数值,则可以查看 WebHook 的说明,比如这里我们是 GitLab Webhook 的 Push Hook,对应的请求体数据如下所示

{
    
    
  "object_kind": "push",
  "before": "95790bf891e76fee5e1747ab589903a6a1f80f22",
  "after": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7",
  "ref": "refs/heads/master",
  "checkout_sha": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7",
  "user_id": 4,
  "user_name": "John Smith",
  "user_username": "jsmith",
  "user_email": "[email protected]",
  "user_avatar": "https://s.gravatar.com/avatar/d4c74594d841139328695756648b6bd6?s=8://s.gravatar.com/avatar/d4c74594d841139328695756648b6bd6?s=80",
  "project_id": 15,
  "project":{
    
    
    "id": 15,
    "name":"Diaspora",
    "description":"",
    "web_url":"http://example.com/mike/diaspora",
    "avatar_url":null,
    "git_ssh_url":"[email protected]:mike/diaspora.git",
    "git_http_url":"http://example.com/mike/diaspora.git",
    "namespace":"Mike",
    "visibility_level":0,
    "path_with_namespace":"mike/diaspora",
    "default_branch":"master",
    "homepage":"http://example.com/mike/diaspora",
    "url":"[email protected]:mike/diaspora.git",
    "ssh_url":"[email protected]:mike/diaspora.git",
    "http_url":"http://example.com/mike/diaspora.git"
  },
  "repository":{
    
    
    "name": "Diaspora",
    "url": "[email protected]:mike/diaspora.git",
    "description": "",
    "homepage": "http://example.com/mike/diaspora",
    "git_http_url":"http://example.com/mike/diaspora.git",
    "git_ssh_url":"[email protected]:mike/diaspora.git",
    "visibility_level":0
  },
  "commits": [
    {
    
    
      "id": "b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327",
      "message": "Update Catalan translation to e38cb41.\n\nSee https://gitlab.com/gitlab-org/gitlab for more information",
      "title": "Update Catalan translation to e38cb41.",
      "timestamp": "2011-12-12T14:27:31+02:00",
      "url": "http://example.com/mike/diaspora/commit/b6568db1bc1dcd7f8b4d5a946b0b91f9dacd7327",
      "author": {
    
    
        "name": "Jordi Mallach",
        "email": "[email protected]"
      },
      "added": ["CHANGELOG"],
      "modified": ["app/controller/application.rb"],
      "removed": []
    },
    {
    
    
      "id": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7",
      "message": "fixed readme",
      "title": "fixed readme",
      "timestamp": "2012-01-03T23:36:29+02:00",
      "url": "http://example.com/mike/diaspora/commit/da1560886d4f094c3e6c9ef40349f7d38b5d27d7",
      "author": {
    
    
        "name": "GitLab dev user",
        "email": "gitlabdev@dv6700.(none)"
      },
      "added": ["CHANGELOG"],
      "modified": ["app/controller/application.rb"],
      "removed": []
    }
  ],
  "total_commits_count": 4
}

请求体中的任何属性都可以提取出来,作为 TriggerBinding 的参数,如果是其他的 Hook 事件,对应的请求体结构可以查看 GitLab 文档说明

这样我们就可以在 TriggerTemplate 对象中通过参数来读取上面 TriggerBinding 中定义的参数值了,定义一个如下所示的 TriggerTemplate 对象,声明一个 TaskRun 的模板,定义的 Task 任务也非常简单,只需要在容器中打印出代码的目录结构即可

apiVersion: triggers.tekton.dev/v1alpha1
kind: TriggerTemplate
metadata:
  name: devops-demo-template
spec:
  params: # 定义参数,和 TriggerBinding 中的保持一致
    - name: gitrevision
    - name: gitrepositoryurl
  resourcetemplates: # 定义资源模板
    - apiVersion: tekton.dev/v1beta1
      kind: TaskRun # 定义 TaskRun 模板
      metadata:
        generateName: gitlab-run- # TaskRun 名称前缀
      spec:
        serviceAccountName: tekton-triggers-gitlab-sa
        taskSpec: # Task 任务声明
          resources:
            inputs: # 定义一个名为 source 的 git 输入资源
              - name: source
                type: git
          steps:
            - name: show-path
              image: ubuntu # 定义一个执行步骤,列出代码目录结构
              script: |
                #! /bin/bash
                ls -la $(resources.inputs.source.path)
        resources: # 声明具体的输入资源参数
          inputs:
            - name: source # 和 Task 中的资源名保持一直
              resourceSpec: # 资源声明
                type: git
                params:
                  - name: revision
                    value: $(tt.params.gitrevision) # 读取参数值
                  - name: url
                    value: $(tt.params.gitrepositoryurl)

需要注意在最后的 pipelineresource 中引用参数值的时候使用了一个 tt 的前缀。定义完过后,直接创建上面的资源对象,创建完成后会自动生成 EventListener 的 Pod 和 Service 对象

[root@master1 ~]# vim gitlab-push-listener.yaml
[root@master1 ~]# vim gitlab-secret.yaml
[root@master1 ~]# vim event-listener-rbac.yaml
[root@master1 ~]# vim trigger-binding.yaml
[root@master1 ~]# vim trigger-template.yaml
[root@master1 ~]# kubectl apply -f gitlab-push-listener.yaml -f gitlab-secret.yaml -f event-listener-rbac.yaml -f trigger-binding.yaml -f trigger-template.yaml

[root@master1 ~]# kubectl get pod,svc,eventlistener
NAME                                                  READY   STATUS      RESTARTS   AGE
pod/build-and-push-pod-v88fw                          0/4     Completed   0          29h
pod/el-gitlab-listener-77b76bb4b8-45pbj               1/1     Running     0          12m
pod/test-pipelinerun-build-and-push-wdkhm-pod-kcb8d   0/4     Completed   0          6h30m
pod/test-pipelinerun-test-7lvcn-pod-vvpd4             0/2     Completed   0          6h33m
pod/testrun-pod-p4zpp                                 0/2     Completed   0          30h

NAME                         TYPE        CLUSTER-IP     EXTERNAL-IP   PORT(S)    AGE
service/el-gitlab-listener   ClusterIP   10.105.38.21   <none>        8080/TCP   12m
service/kubernetes           ClusterIP   10.96.0.1      <none>        443/TCP    7d21h

NAME                                                ADDRESS                                                    AVAILABLE   REASON                     READY   REASON
eventlistener.triggers.tekton.dev/gitlab-listener   http://el-gitlab-listener.default.svc.cluster.local:8080   True        MinimumReplicasAvailable   True

如果eventlistener的pod的镜像不行就换一个
在这里插入图片描述

接下来我们就可以到 GitLab 的项目中配置 WebHook,注意需要配置 Secret Token,我们在上面的 Secret 对象中声明过
创建完成后,我们可以测试下该 WebHook 的 Push events 事件,直接点击测试即可(如果使用自定义的域名则需要在 coredns 中添加映射),正常会返回 Hook executed successfully: HTTP 202 的提示信息,这个时候在 Kubernetes 集群中就会出现如下所示的任务 Pod

$ kubectl get pods -l triggers.tekton.dev/eventlistener=gitlab-listener
NAME                         READY   STATUS      RESTARTS   AGE
gitlab-run-lnqzv-pod-lp8lw   0/2     Completed   0          3m18s
$ kubectl get taskrun -l triggers.tekton.dev/eventlistener=gitlab-listener
NAME               SUCCEEDED   REASON      STARTTIME   COMPLETIONTIME
gitlab-run-lnqzv   True        Succeeded   3m11s       2m48s
$ tkn taskrun logs gitlab-run-lnqzv
[git-source-source-hfrw6] {
    
    "level":"info","ts":1624446684.0399015,"caller":"git/git.go:169","msg":"Successfully cloned http://git.k8s.local/course/devops-demo.git @ 581b1986b6c038ca98a362e6a0b8e9acb55893e8 (grafted, HEAD) in path /workspace/source"}
[git-source-source-hfrw6] {
    
    "level":"info","ts":1624446684.0660462,"caller":"git/git.go:207","msg":"Successfully initialized and updated submodules in path /workspace/source"}

[show-path] total 36
[show-path] drwxr-xr-x 4 root root  163 Jun 23 11:11 .
[show-path] drwxrwxrwx 3 root root   20 Jun 23 11:11 ..
[show-path] -rw-r--r-- 1 root root 1804 Jun 23 11:11 .drone.yml
[show-path] drwxr-xr-x 8 root root  177 Jun 23 11:11 .git
[show-path] -rw-r--r-- 1 root root  192 Jun 23 11:11 .gitignore
[show-path] -rw-r--r-- 1 root root  375 Jun 23 11:11 Dockerfile
[show-path] -rw-r--r-- 1 root root 5101 Jun 23 11:11 Jenkinsfile
[show-path] -rw-r--r-- 1 root root  174 Jun 23 11:11 README.md
[show-path] -rw-r--r-- 1 root root   97 Jun 23 11:11 go.mod
[show-path] -rw-r--r-- 1 root root 3370 Jun 23 11:11 go.sum
[show-path] drwxr-xr-x 3 root root  101 Jun 23 11:11 helm
[show-path] -rw-r--r-- 1 root root  471 Jun 23 11:11 main.go

完成了通过 GitLab 的 Push 事件来触发 Tekton 的一个任务
在这里插入图片描述
再来实现将我们的应用通过 Tekton 来自动部署到 Kubernetes 集群中

猜你喜欢

转载自blog.csdn.net/weixin_45843419/article/details/125134211