Andres Julia
Andres Julia

Reputation: 91

Is there a way to create an iterable list from a string?

I'm passing the following string through values.yaml:

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

Is there a way to create a list from this, so i can then do something like:

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

The problem is I'm passing the urls var in a dynamic fashion, and I'm also can't avoid using a single string for that (ArgoCD ApplicationSet wont let me pass a list).

Upvotes: 2

Views: 809

Answers (2)

Mikolaj S.
Mikolaj S.

Reputation: 3224

Basically all you need is just add this line in your template yaml:

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

It will import urls string from values.yaml as the list so you will be able run your code which you posted in your question.

Simple example based on helm docs:

  1. Let's get simple chart used in helm docs and prepare it:

    helm create mychart
    rm -rf mychart/templates/*
    
  2. Edit values.yaml and insert urls string:

    urls: http://example.com http://example2.com http://example3.com
    
  3. Create ConfigMap in templates folder (name it configmap.yaml)

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

    As can see, I'm using your loop (with "- " to avoid creating empty lines).

  4. Install chart and check it:

    helm install example ./mychart/
    helm get manifest example
    

    Output:

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

Upvotes: 2

z.x
z.x

Reputation: 2527

Split by spaces to get an array of urls.

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

Upvotes: 1

Related Questions