You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过单个正则表达式自动替换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:

  1. Load dependencies: First, we grab the raw content of your config.json file and store the placeholder mappings from values.yaml in a reusable variable for easier reference.
  2. Define replacement logic: The $replaceFunc takes each matched placeholder (like %PLACEHOLDER_1%), strips the surrounding % to extract the key name, then fetches the corresponding value from values.placeholders. If a placeholder isn't defined in values.yaml, it keeps the original placeholder (thanks to default match) to avoid breaking your JSON structure.
  3. Batch replace: regexReplaceAllFunc uses 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 regexReplaceAllFunc was introduced in that version.
  • The default match fallback is optional but recommended—it prevents empty values if a placeholder is missing from values.yaml, making debugging easier.

内容的提问来源于stack exchange,提问作者Amit Baranes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.29 09:47:29