go-template split string by delimiter
Asked Answered
M

2

34

I have my own helm chart and I'm trying to perform split without using the _helpers.tpl in one line

my values.yaml file content:

deployment:
    domain: my.domain

I need to split domain name in my template file: my.domain

I have tried to perform this by using the following syntax:

name regex (.*)\.{{ (split .Values.deployment.domain ".")._0 }}\.{{ (split .Values.deployment.domain ".")._1 }}

or

{{- $split := .Values.deployment.domain "." . }}
name regex (.*)\.{{ first split }}\.{{ second split }}

But nothing worked

I'm trying to get the following results in my template file:

name regex (.*)\.my\.domain
Multiplicity answered 5/12, 2018 at 14:31 Comment(0)
R
66

Helm uses the sprig library to provide lots of data manipulation functions, have a look at their docs for strings. You can use the {{ split }} function to do what you want.

$parts := split "." .Values.deployment.domain
$parts._0
Rustler answered 5/12, 2018 at 17:11 Comment(4)
Thank you @alex Pliutau ,you helped me to figured it out that I had a syntax issue. Here is my final results that worked: {{ (split "." .Values.deployment.domain)._0 }}Multiplicity
How can i get last element after split?Pyriform
You can use splitList to create an array, then use last to retrieve the last element in the list. i.e. {{ (splitList "." "http://www.foo.bar.com") | last | quote }}Idaidae
Unfortunately splitList is not in the Helm documentation. However, it works well because Helm uses the Sprig library under the hood: masterminds.github.io/sprigCream
C
0

I needed the filename of a path, so the last element. There are 2 solutions:

Values.yaml

config:
  files:
  - includes/config/xxx/conf/db.yml
  - includes/config/xxx/conf/application.properties
  - includes/config/xxx/conf/custom.properties

Configmap.yaml

kind: ConfigMap
apiVersion: v1
metadata:
  name: xxx
  namespace: {{ .Values.namespace }}
data: 
  {{- range $file := .Values.config.files }} #$file = includes/config/xxx/conf/db.yml

  #Solution 1
  {{- $splitpath := $file | split "/" }} #$splitpath = map[_0:includes _1:config _2:leasone _3:conf _4:db.yml]
  {{- $indexlast := sub (len $splitpath) 1 }} #$indexlast = %!s(int64=4)
  {{- $index := printf "_%d" $indexlast }} #$index = _4
  {{- $filename := index $splitpath $index }} #$filename = db.yml

  #Solution 2
  {{- $filename2 := splitList "/" $file | last | quote }} #$filename2 = db.yml

  {{ $filename }}: |-
    {{- $fileContent := $.Files.Get . }}
    {{- $fileContent | nindent 4 }}
  {{- end }}
Corr answered 26/6, 2023 at 8:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.