有没有什么方法可以在 K8s 中使用 configMaps 并将嵌套值用作 pod 中的环境变量?

Is there any way to use configMaps in K8s with nested values to be used as environment variable in the pod?

我有 configMap 的示例 cm.yml,其中嵌套 json 数据。

kind: ConfigMap
metadata:
 name: sample-cm
data:
 spring: |-
  rabbitmq: |-
   host: "sample.com"
  datasource: |-
   url: "jdbc:postgresql:sampleDb"

我要设置环境变量,下面的spring-rabbitmq-host=sample.com和spring-datasource-url=jdbc:postgresql:sampleDb豆荚。

kind: Pod
metadata:
 name: pod-sample
spec:
 containers:
  - name: test-container
    image: gcr.io/google_containers/busybox
    command: [ "/bin/sh", "-c", "env" ]
    env:
     - name: sping-rabbitmq-host
       valueFrom:
        configMapKeyRef:
         name: sample-cm    
         key: <what should i specify here?>
     - name: spring-datasource-url
       valueFrom:
        configMapKeyRef:
         name: sample-cm
         key: <what should i specify here?>

遗憾的是,无法将您创建的配置映射中的值作为单独的环境变量传递,因为它是作为单个字符串读取的。

您可以使用kubectl describe cm sample-cm

查看
Name:         sample-cm
Namespace:    default
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"v1","data":{"spring":"rabbitmq: |-\n host: \"sample.com\"\ndatasource: |-\n url: \"jdbc:postgresql:sampleDb\""},"kind":"Con...

Data
====
spring:
----
rabbitmq: |-
 host: "sample.com"
datasource: |-
 url: "jdbc:postgresql:sampleDb"
Events:  <none>

ConfigMap 需要键值对,因此您必须修改它以表示单独的值。

最简单的方法是:

apiVersion: v1
kind: ConfigMap
metadata:
 name: sample-cm
data:
   host: "sample.com"
   url: "jdbc:postgresql:sampleDb"

因此值将如下所示:

kubectl describe cm sample-cm
Name:         sample-cm
Namespace:    default
Labels:       <none>
Annotations:  kubectl.kubernetes.io/last-applied-configuration:
                {"apiVersion":"v1","data":{"host":"sample.com","url":"jdbc:postgresql:sampleDb"},"kind":"ConfigMap","metadata":{"annotations":{},"name":"s...

Data
====
host:
----
sample.com
url:
----
jdbc:postgresql:sampleDb
Events:  <none>

并将其传递给 pod:

apiVersion: v1
kind: Pod
metadata:
 name: pod
spec:
 containers:
  - name: test-container
    image: gcr.io/google_containers/busybox
    command: [ "/bin/sh", "-c", "env" ]
    env:
    - name: sping-rabbitmq-host
      valueFrom:
        configMapKeyRef:
          name: sample-cm
          key: host
    - name: spring-datasource-url
      valueFrom:
        configMapKeyRef:
          name: sample-cm
          key: url