Pass array in --extra-vars - Ansible

Tariq picture Tariq · Sep 2, 2014 · Viewed 79.4k times · Source

How can I pass yaml array to --extra-vars in Ansible playbook. Ansible documentation does not declares its syntax nor I can find that on any internet resource.

I mean if I have a playbook:

---
  - hosts: {{hostName}}
  - remote_user: admin
  ...

Then I should call my playbook like

ansible-playbook DeployWar.yml --extra-vars="hostName=tomcat-webApp"

But I want to run this playbook on two servers say tomcat-webApp and tomcat-all, and I want to control it from out side i.e. using --extra-vars. What I have tried to do is:

ansible-playbook DeployWar.yml --extra-vars="hostName=[tomcat-webApp, tomcat-all]"

ansible-playbook DeployWar.yml --extra-vars="hostName={tomcat-webApp, tomcat-all}"

ansible-playbook DeployWar.yml --extra-vars="[{hostName: tomcat-webApp}, {hostName: tomcat-all}]"

But in all cases playbook fails declaring a syntax error in my call. Any help appreciated.

Answer

jarv picture jarv · Sep 2, 2014

To answer your first question "How can I pass yaml array to --extra-vars in Ansible playbook." you can pass in a json formatted string to extra-vars.

Here is an example play:

- hosts: all
  gather_facts: no
  tasks:
    - debug: var=test_list

And how to pass in test_list to ansible-playbook:

ansible-playbook -c local -i localhost, test.yml --extra-vars='{"test_list": [1,2,3]}'

Though you can use a variable for hosts I recommend checking out Ansible's mechanism for host management which is inventory in conjunction with the --limit option.