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

如何使用Helm创建带有不同标签的独立ConfigMap?

使用Helm创建带独立标签的多个ConfigMap

问题说明

需要通过Helm生成6个带有独立标签的ConfigMap,每个ConfigMap拥有独立的配置,且标签需与Pod使用的一致。当前提供的values.yaml配置如下:

# values.yaml
configmaptestingforhelm:
  configmapref1:
        confname: serviceaccount-config
        key: serviceaccount.test.path
        value: /root/test_key.json
  configmapref2:
        confname: host-credentials-config
        key: secret.credentials.host.path
        value: /root/host_key.json

用户尝试为每个configmapref*单独编写模板,但未能生成期望的独立ConfigMap资源,期望输出示例:

apiVersion: v1
data:
  secret.credentials.host.path: /root/host_key.json
kind: ConfigMap
metadata:
  name: host-credentials-config

apiVersion: v1
data:
  serviceaccount.test.path: /root/test_key.json
kind: ConfigMap
metadata:
  name: serviceaccount-config

解决方案

方案一:优化Values结构(推荐)

先调整values.yaml的结构,让多个ConfigMap的配置更规整,便于批量渲染:

# values.yaml
configMaps:
  - name: serviceaccount-config
    labels:
      app: my-app
      component: auth
    data:
      serviceaccount.test.path: /root/test_key.json
  - name: host-credentials-config
    labels:
      app: my-app
      component: storage
    data:
      secret.credentials.host.path: /root/host_key.json
  # 继续添加剩余4个ConfigMap的配置,结构同上

在templates目录下创建configmaps.yaml模板文件,通过range循环批量生成资源:

# templates/configmaps.yaml
{{- range $cm := .Values.configMaps }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ $cm.name }}
  labels:
    {{- toYaml $cm.labels | nindent 4 }}
data:
  {{- toYaml $cm.data | nindent 2 }}
---
{{- end }}
  • range遍历所有ConfigMap配置,逐个生成独立资源
  • toYaml将嵌套的labels和data对象转为标准YAML格式,nindent保证缩进符合K8s要求
  • ---用于分隔多个K8s资源,确保每个ConfigMap独立

方案二:适配原Values结构

若不想修改原values.yaml结构,可调整模板并补充标签配置:

首先在原values.yaml中为每个configmapref*添加标签字段:

# values.yaml
configmaptestingforhelm:
  configmapref1:
        confname: serviceaccount-config
        key: serviceaccount.test.path
        value: /root/test_key.json
        labels:
          app: my-app
          role: service-account
  configmapref2:
        confname: host-credentials-config
        key: secret.credentials.host.path
        value: /root/host_key.json
        labels:
          app: my-app
          role: host-credentials

然后编写模板文件templates/configmaps.yaml:

# templates/configmaps.yaml
{{- range $key, $value := .Values.configmaptestingforhelm }}
apiVersion: v1
kind: ConfigMap
metadata:
  name: {{ $value.confname }}
  labels:
    {{- toYaml $value.labels | nindent 4 }}
data:
  {{ $value.key }}: {{ $value.value }}
---
{{- end }}

验证

执行helm template .命令,即可生成带有指定标签和数据的独立ConfigMap资源,与期望输出一致。

内容的提问来源于stack exchange,提问作者hemanth krishna

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 16:54:17