Pass array in --extra-vars - Ansible

前端 未结 4 1570
遇见更好的自我
遇见更好的自我 2020-12-25 10:02

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.<

相关标签:
4条回答
  • 2020-12-25 10:17

    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"

    0 讨论(0)
  • 2020-12-25 10:24

    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.

    0 讨论(0)
  • 2020-12-25 10:25

    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.

    0 讨论(0)
  • 2020-12-25 10:33

    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!

    0 讨论(0)
提交回复
热议问题