Access elements of a list in a yaml

7/28/2021

I need to access and store a pod properties in kubernetes during creation. I can access to regular variables in the yaml without problem but i don't know (and could not find online) the syntax to access elements of a list.

apiVersion: "agones.dev/v1"
kind: GameServer
metadata:
  # generate a unique name
  # will need to be created with `kubectl create`
  generateName: ed- 
spec:
  ports:
    - name: game
      portPolicy: Dynamic
      containerPort: 7777
      protocol: UDP 
  template:
    spec:
      containers:
      - name: ed-server
        image: myimage
        imagePullPolicy: Always # add for development
        command: ["sh", "-c"]
        args:
          - echo MY_ID=$(MY_ID)\nMY_IP=$(MY_IP)\nMY_PROTOCOL=$(MY_PROTOCOL)\n";
        env:
          - name: MY_ID # THIS WORKS FINE
            valueFrom:
              fieldRef:
                fieldPath: metadata.name
          - name: MY_IP # THIS WORKS FINE
            valueFrom:
              fieldRef:
                fieldPath: status.podIP
          #- name: MY_PROTOCOL # THIS FAILS
          #  valueFrom:
          #    fieldRef:
          #      fieldPath: spec.ports[0].protocol

I will like to know the correct syntax and get some proper documentation source on the topic.

EDIT: I've put the actual yaml i'm using after requested. I'm using agones framwork but the question is generic. If the parser knows how to access a literal and a dictionary it should be able to access an array.

Thanks!

-- Demiurge
kubernetes
yaml

1 Answer

7/28/2021

First of all, your YAML isn't a valid one. Seems like you've Frankensteined both Deployment and Pod YAMLs.

Your YAML should look like below:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: foo 
spec:
  replicas: 1
  selector:
    matchLabels:
      app: foo
  template:
    metadata:
      labels:
        app: foo
    spec:
      containers:
      - name: foo
        image: dummy_image:0.0.1
        ports:
        - name: game
          portPolicy: Dynamic
          containerPort: 7777
          protocol: UDP

Answer:

Unfortunately, the ports field is not supported by the fieldRef. Check Downward API for the supported field list.

Since the port information doesn't change dynamically on the pod runtime, you can export it like this:

    env:
    - name: MY_PORT
      value: "game"
-- Kamol Hasan
Source: StackOverflow