Pass array in --extra-vars - Ansible
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.
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.
As of Ansible 1.3, extra vars can be formatted as YAML, either on the command line or in a file. See the Ansible documentation titled Defining Variables At Runtime.
Example:
--extra-vars "@some_file.yaml"
Perhaps, don't try to pass complex types via command line and handle their creation within the playbook from json files or strings.
So, @NelonG's approach works but how will it work in all execution contexts? My playbooks tend to get executed by Jenkins jobs via ansiblePlaybook and via packer. Getting the following to work in all of those (even when the command line looks right) doesn't work and can lead to an escaping nightmare.
ansible -i localhost, all -m debug -a "var=test_list" \
--extra-vars='{"test_list": [1,2,3]}'
How about passing in as a string and then splitting via set_fact (note: this only works if you have elements without problematic characters. I have URLs so they are reasonably safe
ansible .... -e "test_list_csv=1,2,3,http://foo.bar/file.txt"
In the playbook
name: generate list from string
set_fact:
test_list: "{{ test_list_csv.split(',') | list }}"
I decided to escape from escaping and it seems to work.
In addition to answer from jarv, here is my savior note:
In case someone wants to pass in an array of integers, this works:
--extra-vars '{"my_params":[40,50,10,20,30]}'
Note: there should be no space in between the numbers in the array you pass! Removing space solved my problem!