测试舵图模板

Testing helm chart templating

有没有办法测试模板是否适用于所有可能的值?
(注意:这与 helm 测试不同,helm 测试用于通过作业中的任意代码 运行 测试已部署的图表)。

我想要实现的是迭代一组值并检查为每个值生成的 K8s 资源。

假设我们要测试图表是否正确书写:

图表:
Values.yaml

app:
  port: 8081

pod2:
   enabled: true

AppPod.yaml

apiVersion: apps/v1
kind: Deployment
metadata:
  name: AppPod
  labels:
    app: nginx
spec:
...
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: {{ $.Values.app.port| default 8080  }}

Pod2.yaml

{{- if $.Values.pod2.enabled }}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: Pod2
  labels:
    app: nginx2
spec:
...
{{- end}}

我们要运行进行以下测试:

所以基本上是为了测试模板逻辑。

我现在在做什么:
每当我修改图表中的某些内容时,我只是 运行 不同 Values.yaml 的 helm 模板并手动检查结果。手动执行此操作很容易出错,并且图表包含的模板越多,就越耗时。

是否有任何内置的 helm 功能或单独的框架?

是的,我们用 rego policy rules 来做到这一点。设置并不复杂,这就是它作为我们管道之一的一部分的样子(这是一个非常简单的入门示例):

# install conftest to be able to run helm unit tests
wget https://github.com/open-policy-agent/conftest/releases/download/v0.28.1/conftest_0.28.1_Linux_x86_64.tar.gz
tar xzf conftest_0.28.1_Linux_x86_64.tar.gz
chmod +x conftest

# you can call "helm template" with other override values of course, too
helm template src/main/helm/my-service/ > all.yaml

echo "running opa policies tests"
if ! ./conftest test -p src/main/helm/my-service/ all.yaml; then
  echo "failure"
  exit 1
fi

my-service 目录中有一个 policy 文件夹,其中包含用于测试的“规则”(尽管这可以作为参数传递)。这是我最近必须编写的两个规则的示例:

package main

deny_app_version_must_be_present[msg] {
    input.kind == "Deployment"
    env := input.spec.template.spec.containers[_].env[_]
    msg := sprintf("env property with name '%v' must not be empty", [env.name])
    "APP_VERSION" == env.name ; "" == env.value
}

deny_app_version_env_variable_must_be_present[msg] {
    input.kind == "Deployment"
    app_version_names := { envs | envs := input.spec.template.spec.containers[_].env[_]; envs.name == "APP_VERSION"}
    count(app_version_names) != 1
    msg := sprintf("'%v' env variable must be preset once", ["APP_VERSION"])
}

这验证了 Deployment 中的容器有一个名为 APP_VERSION 的环境变量,它必须是唯一的并且必须是非空的。