如何通过单个正则表达式自动替换ConfigMap中JSON文件的占位符为values.yaml对应值
Batch Replace Placeholders in JSON for Kubernetes ConfigMap Using Helm
Great question! Instead of writing separate regexReplaceAll calls for each placeholder, you can use Helm's regexReplaceAllFunc to dynamically replace all matching placeholders in one go. This function lets you define custom logic to handle each match, pulling values directly from your values.yaml.
Here's the complete ConfigMap template that achieves your goal:
apiVersion: v1 kind: ConfigMap metadata: name: config data: config.json: |- {{- $content := .Files.Get "config.json" }} {{- $placeholders := .Values.placeholders }} {{- $replaceFunc := func(match string) string }} {{- $key := trimPrefix "%" (trimSuffix "%" match) }} {{- index $placeholders $key | default match }} {{- end }} {{- regexReplaceAllFunc "%([A-Z0-9_]+)%" $content $replaceFunc | nindent 4 }}
How this works:
- Load dependencies: First, we grab the raw content of your
config.jsonfile and store the placeholder mappings fromvalues.yamlin a reusable variable for easier reference. - Define replacement logic: The
$replaceFunctakes each matched placeholder (like%PLACEHOLDER_1%), strips the surrounding%to extract the key name, then fetches the corresponding value fromvalues.placeholders. If a placeholder isn't defined invalues.yaml, it keeps the original placeholder (thanks todefault match) to avoid breaking your JSON structure. - Batch replace:
regexReplaceAllFuncuses the regex%([A-Z0-9_]+)%to match all placeholders wrapped in%, then applies our custom function to each match to inject the correct value.
Example Output:
With your values.yaml setup:
placeholders: PLACEHOLDER_1: Hello PLACEHOLDER_2: World
The generated config.json in the ConfigMap will be:
{ "A":{ "A_KEY":"Hello", "B_KEY":"World" } }
Notes:
- Adjust the regex
%([A-Z0-9_]+)%if your placeholders use other characters (e.g., add lowercase letters with%([a-zA-Z0-9_]+)%). - Ensure you're using Helm 3.5 or newer, as
regexReplaceAllFuncwas introduced in that version. - The
default matchfallback is optional but recommended—it prevents empty values if a placeholder is missing fromvalues.yaml, making debugging easier.
内容的提问来源于stack exchange,提问作者Amit Baranes
相关产品推荐
相关产品推荐

