redhat-cop/resource-locker-operator

Can patchTemplate output partial value of a field contains YAML text

morningspace opened this issue · 2 comments

What I'm trying is to grab text from a ConfigMap to fill the patchTemplate. For example:

apiVersion: v1
kind: ConfigMap
metadata:
  name: test-cm
data:
  settings: |
    kong:
      replicaCount: 1

I'd like to fill the patchTemplate by retrieving text started from data.settings.kong. Something similar as below (of course it wouldn't work):

apiVersion: redhatcop.redhat.io/v1alpha1
kind: ResourceLocker
metadata:
  name: test-patch
  namespace: resource-locker-operator
spec:
  patches:
  - targetObjectRef:
      apiVersion: charts.helm.k8s.io/v1alpha1
      kind: Kong
      name: gateway
    patchTemplate: |
      {{ (index . 0).data.settings | yq ".kong" }}
    patchType: application/merge-patch+json
    sourceObjectRefs:
    - apiVersion: v1
      kind: ConfigMap
      name: test-cm
    id: kong-patch

Not sure if that's a common case, but wondering if there's any suggestion on this.

Thanks @raffaelespazzoli for your quick response!

It sounds great, but I did a quick try and was not able to make it work in some cases. What I tried is that using below ConfigMap:

apiVersion: v1
data:
  settings: |
    kong:
      foo:
        bar: "baz"
      replicaCount: 2
kind: ConfigMap
metadata:
  name: test-cm

And, the ResourceLocker:

apiVersion: redhatcop.redhat.io/v1alpha1
kind: ResourceLocker
metadata:
  name: test-patch
  namespace: resource-locker-operator
spec:
  patches:
  - targetObjectRef:
      apiVersion: charts.helm.k8s.io/v1alpha1
      kind: Kong
      name: gateway
    patchTemplate: |
      spec:
        {{ ((index . 0).data.settings | fromYaml).kong | toYaml }}
    patchType: application/merge-patch+json
    sourceObjectRefs:
    - apiVersion: v1
      kind: ConfigMap
      name: test-cm
    id: kong-patch

The output of Kong is:

apiVersion: charts.helm.k8s.io/v1alpha1
kind: Kong
metadata:
  name: gateway
  namespace: default
replicaCount: 2
spec:
  bar: baz
  ...
status:
  ...

It appears the spec field is missing when it patches to the target resource. If I use the below ConfigMap:

apiVersion: v1
data:
  settings: |
    kong:
      spec:
        foo:
          bar: "baz"
        replicaCount: 2
kind: ConfigMap
metadata:
  name: test-cm

And, the patchTemplate as below:

    patchTemplate: |
        {{ ((index . 0).data.settings | fromYaml).kong | toYaml }}

That will work:

apiVersion: charts.helm.k8s.io/v1alpha1
kind: Kong
metadata:
  name: gateway
  namespace: default
spec:
  foo:
    bar: baz
  replicaCount: 2
  ...
status:
  ...