ansible

Ansible - Reading configuration into a variable


I have some configuration which can be formatted as required that I want to load into ansible in a way that I can then use.

As an example I have

[hosttype1]
values
values2
[hosttype2]
values3
values4

I have also tried with format of

hosttype1:
  - value1
  - value2
hosttype2:
  - value3
  - value4

I have save that config to a file and have managed to store the first entry into a variable

- hosts: localhost
vars_files:
- config.yml
- debug: 
  var_list: "{{ hosttype1 }}"

I have wrapped the values in quotes ', and double quates " and no quotes but always get an error

ERROR! Invalid vars_files entry found: {u'debug': None, u'var_list': [u'value1', u'value2']} var_files entries should be either a string type or a list of string types after template expansion

So what I want is in the first place is for the hosttype1 to not be the name of the variable, so the final code can be much more generic. I'd like to be able to define something higher in the chain so that the hosttypes are components of a variable.

But also the error message suggests to values are not strings, but they are clearly wrapped in quotes, so I have absolutely no idea what the error actually means.

Is anyone able to assist me and give me an idea of what I am doing wrong, or point me at some documentation that describes how?


Solution

  • The playbook you've posted in your question has some significant indentation problems that would render it invalid. Assuming you have a file config.yml that contains:

    hosttype1:
      - value1
      - value2
    hosttype2:
      - value3
      - value4
    

    You can read that into Ansible like this:

    - hosts: localhost
      vars_files:
        - config.yml
    
      tasks:
        - debug:
            msg:
              - "type 1: {{hosttype1}}"
              - "type 2: {{hosttype2}}"
    

    This playbook would produce as output:

    TASK [debug] ******************************************************************************************************************************************************************************************************
    ok: [localhost] => {
        "msg": [
            "type 1: ['value1', 'value2']",
            "type 2: ['value3', 'value4']"
        ]
    }