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.<
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 Passing Variables On The Command Line.
from the link: --extra-vars "@some_file.json"
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.
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.
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!