根据范围查找舵值

lookup helm value based on range

我正在创建一个包含多个容器的 helm chart。

我的值文件如下所示:

# environment variables
rabbitmqhost : "rabbitmq"
db-host : "mongo"
db-username : "root"
db-password : "root"


deployments: 
  - name: "service1"
    image: "Some-repo"
    pullPolicy: IfNotPresent
    tag: "latest"
    env: 
      rabbitmqhost 


  - name: "api"
    image: "Some-repo"
    pullPolicy: IfNotPresent
    tag: "latest"
    env: 
      rabbitmqhost 
      db-host 
      db-username 
      db-password 


我的 deployment.yaml 看起来像这样:

{{ range $.Values.deployments}}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ .name }}
  labels:
    app: {{ .name }}

spec:
  replicas: 1
  selector:
    matchLabels:
      app: {{ .name }}
  template:
     spec:
        containers:
        - name: {{.name}}
          image: "{{ .image }}:{{ .tag }}"
          imagePullPolicy: Always
          env: {{ range $key, $val := .env}}
            - name: "{{ $key }}"
              value: "{{ $.Values.$key }}"
            {{- end}}

{{- end}}

我发现这行不通,我作为 value: "{{ $.Values.$key }}" 不评估。 有没有办法动态评估 $key ? 或者我需要以不同的方式构建它来实现它吗?

我通过扩展逻辑以使用“if has”解决了这个问题

在我的值文件中,我定义了这样的环境变量:

# environment variables
env:
  rabbitmqhost : "rabbitmq"
  db-host : "mongo"
  db-username : "root"
  db-password : "root"

deployments: 
  - name: "service1"
    image: "Some-repo"
    pullPolicy: IfNotPresent
    tag: "latest"
    env: 
      - rabbitmqhost 


  - name: "api"
    image: "Some-repo"
    pullPolicy: IfNotPresent
    tag: "latest"
    env: 
      - rabbitmqhost 
      - db-host 
      - db-username 
      - db-password 

在部署模板中,我将其更改为:

{{ range $deployment := $.Values.deployments}}
apiVersion: apps/v1
kind: Deployment
metadata:
  name: {{ $deployment.name }}
  labels:
    app: {{ $deployment.name }}

spec:
  replicas: 1
  selector:
    matchLabels:
      app: {{ $deployment.name }}
  template:
     spec:
        containers:
        - name: {{$deployment.name}}
          image: "{{ $deployment.image }}:{{ $deployment.tag }}"
          imagePullPolicy: Always
          env: {{ range $key, $val := $.Values.env}}
            {{ if has $key  $deployment.env }}
            - name: "{{ $key }}"
              value: "{{ $val }}"
            {{- end}}

          {{- end}}

{{- end}}

$map.key 语法仅在 key 是已知的固定字符串时才有效,但您可以使用带有变量字符串

的标准模板 index 函数
value: "{{ index $.Values $key }}"