【问题标题】:Is there a way to create an iterable list from a string?有没有办法从字符串创建可迭代列表?
【发布时间】:2021-10-25 20:23:18
【问题描述】:

我正在通过 values.yaml 传递以下字符串:

urls: http://example.com http://example2.com http://example3.com

有没有办法从中创建一个列表,所以我可以这样做:

{{ range $urls }}
{{ . }}
{{ end }}

问题是我以动态方式传递 urls var,而且我也无法避免为此使用单个字符串(ArgoCD ApplicationSet 不会让我传递列表)。

【问题讨论】:

    标签: templates kubernetes yaml kubernetes-helm go-templates


    【解决方案1】:

    基本上你只需要在你的模板中添加这一行yaml:

    {{- $urls := splitList " " .Values.urls }}
    

    它将从values.yaml as the list 导入urls 字符串,这样您就可以运行您在问题中发布的代码。

    基于helm docs的简单示例

    1. 让我们得到helm docs中使用的简单图表并准备它:

      helm create mychart
      rm -rf mychart/templates/*
      
    2. 编辑values.yaml 并插入urls 字符串:

      urls: http://example.com http://example2.com http://example3.com
      
    3. templates文件夹中创建ConfigMap(命名为configmap.yaml

      apiVersion: v1
      kind: ConfigMap
      metadata:
        name: {{ .Release.Name }}-configmap
      data:
        {{- $urls := splitList " " .Values.urls }}
        urls: |- 
          {{- range $urls }}
          - {{ . }}
          {{- end }}
      

      正如所见,我正在使用您的循环(使用“-”来避免创建空行)。

    4. 安装图表并检查它:

      helm install example ./mychart/
      helm get manifest example
      

      输出:

      ---
      # Source: mychart/templates/configmap.yaml
      apiVersion: v1
      kind: ConfigMap
      metadata:
        name: example-configmap
      data:
        urls: |-
          - http://example.com
          - http://example2.com
          - http://example3.com
      

    【讨论】:

      【解决方案2】:

      用空格分割得到一个url数组。

      {{- range _, $v := $urls | split " " }}
      {{ $v }}
      {{- end }}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-11-30
        • 1970-01-01
        • 2014-08-23
        • 2017-08-17
        • 1970-01-01
        • 2019-04-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多