bashbase64yamlyq

How to use `yq` to set a property to a multi-line string?


I have a certificate file that looks similar to:

-------BEGIN CERTIFICATE-------
asdoqijepoqjwe1i49i120941p2j4omslasdajsdqweqwe
qwelqjwkasdlajsölkjasldkjakljsdlkjasdasdpiqwe
-------END CERTIFICATE--------

I also have a YAML file (an OpenShift Template) that looks like this:

apiVersion: v1
kind: Template
objects:
- apiVersion: v1
  kind: Route
  tls:
    certificate:
    key:
  someOther: stuff

How can I use yq to set the value of the property certificate in the YAML file above, to the contents of the certificate file so that the output looks somewhat like this:

apiVersion: v1
...
    certificate: |
      -------BEGIN CERTIFICATE-------
      asdoqijepoqjwe1i49i120941p2j4omslasdajsdqweqwe
      qwelqjwkasdlajsölkjasldkjakljsdlkjasdasdpiqwe
      -------END CERTIFICATE--------

Neither an Internet search nor documentation was of any help. The closest I got was using the following:

yq w /tmp/template.yaml objects[0].tls.certificate "\n$(cat cert.pem)"

...which left me with the following output:

certificate: !!binary |
      fC0KLS0tLS0tLUJFR0lOIENFUlRJRklDQVRFLS0tLS0tLQphc2RvcWlqZXBvcWp3ZTFpND
      lpMTIwOTQxcDJqNG9tc2zDYXNkYWpzZMNxd2Vxd2UKcXdlbHFqd2vDYXNkbGFqc8O2bGtq
      YXNsZGtqYWtsanNkbGtqYXNkYXNkcGlxd2UKLS0tLS0tLUVORCBDRVJUSUZJQ0FURS0tLS
      0tLS0t

...which strangely is the base64 encoded variant of what I wanted to add preceded by !!binary |. Any ideas what's going on and how I can achieve desired output instead?


Solution

  • I have tested @Inian suggestion with yq3 and it works.

    It can also be achieve in yq4 with the following syntax:

    template.yml

    # template.yml
    apiVersion: v1
    kind: Template
    objects:
      - apiVersion: v1
        kind: Route
        tls:
          certificate:
          key:
        someOther: stuff
    

    cert.pem

    -------BEGIN CERTIFICATE-------
    asdoqijepoqjwe1i49i120941p2j4omslasdajsdqweqwe
    qwelqjwkasdlajsölkjasldkjakljsdlkjasdasdpiqwe
    -------END CERTIFICATE--------
    

    command

    yq eval '.objects[0].tls.certificate = "'"$(< cert.pem)"'"' template.yml
    

    output

    apiVersion: v1
    kind: Template
    objects:
      - apiVersion: v1
        kind: Route
        tls:
          certificate: |-
            -------BEGIN CERTIFICATE-------
            asdoqijepoqjwe1i49i120941p2j4omslasdajsdqweqwe
            qwelqjwkasdlajsölkjasldkjakljsdlkjasdasdpiqwe
            -------END CERTIFICATE--------
          key:
        someOther: stuff