Published on

YAML Variables and Interpreting Text as a Block Quote

Authors

YAML Variables (aka aliases) using & and *

For the last few days I have been working a fortune with YAML as I have spent most of my time configuring various applications. One thing I have found is that you define a YAML variable and then copy past it again late exactly as it was. To reuse a block you define the name of that block with an ampersand & e.g.:

- person: &john
    name: John
    surname: Smith
    age: 22

Then later on you can reference this variable using * and the variable/alias name:

Students:
- person:
    <<: *john
- person:
    name:    Jane
    surname: Doe
    age:     20

This expands to:

Students:
  - person:
      name: John
      surname: Smith
      age: 22
  - person:
      name: Jane
      surname: Doe
      age: 20

More examples of this can be found here.

Text as a Block Quote (aka literal scalar) using |

Another very useful thing is being able to specify a literal or as it is referred to in the YAML spec a literal scalar using the pipe | symbol. What this means is that you can specify a block of text that will be interpreted as is similar to a block quote in HTML. This is especially useful when defining a config map in Kubernetes where you have a particularly large config that you do not want to get jarbled the way kubernetes does for smaller configs. You would use it similar to the below:

apiVersion: v1
kind: ConfigMap
metadata:
  name: person-config
  namespace: person-namespace
data:
  person.properties: |
    name=John
    surname=Smith
    age=21

This can then be used in your Kubernetes container environment variable as described here. Or mounted as a volume and used in your container as a file as described here where the file name will match the name of the file as defined just after data so in the above this would be person.properties.