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
- Variable Initialization: The first two lines initialize the variables
$serviceNamespaceand$serviceTagfrom the values defined in yourvalues.yamlfile. - Conditional Concatenation: The
ifstatement checks if$serviceTagis set. If it is, theprintffunction is used to concatenate theserviceNamespaceandserviceTagwith a hyphen in between. - Final Result: If
serviceNamespaceishelloandserviceTagis1.0.0, the resulting value of$serviceNamespacewill behello-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.