写在最前

在实际生产中,由于安全合规要求,即便是内网 Harbor 镜像仓库也不能设为公开访问,必须启用身份认证。但如果手动在每个 Deployment 中配置 imagePullSecrets,不仅繁琐,还容易遗漏,带来维护成本和上线风险。

通过引入 Kyverno 策略控制器,我们可以在 Pod 创建前自动注入镜像拉取凭证imagePullSecrets),无需修改任何已有的 YAML 配置,做到安全、自动、无感知地接入私有镜像仓库。这种方式符合企业级 DevOps 自动化和安全治理的双重需求。

https://kyverno.io/policies/other/add-imagepullsecrets/add-imagepullsecrets/

1. 安装部署

kubectl create -f https://github.com/kyverno/kyverno/releases/download/v1.14.0/install.yaml

2. 配置流程

你只需要执行 kubectl create -f add-imagepullsecrets.yaml 把策略部署上去,之后只要 Pod 重建或者新建,Kyverno 就会自动帮它加上 imagePullSecrets: [my-secret],完全不用你去改 Deployment。

而且这个策略支持按镜像地址匹配,比如你可以设置只对 harbor.tanqidi.com/* 这种镜像才注入秘钥,也可以更精细地指定某个项目或镜像路径,控制非常灵活。

注意一点,my-secret 这个凭证需要事先创建在 kyverno 这个命名空间里,Kyverno 会从那里拿来注入到别的命名空间的 Pod 里。

apiVersion: kyverno.io/v1
kind: ClusterPolicy
metadata:
  name: add-imagepullsecrets
  annotations:
    policies.kyverno.io/title: Add imagePullSecrets
    policies.kyverno.io/category: Sample
    policies.kyverno.io/subject: Pod
    policies.kyverno.io/minversion: 1.6.0
    policies.kyverno.io/description: >-
      Images coming from certain registries require authentication in order to pull them,
      and the kubelet uses this information in the form of an imagePullSecret to pull
      those images on behalf of your Pod. This policy searches for images coming from a
      registry called `corp.reg.com` and, if found, will mutate the Pod to add an
      imagePullSecret called `my-secret`.
spec:
  rules:
  - name: add-imagepullsecret
    match:
      any:
      - resources:
          kinds:
          - Pod
    mutate:
      patchStrategicMerge:
        spec:
          containers:
          - <(image): "harbor.tanqidi.com/*"
          imagePullSecrets:
          - name: my-secret