Order in Array of K8s entity

5/31/2020

I have CRD (Custom Resource Definition) with a field with a type "array". I wonder if in this array the order is preserved , mens , if i apply yaml with:

myField:
- a
- b
- c

And after that I get the entity using kubectl, it is promised to me that I get the order I mentions before and nor

myField:
- b
- a
- c
-- Matan Wiesner
kubernetes
yaml

2 Answers

6/1/2020

Yes, YAML sequences are ordered and preserve order across parsing and serialization. From YAML 1.2 §3.2.1.1 (emphasis in original):

The content of a sequence node is an ordered series of zero or more nodes.

This is contrast to mapping nodes, which are unordered.

<!-- language: lang-yaml -->
guaranteedToPreserveOrder: # a sequence of mappings with name: keys
  - name: a
    value: one
  - name: b
    value: two
notGuaranteedToPreserveOrder: # a simple mapping
  a: one
  b: two
-- David Maze
Source: StackOverflow

6/1/2020

I don't ask about yaml format, I ask about k8s: if k8s save order in its internal storage and cannot change the order

lists/arrays in yaml manifests are like lists in Python which basically are collections of ordered and changeable (mutable) elements. And yes, kubernetes also stores them following this rule.

You can easily check it by performing a simple test. It's not a working example of nginx server as all ports are fictitious, but it illustrates pretty well the idea:

apiVersion: apps/v1
kind: Deployment
metadata:
  name: nginx-deployment
  labels:
    app: nginx
spec:
  replicas: 3
  selector:
    matchLabels:
      app: nginx
  template:
    metadata:
      labels:
        app: nginx
    spec:
      containers:
      - name: nginx
        image: nginx:1.14.2
        ports:
        - containerPort: 5
        - containerPort: 4
        - containerPort: 3
        - containerPort: 2
        - containerPort: 1

Once you deploy it on your k8s cluster by running kubectl apply -f nginx.yaml you can retrieve it by making a call to kube-api server e.g. by using:

kubectl get deployment nginx-deployment -o yaml

which gives you the following output:

...
        ports:
        - containerPort: 5
          protocol: TCP
        - containerPort: 4
          protocol: TCP
        - containerPort: 3
          protocol: TCP
        - containerPort: 2
          protocol: TCP
        - containerPort: 1
...

As you can see all elements of our list are stored in the same order as they were listed in our yaml manifest. You can try to put those elements in completely different order and you'll see that kubernetes won't sort them in any way. The order of the elements of the list will always be kept.

-- mario
Source: StackOverflow