json - 将多行 json 字符串插入 helm 模板以进行 base64 编码

标签 json kubernetes yaml kubernetes-helm kubernetes-secrets

我正在尝试将多行 json 字符串插入到 helm 模板中,以进行 Kubernetes secret 所需的 base64 编码。

目标:

  • helm 值被注入(inject)到 json 字符串中
  • 多行 json 字符串必须使用 b64enc 进行 base64 编码
  • myfile1.json不起作用,但 myfile2.json作品。
    我不想把整个 json 文件放在 values.yaml 中。 .
    apiVersion: v1
    kind: Secret
    metadata:
      name: {{ template "mychart.fullname" . }}
      labels:
        app: {{ template "mychart.name" . }}
        chart: {{ template "mychart.chart" . }}
        release: {{ .Release.Name }}
        heritage: {{ .Release.Service }}
    type: Opaque
    data:
      myfile.json: {{ |-
        {
          "item1": {
              "name": "{{ .Values.item1.name }}"
          },
          "item2": {
          }
        } | b64enc }}
      myfile2.json: {{ .Values.myfile2 | b64enc }}
    

    最佳答案

    您实际上不需要对 helm 图表中的 secret 进行 base64 编码。如果您使用 stringData字段而不是 data字段,Kubernetes 知道它需要在 key 部署时对数据进行 base64 编码。

    来自文档(Source):

    The Secret contains two maps: data and stringData. The data field is used to store arbitrary data, encoded using base64. The stringData field is provided for convenience, and allows you to provide secret data as unencoded strings.



    所以我们可以使用 stringData 重写您的 secret 而不是 data并在模板中保留多行 json 字符串,如下所示:
    apiVersion: "v1"
    kind: "Secret"
    metadata:
      name: {{ template "mychart.fullname" . }}
      labels:
        app: {{ template "mychart.name" . }}
        chart: {{ template "mychart.chart" . }}
        release: {{ .Release.Name }}
        heritage: {{ .Release.Service }}
    type: "Opaque"
    stringData:
      myfile.json: |-
        {
          "item1": {
              "name": "{{ .Values.item1.name }}"
          },
          "item2": {
          }
        }
      myfile2.json: {{ .Values.myfile2 }}
    

    请注意,这并不意味着您突然需要担心有未编码的 secret 。 stringData最终将被 base64 编码并转换为 data安装时,因此一旦加载到 Kubernetes 中,它的行为将完全相同。

    同样,来自文档 (强调我的) (Source):

    stringData allows specifying non-binary secret data in string form. It is provided as a write-only convenience method. All keys and values are merged into the data field on write, overwriting any existing values. It is never output when reading from the API.

    关于json - 将多行 json 字符串插入 helm 模板以进行 base64 编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54152619/

    相关文章:

    javascript - 在 Firefox 和 Chrome 中使用 jQuery 获取 JSON 结果时出现问题(IE8 工作)

    yaml - 使用 Assemble/Grunt,是否可以从 YAML 前端小写和连字符化变量

    PHP JSON 解码(带方括号)

    java - MongoDB 通过 Java 存储 JSON 字符串

    kubernetes - 使用 Spring 配置文件时,Apache Ignite .Net 节点不会启动

    kubernetes - 使用 kubectl 列出给定命名空间中的所有对象

    kubernetes - 未随gcloud SDK一起安装kubectl

    python - 如何执行存储为字符串的 bool 逻辑,最好不使用 eval()?

    azure-devops - 在 Azure YAML 管道的脚本阶段下添加多个命令

    c# - 在不知道类型的情况下将 Json.NET 对象转换为传统的 .NET 对象