flyingfish
flyingfish

Reputation: 335

How to pass extra variables to ansible as list of dictionary to ansible playbook by --extra-vars?

I want to pass variables to my ansible playbook by --extra-vars, and the type of variables is a list of dict like this:

  list1:
    - { key1: "val1", key2: "val2" }
    - { key1: "val3", key2: "val4" }

My playbook is :

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

  tasks:
  - name: echo item
    shell: echo {{ item.key1 }}
    with_items: list1

and I try to pass variables like this:

ansible-playbook build_and_cppcheck.yml -e "lists=[{ "key1": "val1", "key2":"val2" },{ "key1": "val3", "key2":"val4" }]"

But I get the following error which I don't know how to fix:

fatal: [localhost] => with_items expects a list or a set

Upvotes: 5

Views: 16273

Answers (1)

3sky
3sky

Reputation: 890

Just use JSON string syntax: Ansible doc. For example:

play.yml

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

    - debug:
        msg: "This is {{ test[1] }}"

which you call as like this:

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


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    

Upvotes: 9

Related Questions