[SOLVED]: Helm Split String by Delimiter

Helm supports multiple string operations, like split string by delimiter, join string by delimiter, changing the case etc. In this article we will see how to split a string. This usually comes in handy, if we want to split url to separate ingresspath, or to split the ips given as comma separated string.

Helm Split String by Delimiter

For this exercise , a dummy helm chart is taken, where values.yaml is having below content.

[root@c1 linuxdatahub]# cat values.yaml |grep test
test: "sample.com/ingresspath/preview"

Our aim is to create configmap, with key as port and value should only be  the ingresspath. Inorder to achieve this we will have to split the string.  Below syntax can be used for the same

apiVersion: v1
kind: ConfigMap
metadata:
name: linux-data-cm
data:
{{- $ingress:= split "/" .Values.test }}
ceph.cfg: |-
{
"Port": [{{- print $ingress._1 }}]
}
  • From the above code snippet split <delimiter> value will split the string to list and is stored in variable ingress
  • Since we only want to use the second element of the list whose index value is 1. we can use <variable>._1 to utilize the value
  • Similarly by changing the index  and delimiter, we can control the portion of string which we need to use
  • Final configmap will looks as below
{
"Port": [ingresspath]
}

In some cases, we will not be able to foresee the length of list, but we still want to get the last element of the list. Below exercise will help us to fetch the last element of the list without knowing the length of the created list from the split string

Helm Get Last element of List; Split String by Delimiter

  • Below syntax can be used for getting the last element , while doing helm split string
kind: ConfigMap
metadata:
name: linux-data-cm
data:
{{- $ingress:= (splitList "/" .Values.test)|last }}
ceph.cfg: |-
{
"CkeyPort": [{{- print $ingress}}],
}
  • Here we will be using splitList instead of split, and the keyword last will select the last element of the list

References

https://stackoverflow.com/questions/53634583/go-template-split-string-by-delimiter

Also Read

[SOLVED]: Execute Commands on Kubernetes Pods with root access

Search on LinuxDataHub

Leave a Comment