Ansible, how to define a list in host inventory?

2019-09-11 19:08发布

I have a playbook and I want to define a list of strings in my hosts file.

Here's my host file:

[dashboard]
1.2.3.4 dashboard_domain=test site_domain=['one','two','foo', 'bar'] 

Here's my playbook that I attempted to write using the list documentation:

---
- hosts: dashboard
  gather_facts: False
  remote_user: ubuntu
  become: yes

  tasks:

    - name: ping
      ping:

    - debug: 
        msg: "Domain: {{dashboard_domain}}"

    - debug: 
        msg: "Site: {{ item }}"
      with_items: "{{site_domain}}"

However running this playbook with ansible-playbook -i hosts ping.yml causes this error:

TASK: [debug ] ****************************************************************
fatal: [1.2.3.4] => with_items expects a list or a set

This seems to be an issue of transferring the defined list from the host file to the playbook because defining the list directly in the playbook works:

---
- hosts: dashboard
  gather_facts: False
  remote_user: ubuntu
  become: yes
  vars:
    site_domain: ['one','two','foo', 'bar'] 
  tasks:

    #### APPLY HTTP-AUTH ####
    - name: ping
      ping:

    - debug: 
        msg: "Domain: {{dashboard_domain}}"

    - debug: 
        msg: "Site: {{ item }}"
      with_items: "{{site_domain}}"

1条回答
forever°为你锁心
2楼-- · 2019-09-11 20:03

Just quote the variable value:

[dashboard]
1.2.3.4 dashboard_domain=test site_domain="['one','two','foo', 'bar']"

It seems in case of INI-formatted inventory files, Ansible does not parse the variable value if it starts with an unquoted [ and passes it as a string.


Regarding your example: I'm not sure why you're not getting an expected key=value error on reading the inventory file, if you really have a space inside.

查看更多
登录 后发表回答