如何通过--extra-vars将额外变量作为字典列表传递给ansible到ansible playbook?

fly*_*ish 2 ansible

我想通过 --extra-vars 将变量传递给我的 ansible playbook,变量的类型是这样的 dict 列表:

  list1:
    - { key1: "val1", key2: "val2" }
    - { key1: "val3", key2: "val4" }
Run Code Online (Sandbox Code Playgroud)

我的剧本是:

---
- name: main file
  gather_facts: false
  hosts: localhost
  vars:
    list1: "{{ lists }}"

  tasks:
  - name: echo item
    shell: echo {{ item.key1 }}
    with_items: list1
Run Code Online (Sandbox Code Playgroud)

我尝试传递这样的变量:

ansible-playbook build_and_cppcheck.yml -e "lists=[{ "key1": "val1", "key2":"val2" },{ "key1": "val3", "key2":"val4" }]"
Run Code Online (Sandbox Code Playgroud)
但它不起作用:

fatal: [localhost] => with_items expects a list or a set
Run Code Online (Sandbox Code Playgroud)
有什么建议吗?

3sk*_*sky 5

只需使用 JSON 字符串语法:Ansible doc。例如:

$ play.yml

---
- hosts: localhost
  gather_facts: no
  tasks:
    - debug:
        msg: "This is {{ test[0] }}"

    - debug:
        msg: "This is {{ test[1] }}"
Run Code Online (Sandbox Code Playgroud)

$ ansible-playbook play.yml -e '{"test":["1.23.45", "12.12.12"]}'

[3sky@t410 testing]$ ansible-playbook play.yml -e '{"test":["1.23.45", "12.12.12"]}'
 [WARNING]: provided hosts list is empty, only localhost is available. Note that the implicit localhost does not match 'all'


PLAY [localhost] ********************************************************************************

TASK [debug] ********************************************************************************
ok: [localhost] => {
    "msg": "This is 1.23.45"
}

TASK [debug] ********************************************************************************
ok: [localhost] => {
    "msg": "This is 12.12.12"
}

PLAY RECAP ********************************************************************************
localhost     
Run Code Online (Sandbox Code Playgroud)