Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variable reuse in YAML, variable within variable

Tags:

yaml

I'm looking for a way to reuse variables defined in my list on YAML, I have a YAML list with the following sample entries :

workstreams:
  - name: tigers
    service_workstream: tigers-svc
    virtual_user:
      - {name: inbound-tigers, pass: '123', access: inbound, env: app1}
      - {name: outbound-tigers, pass: '123', access: outbound, env: app1}
    email: [email protected]
    mount_dir: /mnt/tigers
    app_config_dir: /opt/tigers

Using the example from above I want to reuse a defined value, like tigers. The ideal solution would be something like this :

workstreams:
  - name: tigers
    service_workstream: "{{ vars['name'] }}-svc"
    virtual_user:
      - {name: "inbound-{{ vars['name'] }}", pass: '123', access: inbound, env: app1}
      - {name: "outbound-{{ vars['name'] }}", pass: '123', access: outbound, env: app1}
    email: "{{ vars['name'] }}@my-fqdn.com"
    mount_dir: "/mnt/{{ vars['name'] }}"
    app_config_dir: "/opt/{{ vars['name'] }}"

Any points as to how I can do this in YAML ?

like image 547
fmaree Avatar asked Jul 31 '17 13:07

fmaree


Video Answer


1 Answers

You can do:

workstreams:
  - name: &name tigers          # the scalar "tigers" with an anchor &name
    service_workstream: *name   # alias, references the anchored scalar above

However, you can not do string concatenation or anything like it in YAML 1.2. It cannot do any transformations on the input data. An alias is really a reference to the node that holds the corresponding anchor, it is not a variable.

Quite some YAML-using software provides non-YAML solutions to that problem, for example, preprocessing the YAML file with Jinja or whatnot. Depending on context, that may or may not be a viable solution for you.

like image 161
flyx Avatar answered Oct 19 '22 01:10

flyx