Search code examples
variablesansibleformatyaml

Use dotted YAML variables file in Ansible


I'm trying to achieve the following using Ansible:

Define a YAML file with some variables in the dotted format inside it (variables.yml)

database.hosts[0]: "db0"
database.hosts[1]: "db1"
database.hosts[2]: "db2"

foo.bar: 1
foo.baz: 2

Load the variables in variables.yml by using the include_vars module in my playbook (playbook.yml) and print them in a tree structure

- hosts: all
  gather_facts: not
  tasks:
    - name: "Loading vars"
      run_once: true
      include_vars:
        file: 'variables.yml'

    - name: "Testing"
      debug:
        msg: "{{ foo }}"

    - name: "Testing"
      debug:
        msg: "{{ database }}"

Running this results in the following error:

fatal: [host0]: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'foo' is undefined\n\nThe error appears to be in '.../playbook.yml': line 9, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n    - name: \"Testing\"\n      ^ here\n"}

Which makes it clear that each property in the YAML file has been loaded as a separate property and not as properties within two trees rooted in database and foo.

Of course, the playbook works as expected if I specify the properties as follows:

database:
  hosts:
    - "db0"
    - "db1"
    - "db2"        

foo:
  bar: 1
  baz: 2

However, I need the YAML variables file to be in the dotted format instead of in the classic indented format. Is there any way to achieve this? E.g.: a module different from include_vars or some configuration that I can add to the ansible.cfg file? I have already tried to use hash_behaviour=merge, but that didn't help.


Solution

  • Q: "I need the YAML variables file to be in the dotted format instead of in the classic indented format. Is there any way to achieve this?"

    A: No. It's' not possible. See Creating valid variable names.