Home > Software design >  Add object to an array in yaml via Kustomize
Add object to an array in yaml via Kustomize

Time:10-24

how can I add object to array via Kustomize? As a result I would like to have two ServiceAccounts added to subjects, like so:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: binding
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:auth-delegator
subjects:
  - kind: ServiceAccount
    name: name
    namespace: test1
  - kind: ServiceAccount
    name: name
    namespace: test2

I'm trying with that patch:

- op: add
  path: "/subjects/0"
  value:
    kind: ServiceAccount
    name: name
    namespace: test1

And another patch for second environment:

- op: add
  path: "/subjects/1"
  value:
    kind: ServiceAccount
    name: name
    namespace: test2

But in result I'm getting duplicated subjects, so of course it is wrong:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: binding
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:auth-delegator
subjects:
  - kind: ServiceAccount
    name: name
    namespace: test1 // the same...
  - kind: ServiceAccount
    name: name
    namespace: test1 // ...as here

What would be a proper way to add it?

CodePudding user response:

If I start with a ClusterRoleBinding that looks like this in crb.yaml:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: binding
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:auth-delegator
subjects: []

And I create a kustomization.yaml file like this:

apiVersion: kustomize.config.k8s.io/v1beta1
kind: Kustomization

resources:
  - crb.yaml

patches:
  - target:
      kind: ClusterRoleBinding
      name: binding
    patch: |
      - op: add
        path: /subjects/0
        value:
          kind: ServiceAccount
          name: name
          namespace: test1

  - target:
      kind: ClusterRoleBinding
      name: binding
    patch: |
      - op: add
        path: /subjects/1
        value:
          kind: ServiceAccount
          name: name
          namespace: test2

Then I get as output:

apiVersion: rbac.authorization.k8s.io/v1
kind: ClusterRoleBinding
metadata:
  name: binding
roleRef:
  apiGroup: rbac.authorization.k8s.io
  kind: ClusterRole
  name: system:auth-delegator
subjects:
- kind: ServiceAccount
  name: name
  namespace: test1
- kind: ServiceAccount
  name: name
  namespace: test2

Which is I think what you're looking for. Does this help? Note that instead of explicitly setting an index in the path, like:

path: /subjects/0

We can instead specify:

path: /subjects/-

Which means "append to the list", and in this case will generate the same output.

  • Related