Home > front end >  How to pass multiple values to "with_items" through ad-hoc command?
How to pass multiple values to "with_items" through ad-hoc command?

Time:12-29

Here is the example ansible-playbook, if I want to pass the values of {{ item.first }} and {{ item.second }} through ad-hoc command from the terminal.

How can we do it ?

Thanks in advance..

---
- hosts: localhost
  tasks:
  - name: Here we are providing a list which have items containing multiple 
    debug:
      msg: "current first value is {{ item.first }} and second value is {{ item.second }}"
    with_items:
      - { first: lemon, second: carrot }
      - { first: cow, second: goat }

CodePudding user response:

So, to loop your debug task by passing the values from command line (or anywhere else), you will need to use a variable for the task (e.g. with_items: "{{ my_var }}").

There are many ways to supply value to variables, but for this specific requirement, we can use --extra-vars.

Considering a playbook myplaybook.yml as below:

- hosts: localhost

  tasks:
    - name: Here we are providing a list which have items containing multiple
      debug:
        msg: "current first value is {{ item.first }} and second value is {{ item.second }}"
      with_items: "{{ my_var }}"

Can be run by passing this variable on the command line as:

ansible-playbook myplaybook.yml -e '{my_var: [{first: lemon, second: carrot}, {first: cow, second: goat}]}'

Do note the other ways (linked above) using which variables can be supplied and use them if they are more efficient than this approach.

  • Related