In Helm templates, you often need to concatenate strings or variables to create dynamic values. This can be particularly useful when constructing names or labels based on user-defined inputs. Below is a guide on how to achieve this using the printf function, which simplifies the process of combining variables with a string in between.

Example Scenario

Suppose you have two variables defined in your values.yaml file:

serviceNamespace: "hello"
serviceTag: "1.0.0"

You want to create a new variable that combines these two with a hyphen in between. Here’s how you can do it:

Code Implementation

You can use the following code snippet in your Helm template:

{{- $serviceNamespace := .Values.serviceNamespace -}}
{{- $serviceTag := .Values.serviceTag -}}
{{- if $serviceTag }}
{{- $serviceNamespace = printf "%s-%s" .Values.serviceNamespace .Values.serviceTag -}}
{{- end }}

Explanation

  1. Variable Initialization: The first two lines initialize the variables $serviceNamespace and $serviceTag from the values defined in your values.yaml file.
  2. Conditional Concatenation: The if statement checks if $serviceTag is set. If it is, the printf function is used to concatenate the serviceNamespace and serviceTag with a hyphen in between.
  3. Final Result: If serviceNamespace is hello and serviceTag is 1.0.0, the resulting value of $serviceNamespace will be hello-1.0.0.

Conclusion

Using the printf function for string concatenation in Helm templates allows for more readable and maintainable code. This method is preferred over manual string manipulation, as it leverages the built-in capabilities of Go templates effectively.