Ronu
Ronu

Reputation: 553

How to reference values in yaml file?

I have written a YAML file as follows:

private_ips:
    - 192.168.1.1
    - 192.168.1.2
    - 192.168.1.3
    - 192.168.1.4

testcases:
    - name: test_outbound
      ip: << I want to use reference to  private_ips[0] = '192.168.1.1'

How can I use references in a YAML file?

Upvotes: 8

Views: 8387

Answers (1)

Anthon
Anthon

Reputation: 76578

You can use something like:

ip: !Ref private_ips.0

in YAML. But that would require that the program that loads the YAML implements a special type for the tag !Ref that interprets its node in a way relativ to the current data structure. This is somewhat problematic in most YAML loaders as they do a depth first traversal and there is no notion when building the !Ref tagged node of the root of the tree YAML document. That could be solved by a second pass after the datastructure is loaded. There is no "shortcut" in the YAML specification to do this kind of traversal of the document to get a value without the loading program doing something special (i.e. not specified in the YAML specification).

What is in YAML specification is the concept of anchors (indicated by &) and aliases (indicated by *), depending on how you want to use this, that might solve your problem, e.g. if you want to experiment with what IP address should be used for testing:

private_ips:
    - &test 192.168.1.1
    - 192.168.1.2
    - 192.168.1.3
    - 192.168.1.4

testcases:
    - name: test_outbound
      ip: *test

This should load in any YAML loader conforming to the spec, as if the last line was written as:

      ip: 192.168.1.1

Without your program doing any extra processing.

Upvotes: 10

Related Questions