Search code examples
kubernetes-helmgo-templatessprig-template-functions

Make sure path in Go template always ends with slash


I am writing a Helm chart for a bunch of deployments. I am supplying a value which can be:

my_value: "/opt/my-path"or my_value: "/opt/my-path/"

Now I would want to make sure that there is always a single / at the end of the path.

How do I do this using Go templates?


Solution

  • You can trim the suffix / with trimSuffix function, docs here http://masterminds.github.io/sprig/strings.html, and to add / manually at the end. So regardless the original value you will always get a / at the end. example

    values.yaml:

    path_with_slash: "/my/path/"
    path_without_slash: "/my/path"
    

    inside a template file:

    {{ $path_with_slash := trimSuffix "/" .Values.path_with_slash }}
    {{ $path_without_slash := trimSuffix "/" .Values.path_without_slash }}
    path_with_slash: "{{ $path_with_slash }}/"
    path_without_slash: "{{ $path_without_slash }}/"
    

    rendered file:

    path_with_slash: "/my/path/"
    path_without_slash: "/my/path/"