Pass array in --extra-vars - Ansible

这一生的挚爱 提交于 2019-11-30 02:40:37

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.

Ivan Ogai

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.

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!

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!