Kubernetes|Helm values.yaml - How to access array using dynamic index

11/20/2018

I have a values.yaml where I need to mention multiple ports like the following:

kafkaClientPort:
  - 32000
  - 32001
  - 32002

In yaml for statefulset, I need to get value using ordinal number. So for kf-0, I need to put first element of kafkaClientPort; and for kf-1, second element and so on. I am trying like the following:

args:
- "KAFKA_ADVERTISED_LISTENERS=PLAINTEXT://$(MY_NODE_NAME):{{ index .Values.kafkaClientPort ${HOSTNAME##*-} }}"

But it is showing an error.

Please advise what is the best way to access dynamically values.yaml value.

-- Soumen Ghosh
kubernetes
kubernetes-helm
yaml

1 Answer

11/20/2018

The trick here is that Helm template doesn't know anything about ordinal in your stateful set. If you look at the Kafka Helm Chart, you see that they are using a base port 31090 and then they add the ordinal number but that substitution is in place 'after' the template is created. Something like this in your values:

"advertised.listener": |-
   PLAINTEXT://kafka.cluster.local:$((31090 + ${KAFKA_BROKER_ID}))

and then in the template file, the use a bash export under command with a printf which is an alias for fmt.Sprintf. Something like this in your case:

    command:
    - sh
    - -exc
    - |
      unset KAFKA_PORT && \
      export KAFKA_BROKER_ID=${HOSTNAME##*-} && \
      export "KAFKA_ADVERTISED_LISTENERS={{ printf "%s" $advertised.listener }} \\
      ...
-- Rico
Source: StackOverflow