有效的 Kubernetets YAML 文件的 Conftest 失败

Conftest Fails For a Valid Kubernetets YAML File

我有以下简单的 Kubernetes YAML 部署:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ .Values.app.name }}
  namespace: {{ .Values.app.namespace }}
spec:
  selector:
    matchLabels:
      app: {{ .Values.app.name }}
  replicas: 1
  template:
    metadata:
      labels:
        app: {{ .Values.app.name }}
    spec:
      securityContext:
        runAsUser: 1000
        runAsGroup: 3000
        fsGroup: 2000
      containers:
        - name: {{ .Values.app.name }}
          image: {{ .Values.plantSimulatorService.image.repository }}:{{ .Values.plantSimulatorService.image.tag }}
          ports:
            - containerPort: {{ .Values.plantSimulatorService.ports.containerPort }} # Get this value from ConfigMap

我的 test.rego 中有以下内容:

package main

import data.kubernetes

name = input.metadata.name

deny[msg] {
  kubernetes.is_deployment
  not input.spec.template.spec.securityContext.runAsNonRoot

  msg = sprintf("Containers must not run as root in Deployment %s", [name])
}

当我 运行 使用以下命令时:

joesan@joesan-InfinityBook-S-14-v5:~/Projects/Private/infrastructure-projects/plant-simulator-deployment$ helm conftest helm-k8s -p test
WARN - Found service plant-simulator-service but services are not allowed
WARN - Found service plant-simulator-grafana but services are not allowed
WARN - Found service plant-simulator-prometheus but services are not allowed
FAIL - Containers must not run as root in Deployment plant-simulator
FAIL - Deployment plant-simulator must provide app/release labels for pod selectors

如您所见,我确实没有运行将容器设置为 root,但尽管如此,我还是收到了这条错误消息 - Container must not 运行 as root in Deployment plant-simulator

知道原因是什么吗?

您需要将 runAsNonRoot 添加到您的 securityContext:

  securityContext:
    runAsUser: 1000
    runAsGroup: 3000
    fsGroup: 2000
    runAsNonRoot: true

rego 规则只能验证 Yaml 结构 - 它不够聪明,无法确定您的配置实际上是 运行 非根用户。