0

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 }
Zeitounator
  • 38,476
  • 7
  • 53
  • 66
Sashi K
  • 43
  • 5
  • 3
    Do you want to run this task/play, taking value from command line instead? If its the ad-hoc mode, you won't be able to use `with_items` and `item`. – seshadri_c Dec 27 '21 at 06:31
  • 1
    Does [variables in Ansible ad-hoc commands](https://serverfault.com/a/1027026/448950) answer your quesstion? – U880D Dec 27 '21 at 08:48
  • thank you @seshadri_c can you please let me know what needs to be changed in the playbook. So, that the above task/play could be run from the command line. thanks in advance. – Sashi K Dec 27 '21 at 13:46

1 Answers1

0

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.

seshadri_c
  • 6,906
  • 2
  • 10
  • 24