创建项目时自动配置 JFrog 资源
jfrog-connector-automatic-creation Task 会协调项目在 JFrog Artifactory 和 Kubernetes 中所需的全部资源,但必须由某个机制来运行它。为每个新项目手动运行它,会使接入延迟回到原来的水平。
本指南将该 Task 连接到命名空间事件之后,这样在集群上创建项目命名空间时,就会配置项目的 Artifactory 仓库和范围限定的身份,并在项目命名空间中配置 Connector、认证 Secret 和镜像拉取 Secret,全程无需 operator 操作。
事件源是随 connectors-autocreate 提供的 ns-event-source 适配器。该适配器与工具无关:它监视命名空间并转发 CloudEvents。本指南所述的 Pipeline 会使用这些事件并运行 JFrog Task。
如果你已经为 Harbor、Nexus、GitLab 和 SonarQube 运行 connector-auto-create Pipeline,则已经拥有该适配器。请注意,一个适配器恰好只有一个 K_SINK,因此仅在现有 EventListener 旁添加本指南的 EventListener 并不足够:要么使用指向 el-jfrog-autocreate-el 的 K_SINK 再运行一个适配器,要么保留一个适配器,并将本指南的 TriggerBinding 和 TriggerTemplate 作为另一个触发器添加到已有的 EventListener 中。
架构
Management cluster
┌─────────────────────────────────────────────────────────────────┐
│ ns-event-source ──CloudEvent──▶ EventListener jfrog-autocreate-el│
│ (watches namespaces) │ │
│ ▼ │
│ PipelineRun │
│ jfrog-project-provision │
│ │ │
│ ▼ │
│ jfrog-connector-automatic-creation Task │
└─────────────────────────────────────────────────────────────────┘
│
▼
Artifactory: repositories, group,
user, permission target, token
Kubernetes: Connector + Secret +
image pull Secret in <project-namespace>
Pipeline 需要了解的所有信息都来自命名空间本身:其名称,以及携带其所属项目的 cpaas.io/project 标签。
先决条件
-
已安装 Tekton Pipelines 和 Tekton Triggers。
-
已安装 Connectors 系统和 JFrog Connector 组件。
-
管理命名空间中存在一个管理员 JFrog Connector(下文称为 jfrog-admin),并由 Artifactory 管理员凭证提供支持。有关确切权限以及如何创建 Connector,请参阅 Artifactory 的 jfrog-secret 凭证。
-
Artifactory 为 Pro(或更高版本)。该 Task 在 OSS 上会快速失败。
-
已在管理命名空间中安装 jfrog-connector-automatic-creation Task。
-
已安装 ns-event-source 适配器,并将其指向此集群。请参阅步骤 1 — 安装适配器。该页面会将 K_SINK 设置为 http://el-autocreate-el:8080,即 Harbor/Nexus/GitLab 流程的 EventListener;对于本指南,必须将其设置为 http://el-jfrog-autocreate-el:8080,即步骤 3创建的服务:
kubectl -n "$TARGET_NS" set env deploy/ns-event-source K_SINK=http://el-jfrog-autocreate-el:8080
如果保留为另一个值,下面的所有内容都会成功安装,但始终不会运行任何任务:适配器会记录 failed to send cloudevent … lookup el-autocreate-el … no such host,并且不会出现 PipelineRun。
导出以下命令所使用的变量:
export TARGET_NS=<management-namespace>
export JFROG_ADMIN=<jfrog-admin-connector-name>
export JFROG_URL=<artifactory-url> # e.g. https://jfrog.example.com
export REGISTRY=<your-registry>
kubectl config set-context --current --namespace="$TARGET_NS"
步骤 1 — 安装 Pipeline
该 Pipeline 的结构与随附的 connector-auto-create Pipeline 相似:一个上下文任务确定需要协调的对象并持有每个项目的锁,而 provisioning Task 则使用其结果。目标集合没有硬编码在 Task 调用中。
cat <<'EOF' | envsubst '$TARGET_NS $REGISTRY' | kubectl apply -f -
apiVersion: tekton.dev/v1
kind: Pipeline
metadata:
name: jfrog-project-provision
namespace: $TARGET_NS
spec:
params:
- name: namespace
description: Namespace whose event triggered this run. Used to find the project's other namespaces, not as the only target.
type: string
- name: project
description: Project the namespace belongs to; names the repositories, the Connector and the pull Secrets.
type: string
- name: jfrogUrl
description: Artifactory origin, without a trailing /artifactory. Must match the address of the Connector bound to the jfrog-admin workspace.
type: string
- name: repositoryPackageTypes
description: One repository per package type, named <project>-<packageType>.
type: array
default: ["docker"]
- name: repositoryMode
description: provision (create the repositories when absent) or reference (they already exist; only grant access).
type: string
default: provision
- name: permissions
description: Artifactory actions granted on every repository in the run.
type: array
default: ["read", "write", "annotate", "delete"]
- name: tokenExpiry
description: Lifetime of the minted access token.
type: string
default: "30d"
- name: bindImagePullSecretToSA
description: Append each generated pull Secret to a ServiceAccount in its namespace.
type: string
default: "true"
- name: serviceAccountName
description: ServiceAccount that receives the pull Secrets.
type: string
default: default
- name: lockDurationSeconds
description: How long this run's project lock stays valid if the run dies without releasing it.
type: string
default: "300"
- name: lockWaitSeconds
description: How long to wait for another reconciliation of the same project to finish.
type: string
default: "600"
- name: kubectlImage
description: Image used by the context task; any image carrying kubectl works.
type: string
default: ${REGISTRY}/alauda-connectors/kubectl:v1.33
- name: jfrogCliImage
description: Runtime image for the Task itself; must be the jfrog-connector-automatic-creation image or a derivative.
type: string
default: ${REGISTRY}/alauda-connectors/connectors-extensions/jfrog-connector-automatic-creation:latest
workspaces:
- name: jfrog-admin
description: Admin JFrog Connector, mounted through the Connectors CSI driver.
# A PipelineRun only surfaces the results the Pipeline itself declares.
# Without this block `kubectl get pipelinerun -o jsonpath='{.status.results}'`
# prints nothing, however many results the Task emitted.
results:
- name: jfrog-repositories
value: $(tasks.provision.results.jfrog-repositories[*])
- name: connector-ref
value: $(tasks.provision.results.connector-ref)
- name: image-pull-secret-refs
value: $(tasks.provision.results.image-pull-secret-refs[*])
- name: token-rotated
value: $(tasks.provision.results.token-rotated)
tasks:
- name: prepare-project-context
params:
- { name: namespace, value: $(params.namespace) }
- { name: project, value: $(params.project) }
- { name: jfrogUrl, value: $(params.jfrogUrl) }
- { name: repositoryPackageTypes, value: ["$(params.repositoryPackageTypes[*])"] }
- { name: repositoryMode, value: $(params.repositoryMode) }
- { name: holder, value: $(context.pipelineRun.name) }
- { name: runNamespace, value: $(context.pipelineRun.namespace) }
- { name: lockDurationSeconds, value: $(params.lockDurationSeconds) }
- { name: lockWaitSeconds, value: $(params.lockWaitSeconds) }
- { name: kubectlImage, value: $(params.kubectlImage) }
taskSpec:
params:
- { name: namespace, type: string }
- { name: project, type: string }
- { name: jfrogUrl, type: string }
- { name: repositoryPackageTypes, type: array }
- { name: repositoryMode, type: string }
- { name: holder, type: string }
- { name: runNamespace, type: string }
- { name: lockDurationSeconds, type: string }
- { name: lockWaitSeconds, type: string }
- { name: kubectlImage, type: string }
results:
- name: connectorNs
description: Namespace that receives the Connector and its auth Secret.
- name: jfrogUrl
description: Artifactory origin used by the provisioning task.
- name: imagePullSecrets
type: array
description: One <namespace>/<secret> entry per namespace of this project.
- name: jfrogRepositories
description: The jfrogRepositories YAML the Task receives.
stepTemplate:
image: $(params.kubectlImage)
# Required on a namespace that enforces the `restricted` Pod Security
# Standard, which rejects the Pod otherwise — the podTemplate in the
# TriggerTemplate can only set the pod-level half of this.
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop: ["ALL"]
runAsNonRoot: true
runAsUser: 65532
seccompProfile:
type: RuntimeDefault
env:
# Parameters reach the scripts through env, never interpolated into
# them: a value containing a quote would otherwise break out of the shell.
- { name: NAMESPACE, value: $(params.namespace) }
- { name: PROJECT, value: $(params.project) }
- { name: JFROG_URL, value: $(params.jfrogUrl) }
- { name: REPOSITORY_MODE, value: $(params.repositoryMode) }
- { name: HOLDER, value: $(params.holder) }
- { name: RUN_NS, value: $(params.runNamespace) }
- { name: LOCK_DURATION_SECONDS, value: $(params.lockDurationSeconds) }
- { name: LOCK_WAIT_SECONDS, value: $(params.lockWaitSeconds) }
steps:
# 1. Which namespace owns the Connector. On ACP a project has an inner
# namespace; elsewhere fall back to the triggering namespace. Resolved
# first because the lock lives here, so every namespace of the project
# contends for the same Lease.
- name: resolve-connector-namespace
script: |
#!/usr/bin/env sh
set -eu
ns="$(kubectl get namespace "${NAMESPACE}" \
-o jsonpath='{.metadata.annotations.cpaas\.io/project-inner-namespace}' 2>/dev/null || true)"
[ -n "${ns}" ] || ns="${NAMESPACE}"
printf '%s' "${ns}" > "$(results.connectorNs.path)"
echo "connector namespace: ${ns}"
# 2. Serialize reconciliations of the same project. Two namespaces added at
# once would otherwise race on the same Artifactory group generation and
# permission target.
- name: acquire-project-lock
script: |
#!/usr/bin/env sh
set -eu
# The Lease is keyed by PROJECT and lives in the namespace this
# Pipeline runs in — not in the namespace resolved above. Putting it
# there would give two namespaces of one project two different Leases,
# so they would never contend, which is the whole point of the lock.
lock_ns="${RUN_NS}"
lock="jfrog-autocreate-${PROJECT}"
waited=0
while :; do
if cat <<LEASE | kubectl create -f - >/dev/null 2>/tmp/lock.err
apiVersion: coordination.k8s.io/v1
kind: Lease
metadata:
name: ${lock}
namespace: ${lock_ns}
spec:
holderIdentity: ${HOLDER}
leaseDurationSeconds: ${LOCK_DURATION_SECONDS}
acquireTime: "$(date -u +%Y-%m-%dT%H:%M:%S.000000Z)"
renewTime: "$(date -u +%Y-%m-%dT%H:%M:%S.000000Z)"
LEASE
then
echo "acquired ${lock_ns}/${lock} after ${waited}s"; exit 0
fi
grep -q AlreadyExists /tmp/lock.err || { cat /tmp/lock.err >&2; exit 1; }
state="$(kubectl get lease "${lock}" -n "${lock_ns}" \
-o jsonpath='{.spec.holderIdentity}|{.spec.renewTime}|{.spec.leaseDurationSeconds}|{.metadata.resourceVersion}')"
current="${state%%|*}"; rest="${state#*|}"
renew="${rest%%|*}"; rest="${rest#*|}"
duration="${rest%%|*}"; version="${rest##*|}"
[ "${current}" = "${HOLDER}" ] && { echo "already held by this run"; exit 0; }
# Reclaim only when the holder cannot still be working: either its
# PipelineRun reached a terminal condition, or it is gone from the
# cluster AND the Lease has outlived its duration. Reclaiming on
# elapsed time alone would let a slow-but-alive run be robbed.
reclaim=false
holder_state="$(kubectl get pipelinerun "${current}" -n "${lock_ns}" \
-o jsonpath='{.status.conditions[-1].status}' 2>/dev/null || true)"
if [ "${holder_state}" = "True" ] || [ "${holder_state}" = "False" ]; then
reclaim=true
elif ! kubectl get pipelinerun "${current}" -n "${lock_ns}" >/dev/null 2>&1; then
# busybox `date` needs the input format spelled out, and the Lease
# carries fractional seconds it cannot parse.
normalized="$(printf '%s' "${renew}" | sed 's/\.[0-9][0-9]*Z$/Z/')"
if renew_epoch="$(date -D '%Y-%m-%dT%H:%M:%SZ' -d "${normalized}" +%s 2>/dev/null)"; then
[ $(( renew_epoch + ${duration:-300} )) -le "$(date +%s)" ] && reclaim=true
else
echo "cannot parse Lease renewTime: ${renew}" >&2; exit 1
fi
fi
if [ "${reclaim}" = true ]; then
now="$(date -u +%Y-%m-%dT%H:%M:%S.000000Z)"
# The resourceVersion test makes the take-over atomic: if another
# waiter got there first, this patch fails instead of double-granting.
kubectl patch lease "${lock}" -n "${lock_ns}" --type=json -p "[
{\"op\":\"test\",\"path\":\"/metadata/resourceVersion\",\"value\":\"${version}\"},
{\"op\":\"add\",\"path\":\"/spec/holderIdentity\",\"value\":\"${HOLDER}\"},
{\"op\":\"add\",\"path\":\"/spec/acquireTime\",\"value\":\"${now}\"},
{\"op\":\"add\",\"path\":\"/spec/renewTime\",\"value\":\"${now}\"}
]" >/dev/null 2>&1 && { echo "took over lock from ${current}"; exit 0; }
fi
waited=$(( waited + 5 ))
[ "${waited}" -lt "${LOCK_WAIT_SECONDS}" ] || {
echo "timed out after ${waited}s waiting for ${lock_ns}/${lock} held by ${current}" >&2; exit 1; }
echo "waiting for ${lock_ns}/${lock} held by ${current} (${waited}s)"
sleep 5
done
# 3. What to reconcile: the Artifactory URL, one pull Secret per namespace
# that currently belongs to this project, and the repository list.
- name: inspect-project
# The array param arrives as argv, which is the only way a step can
# receive one; "$@" below iterates the package types.
args: ["$(params.repositoryPackageTypes[*])"]
script: |
#!/usr/bin/env sh
set -eu
[ -n "${JFROG_URL}" ] || { echo "jfrogUrl is required" >&2; exit 1; }
printf '%s' "${JFROG_URL}" > "$(results.jfrogUrl.path)"
kubectl get namespaces -l "cpaas.io/project=${PROJECT}" \
-o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' \
| awk -v s="${PROJECT}-jfrog-pull" '
BEGIN { printf "["; sep = "" }
NF { printf "%s\"%s/%s\"", sep, $0, s; sep = "," }
END { print "]" }' > "$(results.imagePullSecrets.path)"
# The jfrogRepositories YAML is built here rather than written into the
# Task invocation, so the package types and provision-vs-reference
# choice are Pipeline parameters instead of a Pipeline edit.
case "${REPOSITORY_MODE}" in
provision|reference) : ;;
*) echo "repositoryMode must be provision or reference, got: ${REPOSITORY_MODE}" >&2; exit 1 ;;
esac
{
printf '%s:\n' "${REPOSITORY_MODE}"
for t in "$@"; do
printf ' - name: %s-%s\n' "${PROJECT}" "${t}"
# A reference entry takes a name only: the repository already
# exists and this Task must not try to redefine it.
[ "${REPOSITORY_MODE}" = provision ] && printf ' packageType: %s\n' "${t}"
done
} > "$(results.jfrogRepositories.path)"
echo "url=${JFROG_URL} pullSecrets=$(cat "$(results.imagePullSecrets.path)")"
echo "repositories (${REPOSITORY_MODE}):"; cat "$(results.jfrogRepositories.path)"
- name: provision
runAfter: [prepare-project-context]
taskRef:
name: jfrog-connector-automatic-creation
params:
- name: jfrogUrl
value: $(tasks.prepare-project-context.results.jfrogUrl)
- name: connector
value: $(tasks.prepare-project-context.results.connectorNs)/$(params.project)-jfrog
- name: jfrogCliImage
value: $(params.jfrogCliImage)
- name: jfrogRepositories
value: $(tasks.prepare-project-context.results.jfrogRepositories)
- name: permissions
value: ["$(params.permissions[*])"]
- name: tokenExpiry
value: $(params.tokenExpiry)
- name: imagePullSecrets
value: ["$(tasks.prepare-project-context.results.imagePullSecrets[*])"]
- name: bindImagePullSecretToSA
value: $(params.bindImagePullSecretToSA)
- name: serviceAccountName
value: $(params.serviceAccountName)
workspaces:
- name: jfrog-secret
workspace: jfrog-admin
finally:
- name: release-project-lock
params:
- { name: project, value: $(params.project) }
- { name: runNamespace, value: $(context.pipelineRun.namespace) }
- { name: holder, value: $(context.pipelineRun.name) }
- { name: kubectlImage, value: $(params.kubectlImage) }
taskSpec:
params:
- { name: project, type: string }
- { name: runNamespace, type: string }
- { name: holder, type: string }
- { name: kubectlImage, type: string }
steps:
- name: release
image: $(params.kubectlImage)
securityContext:
allowPrivilegeEscalation: false
capabilities:
drop: ["ALL"]
runAsNonRoot: true
runAsUser: 65532
seccompProfile:
type: RuntimeDefault
env:
- { name: LOCK_NS, value: $(params.runNamespace) }
- { name: PROJECT, value: $(params.project) }
- { name: HOLDER, value: $(params.holder) }
script: |
#!/usr/bin/env sh
set -eu
lock="jfrog-autocreate-${PROJECT}"
current="$(kubectl get lease "${lock}" -n "${LOCK_NS}" \
-o jsonpath='{.spec.holderIdentity}' 2>/dev/null || true)"
# Only ever delete the Lease this run holds: a run that timed out waiting must not
# release the lock the run ahead of it is holding.
if [ "${current}" = "${HOLDER}" ]; then
kubectl delete lease "${lock}" -n "${LOCK_NS}" --ignore-not-found
echo "released ${LOCK_NS}/${lock}"
fi
EOF
上面的内容没有任何部分是按命名空间固定的——这正是上下文任务的作用:
-
pull Secret 的 registry 键是 jfrogUrl 权威。 Task 会将 auths 条目写入 jfrogUrl 的 host:port
下——对于 https://jfrog.example.com,即 jfrog.example.com——因此,只有以相同 host:port
开头的镜像引用,Pod 才会获取该凭证。当 Artifactory 以 repository-path 风格在根路径提供其 docker registry 时,<jfrog-host>/<repository>/<image>:<tag> 随后无需在 Pod 中设置任何 imagePullSecrets 即可工作。请在依赖此行为前检查自己的部署:当 docker 端点与 API 使用的 host:port
不一致时——例如使用单独的端口、每个仓库的子域名或其他位置的反向代理——Secret 将无法匹配镜像引用中的 registry,拉取会回退到匿名方式,并以 unauthorized 失败,且没有任何信息指向这里。将 jfrogUrl 设置为提供 docker 服务的 host:port
,或为该主机添加第二个 pull Secret。
-
pull Secret 是派生出来的,而不是列出的。 inspect-project 会查询每个带有 cpaas.io/project=<project> 的命名空间,并为每个命名空间生成一个 <namespace>/<project>-jfrog-pull 条目,Task 会将其作为 imagePullSecrets 数组接收。将命名空间添加到项目后,下一次运行也会在那里写入 pull Secret;无需编辑 Pipeline。
-
jfrogUrl 是地址;workspace 是凭证。 Pipeline 将 Artifactory 源作为参数接收,并且不会为其查找 Connector。凭证是独立的,也不会进入 Pipeline:jfrog-admin workspace 在步骤 3中通过 Connectors CSI driver 绑定到管理员 Connector,Task 则通过代理进行身份验证。
保持 jfrogUrl 与该 Connector 的 spec.address 相同。系统不会验证这一点,而不匹配会以令人困惑的静默方式出现:凭证仍然正确,因此运行可以顺利完成身份验证,却连接到了错误的 Artifactory。挂载无法消除这种重复——它携带的是代理地址(connector.status.proxyAddress,以及 HTTP(S)_PROXY 中的 .env),而不是上游 URL——因此必须在某处声明地址,而参数是最简单的位置。
-
Connector 的落点是解析得到的,而不是假定的。 resolve-connector-namespace 会读取 ACP 注解 cpaas.io/project-inner-namespace,因此在 ACP 上,项目的每个命名空间都会汇聚到项目内部命名空间中的一个 Connector 和一个令牌。如果没有该注解,它会回退到触发运行的命名空间,从而为每个命名空间使用一个 Connector——所有 Connector 共享项目的仓库,但各自使用不同的令牌。如果希望在没有内部命名空间的集群上采用汇聚后的结构,请设置该注解,或将该步骤替换为固定命名空间。
-
同一项目的运行会串行执行。 如果两个命名空间同时加入项目,它们就会争用同一个 Artifactory group generation 和 permission target。acquire-project-lock 会在此 Pipeline 运行所在的命名空间中获取名为 jfrog-autocreate-<project> 的 coordination.k8s.io Lease,最多等待 lockWaitSeconds 以等待其他运行,回收持有者已失效的 Lease(经过 lockDurationSeconds 时间未刷新),而 finally 任务会释放该 Lease——但仅当此运行仍是持有者时。按项目而不是按命名空间为 Lease 设置键,正是让同级命名空间发生争用的原因;不同项目的运行则不会相互争用。
-
仓库列表是构建出来的,而不是直接写入的。 inspect-project 根据两个参数渲染 jfrogRepositories YAML,并将其作为结果交给 Task。repositoryPackageTypes 默认为 ["docker"]——一个仓库,即 <project>-docker——而 repositoryMode 决定创建这些仓库,还是仅授予访问权限。更改其中任一项都是参数更改,而不是 Pipeline 编辑。
最有可能需要更改的三项内容:
-
项目获得哪些仓库。 向 repositoryPackageTypes 添加包类型;每种类型都会变成一个 <project>-<packageType>。对于除了镜像之外还需要 Maven 仓库的项目:
- name: repositoryPackageTypes
value: ["docker", "maven"]
不适合 <project>-<packageType> 的布局——例如共享上游、虚拟仓库或按环境命名——超出了上下文任务的渲染能力。请在那里将 jfrogRepositories 结果替换为自己的内容;有关 Task 接受的内容,请参阅jfrogRepositories Schema。
-
Task 镜像的来源。 Pipeline 会传递 jfrogCliImage,因为 Task 自身的默认值指向发布该镜像的 registry,而你的集群通常无法访问该 registry。如果在此处不设置该值,provision task 会以 ErrImagePull 失败,且没有其他线索。请将其指向你的镜像仓库。
-
授予的操作。 默认值包含 delete,因为 Artifactory 会将覆盖现有 artifact 视为删除,否则重新推送 tag 的 CI 将失败。它比 Task 自身的 ["read"] 默认值更宽泛,因此,对于仅使用 artifact 的项目,请将其缩小为 ["read"]。请参阅权限。
已存在其仓库的项目
默认的 repositoryMode: provision 会在仓库不存在时创建仓库,并保持现有仓库不变,因此,为仓库已经手动创建的项目进行接入也可以正常工作——运行会找到这些仓库,并仅授予访问权限。
当仓库由其他位置管理,且此自动化绝不能创建仓库时,请设置 repositoryMode: reference:
- name: repositoryMode
value: reference
两者的区别体现在拼写错误的处理方式上。在 provision 模式下,拼错的名称会生成一个新的空仓库,并使运行成功;在 reference 模式下,运行会失败并指出找不到的仓库,因为 Task 从不创建 reference: 条目。这使得对于已建立的 Artifactory,reference 是更安全的模式,但代价是在有人创建仓库之前运行会持续失败。
两种模式都要求名称为 <project>-<packageType>。如果现有仓库的名称不同,则必须在其中一侧进行重命名——可以在 Artifactory 中重命名,也可以将渲染后的 jfrogRepositories 结果替换为自己的内容。
要接入一个已经存在的项目,无需进行其他更改:为其某个命名空间添加标签(或创建一个新的命名空间),运行就会协调现有仓库、身份和 Secret。可以安全地重新运行——请参阅重新运行以更改范围或更新凭证。
步骤 2 — 授予 Pipeline ServiceAccount 访问项目命名空间的权限
Pipeline 会写入它所在之外的命名空间,因此其 ServiceAccount 需要在这些命名空间中拥有权限。创建一次 ClusterRole,并在整个集群范围内进行绑定,即可让新项目命名空间无需进一步操作就能正常工作。
cat <<'EOF' | envsubst '$TARGET_NS' | kubectl apply -f -
apiVersion: v1
kind: ServiceAccount
metadata:
name: jfrog-project-provision
namespace: $TARGET_NS
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
# Cluster-scoped, so the name carries $TARGET_NS: a second install in
# another management namespace would otherwise rebind this one's subjects.
name: jfrog-project-provision-$TARGET_NS
rules:
- apiGroups: [""]
resources: ["secrets"]
verbs: ["get", "create", "patch"]
- apiGroups: [""]
resources: ["serviceaccounts"]
verbs: ["get", "update"]
- apiGroups: ["connectors.alauda.io"]
resources: ["connectors"]
verbs: ["get", "create", "patch"]
# `get` because the Task checks each target namespace exists before writing
# anything; `list` because the context task finds the project's namespaces by
# label, and a label query cannot be narrowed with resourceNames.
- apiGroups: [""]
resources: ["namespaces"]
verbs: ["get", "list"]
# The per-project lock.
- apiGroups: ["coordination.k8s.io"]
resources: ["leases"]
verbs: ["get", "create", "patch", "delete"]
# Before reclaiming a lock, the context task asks whether the holding
# PipelineRun is still alive.
- apiGroups: ["tekton.dev"]
resources: ["pipelineruns"]
verbs: ["get"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: jfrog-project-provision-$TARGET_NS
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: jfrog-project-provision-$TARGET_NS
subjects:
- kind: ServiceAccount
name: jfrog-project-provision
namespace: $TARGET_NS
EOF
除了 create 之外,还需要 patch:Task 会使用 kubectl apply 应用更改,该操作会在修补对象之前读取实时对象。仅当 bindImagePullSecretToSA 为 true 时才需要 serviceaccounts 规则,而 namespaces: get 是必需的,因为 Task 拒绝写入它无法确认存在的命名空间。
了解集群范围绑定授予的权限。针对这些规则的 ClusterRoleBinding 允许任何能以此 ServiceAccount 身份运行的对象按名称读取集群中的每个 Secret——包括管理员 Connector 自身的 Artifactory 凭证、registry 凭证以及其他 Connector 的 Secret——并覆盖任何命名空间中的 Secret 和 default ServiceAccount。Task 自身只会操作其参数中指定的命名空间;集群范围绑定只是为了方便,并非必需。
按优先级排序,有两种避免方式:
- 按命名空间绑定。保留 ClusterRole(使规则集中存放在一处),并在每个项目命名空间中创建指向它的 RoleBinding,同时创建一个使用
resourceNames 缩小范围的 namespaces: get ClusterRole。让负责创建项目命名空间的组件同时创建 RoleBinding,这样自动化流程无需介入。
- 通过
kube-config 定向。将 kube-config workspace 绑定到一个限定在项目命名空间范围内的凭证,这样该 ServiceAccount 完全不需要集群权限——请参阅多集群,其中介绍了在单个集群内以相同方式工作的方案。
无论选择哪种方式,都应限制谁可以使用此 ServiceAccount 在 $TARGET_NS 中创建 PipelineRun 和 TaskRun:该权限等同于上述绑定授予的全部权限。
步骤 3 — 安装 Triggers
cat <<'EOF' | envsubst '$TARGET_NS $JFROG_ADMIN $JFROG_URL' | kubectl apply -f -
apiVersion: v1
kind: ServiceAccount
metadata:
name: jfrog-autocreate-el-sa
namespace: $TARGET_NS
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: jfrog-autocreate-el-sa-binding
namespace: $TARGET_NS
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: tekton-triggers-eventlistener-roles
subjects:
- kind: ServiceAccount
name: jfrog-autocreate-el-sa
namespace: $TARGET_NS
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: jfrog-autocreate-el-sa-clusterbinding-$TARGET_NS
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: tekton-triggers-eventlistener-clusterroles
subjects:
- kind: ServiceAccount
name: jfrog-autocreate-el-sa
namespace: $TARGET_NS
---
apiVersion: triggers.tekton.dev/v1beta1
kind: TriggerBinding
metadata:
name: jfrog-autocreate-binding
namespace: $TARGET_NS
spec:
params:
- name: namespace
value: $(body.metadata.name)
- name: project
value: $(extensions.project)
---
apiVersion: triggers.tekton.dev/v1beta1
kind: TriggerTemplate
metadata:
name: jfrog-autocreate-template
namespace: $TARGET_NS
spec:
params:
- name: namespace
- name: project
- name: jfrogUrl
default: $JFROG_URL
resourcetemplates:
- apiVersion: tekton.dev/v1
kind: PipelineRun
metadata:
generateName: jfrog-autocreate-
labels:
autocreate.connectors.alauda.io/project: $(tt.params.project)
spec:
pipelineRef:
name: jfrog-project-provision
params:
- name: namespace
value: $(tt.params.namespace)
- name: project
value: $(tt.params.project)
- name: jfrogUrl
value: $(tt.params.jfrogUrl)
taskRunTemplate:
serviceAccountName: jfrog-project-provision
podTemplate:
securityContext:
fsGroup: 65532
runAsNonRoot: true
seccompProfile:
type: RuntimeDefault
workspaces:
- name: jfrog-admin
csi:
driver: connectors-csi
readOnly: true
volumeAttributes:
connectors: $TARGET_NS/$JFROG_ADMIN
---
apiVersion: triggers.tekton.dev/v1beta1
kind: EventListener
metadata:
name: jfrog-autocreate-el
namespace: $TARGET_NS
spec:
serviceAccountName: jfrog-autocreate-el-sa
triggers:
- name: jfrog-autocreate-trigger
bindings:
- kind: TriggerBinding
ref: jfrog-autocreate-binding
interceptors:
- ref:
kind: ClusterInterceptor
name: cel
params:
- name: filter
value: (header.match('ce-type', 'dev.knative.apiserver.resource.add') || header.match('ce-type', 'dev.knative.apiserver.resource.update')) && body.metadata.labels['cpaas.io/project'] != '' && body.metadata.labels['cpaas.io/project'] != 'cpaas-system'
- name: overlays
value:
- key: project
expression: body.metadata.labels['cpaas.io/project']
template:
ref: jfrog-autocreate-template
EOF
CEL 过滤器用于避免该触发器在集群中的每个命名空间上运行:只有带有非空 cpaas.io/project 标签的命名空间才会进入 Pipeline,同时该标签也会作为 project 参数传入。
被过滤的事件并不表示被拒绝:无论结果如何,EventListener 都会返回 202,然后由过滤器决定是否创建任何对象。请通过查找 PipelineRun 来确认结果,而不是查看 HTTP 状态。
它同时匹配 resource.add 和 resource.update,二者都是必需的:命名空间通常会先创建,之后才加入项目;这会以更新而非创建的形式到达此 EventListener。删除 resource.update 会导致之后添加到项目的所有命名空间被静默跳过。
代价是,任何对带标签命名空间的更新都会触发一次运行——注解更改、配额编辑或重新设置标签都包括在内。这些运行具有幂等性:仓库、组、用户和权限目标都已存在;如果运行发现没有任何需要更改的内容,就会以 token-rotated: false 结束,而不会重写 Secrets——其 resourceVersion 甚至不会发生变化。将命名空间添加到项目时也是如此:现有令牌会从 auth Secret 中读回,唯一的写入操作是创建新命名空间的 pull Secret 及其 default ServiceAccount 绑定。
只有当 Connector 命名空间中没有可用于读取已存储令牌的 auth Secret 时,才会创建令牌:项目的首次运行,以及在没有 cpaas.io/project-inner-namespace 注解的集群上为每个新标记的命名空间创建令牌,因为此时 Connector 命名空间会跟随触发命名空间,而新命名空间尚无 Secret。这也是更应采用步骤 1中所述收敛架构的原因之一。
同样无害的情况还包括:项目根本没有任何带标签的命名空间。当命名空间创建后很快被删除,或排队的事件延迟重新传递时,就可能出现这种情况。imagePullSecrets 返回空值,没有任何内容需要写入,运行会成功;无论项目之后有哪些命名空间,下一个事件或定时任务都会使其达到收敛状态。
因此,浪费的是 PipelineRun 对象和 Pod 调度,而不是 Artifactory 中的反复变更。以下两点可以控制这种浪费:
- 让 Tekton 清理已完成的运行——使用平台附带的清理器,或使用
PipelineRun TTL——以免管理命名空间中不断累积这些对象。
- 让
cpaas.io/project 标签与项目本身一样受到控制:它决定为命名空间配置哪个项目,而对带标签命名空间的每次编辑都会触发另一次运行。
验证
创建一个带有项目标签的命名空间:
kubectl create -f - <<'EOF'
apiVersion: v1
kind: Namespace
metadata:
name: demo-project-dev
labels:
cpaas.io/project: demo-project
EOF
为现有命名空间添加标签的方式相同——这就是“命名空间稍后加入项目”的路径,并且会以更新的形式到达。使用一个已存在的命名空间;此示例会先创建一个,因为项目的第二个命名空间通常会在加入项目之前创建:
kubectl create namespace demo-project-staging
kubectl label namespace demo-project-staging cpaas.io/project=demo-project
几秒钟内应该会出现一个 PipelineRun——实际上通常会出现多个,因为平台会快速连续写入命名空间的标签、注解和配额,而每次写入都会产生另一个 resource.update 事件。这是预期行为,而不是故障:每个项目的 Lease 会将它们串行化,第一个运行会执行操作,其余运行会以 token-rotated: false 结束。
kubectl get pipelinerun -n "$TARGET_NS" \
-l autocreate.connectors.alauda.io/project=demo-project
运行完成后,项目命名空间中应包含 Connector、其 auth Secret 和 pull Secret:
kubectl get connector,secret -n demo-project-dev
kubectl wait --for=condition=Ready connector/jfrog -n demo-project-dev --timeout=120s
kubectl get serviceaccount default -n demo-project-dev -o jsonpath='{.imagePullSecrets}'
Artifactory 中则应包含存储库、组、用户和权限目标——Task 结果会列出每一项:
RUN="$(kubectl get pipelinerun -n "$TARGET_NS" \
-l autocreate.connectors.alauda.io/project=demo-project \
--sort-by=.metadata.creationTimestamp -o jsonpath='{.items[-1:].metadata.name}')"
kubectl get pipelinerun "$RUN" -n "$TARGET_NS" -o jsonpath='{.status.results}'
这会输出存储库、Connector 引用、写入的每个 pull Secret(image-pull-secret-refs,项目中每个命名空间对应一项),以及是否创建了令牌。
--sort-by=.metadata.creationTimestamp 很重要:PipelineRun 使用 generateName 命名,因此没有它时,你读取到的会是名称排序最后的那个运行。Pipeline 会重新导出 Task 的四个结果;至于其余结果——Artifactory 用户、组和权限目标——请直接从 provisioning TaskRun 中读取:
kubectl get taskrun -n "$TARGET_NS" \
-l tekton.dev/pipelineRun="$RUN",tekton.dev/pipelineTask=provision \
-o jsonpath='{.items[*].status.results}'
现有项目及其持续续期
一个定时任务可以弥补以下两个缺口:
- 已经存在的项目。 EventListener 只能看到变更。在此流程安装之前就已存在的项目不会触发事件,因此会一直处于未配置状态,直到有人编辑其某个命名空间。
- 令牌会过期。 使用默认的
tokenExpiry 时,创建的令牌有效期为 30 天,并且不会有任何机制自动重新运行 Pipeline。
这两种情况需要的都是同一件事:现在按需为每个项目运行一次 Pipeline,之后按计划运行。
每个项目运行一次,而不是每个命名空间运行一次。 存储库、Artifactory 身份和权限目标都是按项目标识的,而上下文 Task 会从带有该项目标签的所有命名空间派生 pull Secret——因此一次运行即可覆盖所有这些命名空间。对于包含两个命名空间的项目,一次运行会返回:
image-pull-secret-refs = ["<ns-a>/<project>-jfrog-pull", "<ns-b>/<project>-jfrog-pull"]
token-rotated = false
token-rotated: false 是另一半答案:如果没有需要续期的内容,运行会复用已存储的令牌而不进行任何写入,这使得相同的循环可以安全地放到定时器上运行。
唯一不会按项目收敛的是 Connector 的放置位置:当集群没有 cpaas.io/project-inner-namespace 注解时,Connector 会被放置到你传入的命名空间中,因此如果每个命名空间都需要自己的 Connector,就要为每个命名空间运行一次。请参阅步骤 1下的决策列表。
要为哪些项目运行
当项目超过少数几个后,手动维护列表就不再可行。改为读取标签,并排除平台自身的项目:
kubectl get ns -l cpaas.io/project \
-o jsonpath='{range .items[*]}{.metadata.labels.cpaas\.io/project}{"\n"}{end}' \
| sort -u | grep -vx cpaas-system
这会覆盖至少有一个带标签命名空间的每个项目,包括你手动添加标签的命名空间,并且除了 namespaces: list 外无需其他配置。
定时任务
管理命名空间中的一个 CronJob 对象即可弥补这两个缺口:它会按设定周期为每个项目重新运行 Pipeline,而根据相同定义创建的 Job 则用于回填。无需依赖笔记本电脑运行,也无需随着项目的增删而重新应用配置。
它的 ServiceAccount 所需权限少于 Pipeline:列出命名空间,以及在管理命名空间中创建 PipelineRun。
cat <<'EOF' | envsubst '$TARGET_NS' | kubectl apply -f -
apiVersion: v1
kind: ServiceAccount
metadata:
name: jfrog-project-backfill
namespace: $TARGET_NS
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRole
metadata:
name: jfrog-project-backfill-$TARGET_NS
rules:
# Which projects exist, and one namespace for each — both come from the
# cpaas.io/project label, so this is the only cluster-wide read needed.
- apiGroups: [""]
resources: ["namespaces"]
verbs: ["list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
name: jfrog-project-backfill-$TARGET_NS
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: ClusterRole
name: jfrog-project-backfill-$TARGET_NS
subjects:
- kind: ServiceAccount
name: jfrog-project-backfill
namespace: $TARGET_NS
---
apiVersion: rbac.authorization.k8s.io/v1
kind: Role
metadata:
name: jfrog-project-backfill
namespace: $TARGET_NS
rules:
- apiGroups: ["tekton.dev"]
resources: ["pipelineruns"]
verbs: ["create", "list"]
---
apiVersion: rbac.authorization.k8s.io/v1
kind: RoleBinding
metadata:
name: jfrog-project-backfill
namespace: $TARGET_NS
roleRef:
apiGroup: rbac.authorization.k8s.io
kind: Role
name: jfrog-project-backfill
subjects:
- kind: ServiceAccount
name: jfrog-project-backfill
namespace: $TARGET_NS
EOF
它会创建以 jfrog-project-provision 运行的 PipelineRun,因此请限制谁可以在 $TARGET_NS 中创建 PipelineRun——此 ServiceAccount 现在也是其中之一。
cat <<'EOF' | envsubst '$TARGET_NS $JFROG_ADMIN $JFROG_URL $REGISTRY' | kubectl apply -f -
apiVersion: batch/v1
kind: CronJob
metadata:
name: jfrog-project-backfill
namespace: $TARGET_NS
spec:
# Weekly, which is well inside the renewal window of the default 30-day
# token. Any period shorter than `tokenExpiry - tokenRenewBeforeDays`
# works; see the note below.
schedule: "0 3 * * 0"
concurrencyPolicy: Forbid
successfulJobsHistoryLimit: 3
failedJobsHistoryLimit: 3
jobTemplate:
spec:
backoffLimit: 2
template:
spec:
serviceAccountName: jfrog-project-backfill
restartPolicy: OnFailure
securityContext:
runAsNonRoot: true
runAsUser: 65532
seccompProfile:
type: RuntimeDefault
containers:
- name: backfill
image: $REGISTRY/alauda-connectors/kubectl:v1.33
securityContext:
allowPrivilegeEscalation: false
readOnlyRootFilesystem: true
capabilities:
drop: ["ALL"]
env:
- { name: TARGET_NS, value: $TARGET_NS }
- { name: JFROG_URL, value: $JFROG_URL }
- { name: JFROG_ADMIN, value: $JFROG_ADMIN }
command: ["/bin/sh", "-c"]
args:
- |
set -eu
projects="$(kubectl get ns -l cpaas.io/project \
-o jsonpath='{range .items[*]}{.metadata.labels.cpaas\.io/project}{"\n"}{end}' \
| sort -u | grep -vx cpaas-system || true)"
# grep exits 1 when nothing survives the filter, which `set -e`
# would turn into a silent exit before the message below.
[ -n "$projects" ] || { echo "no projects found" >&2; exit 1; }
rc=0
for project in $projects; do
ns="$(kubectl get ns -l "cpaas.io/project=$project" \
-o jsonpath='{.items[0].metadata.name}' 2>/dev/null || true)"
if [ -z "$ns" ]; then
echo "skip $project: no namespace carries its label"
continue
fi
# One run per project. Failing one project must not stop the rest.
kubectl -n "$TARGET_NS" create -f - <<PR || rc=1
apiVersion: tekton.dev/v1
kind: PipelineRun
metadata:
generateName: jfrog-backfill-$project-
labels:
autocreate.connectors.alauda.io/project: $project
spec:
pipelineRef:
name: jfrog-project-provision
params:
- { name: namespace, value: $ns }
- { name: project, value: $project }
- { name: jfrogUrl, value: $JFROG_URL }
taskRunTemplate:
serviceAccountName: jfrog-project-provision
workspaces:
- name: jfrog-admin
csi:
driver: connectors-csi
readOnly: true
volumeAttributes:
connectors: $TARGET_NS/$JFROG_ADMIN
PR
done
exit $rc
EOF
回填就是同一个任务,立即运行——无需第二个清单,也无需等待计划任务:
kubectl -n "$TARGET_NS" create job --from=cronjob/jfrog-project-backfill jfrog-backfill-now
kubectl -n "$TARGET_NS" logs job/jfrog-backfill-now -f
根据令牌而不是习惯选择周期。 周期必须短于 tokenExpiry - tokenRenewBeforeDays——使用默认值时应少于 23 天——这样每个令牌都能在有效期内续期。更频繁地运行会增加空闲 PipelineRun,而不会导致 Artifactory 发生反复变更:没有需要续期内容的运行会以 token-rotated: false 结束。
无需考虑并发问题。 concurrencyPolicy: Forbid 会防止两个计划任务重叠;在一次遍历中,每个项目的 Lease 会使同一项目的运行排队,而不同项目的运行之间不会相互竞争。循环会创建运行但不会等待它们完成,因此运行缓慢的项目不会阻塞其余项目;同一项目的后续运行最多等待 lockWaitSeconds。
该任务只会创建 PipelineRun,不会等待它们完成。之后检查结果:
kubectl -n "$TARGET_NS" get pipelineruns \
-l autocreate.connectors.alauda.io/project \
--sort-by=.metadata.creationTimestamp
请参阅重新运行以更改范围或续期凭证,了解重新运行会更改和不会更改哪些内容,以及凭证必须立即停止工作时使用的 tokenPolicy: refresh。
多集群
当项目命名空间位于业务集群,而自动化组件仅位于管理集群时,其结构与 connector-auto-create Pipeline 相同:管理集群上每个业务集群对应一个 EventListener,每个业务集群上的 adapter 都有一个指向该 EventListener 的 K_SINK,TriggerTemplate 上还有一个携带该集群凭证的 kube-config workspace。
这需要进行三处修改。首先,在 Pipeline 上声明 workspace(紧邻 jfrog-admin):
workspaces:
- name: jfrog-admin
description: Admin JFrog Connector, mounted through the Connectors CSI driver.
- name: kube-config
description: Credential for the cluster that receives the Connector and Secrets.
然后将其传递给 Task(在 provision task 上的 jfrog-secret 映射旁):
workspaces:
- name: jfrog-secret
workspace: jfrog-admin
- name: kube-config
workspace: kube-config
绑定 Pipeline 未声明的 workspace 会在 PipelineRun 准入时被拒绝,因此请在修改 TriggerTemplate 之前完成这两处修改。最后,在 TriggerTemplate 中绑定它:
workspaces:
- name: jfrog-admin
csi:
driver: connectors-csi
readOnly: true
volumeAttributes:
connectors: $TARGET_NS/$JFROG_ADMIN
- name: kube-config
secret:
secretName: target-kubeconfig-a
绑定了 kube-config 后,Task 会将 Connector、Secret 和 pull Secret 应用到 kubeconfig 所指向的集群,而 Pipeline ServiceAccount 不再需要对本地集群的项目命名空间拥有权限——因此请删除 Step 2 中的 ClusterRoleBinding,而不要留下不再使用的集群范围 Secret 授权。
Step 2 和 Step 3 中的集群范围对象的名称包含 $TARGET_NS,原因正在于此:在另一个管理命名空间中进行第二次安装时,它会获得自己的 ClusterRole 和绑定,而不会悄然重新绑定第一个安装的主体。如需完整的多集群操作指南——包括 adapter 部署、NodePort 或 Ingress 暴露,以及每个集群的凭证——请参阅多集群安装。
故障排除
未出现 PipelineRun
首先检查 adapter 的 K_SINK——这是最常见的原因,因为 adapter 自己的安装页面会将其指向另一条流程的 EventListener:
kubectl -n "$TARGET_NS" get deploy ns-event-source \
-o jsonpath='{.spec.template.spec.containers[0].env[?(@.name=="K_SINK")].value}'
kubectl -n "$TARGET_NS" logs deploy/ns-event-source --tail=20
其配置值必须是 http://el-jfrog-autocreate-el:8080。如果不是,adapter 会针对每次命名空间变更记录 failed to send cloudevent … no such host,而本指南中的其他部分都没有问题。
否则,请检查命名空间是否带有非空的 cpaas.io/project 标签——这是过滤器唯一接受的内容,无论该标签是在创建时添加的,还是之后重新标记时添加的——并检查 EventListener Pod 是否已就绪。
PipelineRun 在 prepare-project-context 中失败
可能是 jfrogUrl 为空,或者无法获取锁。步骤日志会说明具体原因:jfrogUrl is required,或者记录包含 Lease 名称和持有该 Lease 的运行的行。锁超时表示同一项目的对等运行所需时间超过了 lockWaitSeconds。
PipelineRun 在 provision 中失败
该失败来自 Task 本身——请参阅 Task 指南中的故障排除。此流程中最常见的两个原因是 Artifactory 不是 Pro 版本,以及 Pipeline ServiceAccount 无法写入项目命名空间。
项目的每个命名空间都会触发运行
这是预期行为:项目的每个命名空间都需要自己的 pull Secret。代码库、组、用户和权限目标均按项目标识,因此第二次及后续运行会发现它们已经存在;每次运行都会为项目的每个命名空间写入 pull Secret,并保留其余内容不变。Connector 的落点取决于 cpaas.io/project-inner-namespace 注解——设置该注解时,整个项目使用一个 Connector;未设置时,每个命名空间使用一个 Connector——详见 Step 1。