是否可以将整数锚点转换或转换为 yaml 文件中的字符串别名?

Is it possible to convert or cast an integer anchor to a string alias in a yaml file?

对于我的 AKS 容器设置,我想通过环境变量将给定 statefulset 的请求副本数传递给每个 pod。

我试图做到这一点而不重复自己(一次在 "replicas" 设置中,一次在环境变量的设置中)。

我能找到的唯一真正解决方法是使用锚点和别名(基于 Kubernetes StatefulSet - obtain spec.replicas metadata and reference elsewhere in configuration):

apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: solr
spec:
  selector:
    matchLabels:
      app: solr
  serviceName: solr-hs
  replicas: &numReplicas 3
  updateStrategy:
    type: RollingUpdate
  # Make sure pods get created sequentially
  podManagementPolicy: OrderedReady
  template:
    metadata:
      labels:
        app: solr
    spec:
      containers:
      - name: kubernetes-solr
        imagePullPolicy: Always
        image: "..."
        resources:
          requests:
            memory: "8Gi"
            cpu: "0.5"
        ports:
        - containerPort: 8983
        env:
        - name: N_O_REPLICAS
          value: *numReplicas

不幸的是,"env" 值似乎必须是一个字符串,而 "replicas" 的整数值没有被转换或转换。而是抛出以下错误:

v1.EnvVar.v1.EnvVar.Value: ReadString: expects " or n, but found 3, error found in #10 byte of ...|,"value":3},{"name":|..., bigger context ...|:"solr-config"}}},{"name":"N_O_REPLICAS","value":3},

我尝试通过以下方式手动转换为字符串:

value: !!str *numReplicas

但这也不起作用并抛出以下错误:

error converting YAML to JSON: yaml: line 52: did not find expected key

有没有什么方法可以创建允许将整数值作为字符串重用的 Kubernetes YAML 文件?或者对于这种特殊情况是否有其他解决方案?

Helm 是您所需要的。

实际上,Helm 比您需要的更多,但它有一个模板引擎(就像在 Ansible 中一样),这可以帮助您解决问题。此外,今天使用 Helm 它几乎是 Kubernetes 的强制性要求,只是因为它有一个巨大的图表库,可以帮助您非常快速地部署不同的软件,例如通过一个命令部署 Elastic stack 或 Redis ...(几乎)。所以,试试这个,它可以改善您使用 Kubernetes

的工作

尽管您的方法很有趣,但 !!str 不是转换运算符,并且 YAML specification 清楚地表明您尝试的方法行不通:

When a node has more than one occurrence (using aliases), tag resolution must depend only on the path to the first (anchored) occurrence of the node.

所以在 YAML 中这是不可能的,除非 parser/loader 是不符合的。

对于您的问题,IMO 的最佳解决方案是 kubernetes 在将它们添加到环境之前将所有将成为环境变量的参数显式转换为字符串。这样你也可以使用布尔值、日期等。

您也可以使用您喜欢的任何模板系统为 kubernetes 生成 YAML 输入,只要这样的系统允许您 "stringify" 您的整数参数。