bosari
bosari

Reputation: 2000

How to pass variable value from command parameter and use it in with_items:?

For me the below code is working - with_items: "{{ groups['mlpoc'] }}" but instead of hardcoded mlpoc I want to pass it in a variable as a parameter.
Say the command parameter is mlhosts=mlpoc and I want to use the variable instead of hardcoded value, something like - with_items: "{{ groups['{{ mlhosts }}'] }}" but it throws error. Is it even possible to pass a dynamic value to groups ?
Here is my code -

- hosts: dbsrd3510
  user: '{{ mluser }}'
  gather_facts: no
  no_log: false
  tasks:
    - name: Fetch source list from clients
      with_items: "{{ groups['mlpoc'] }}" 
      shell: rsync -av /MLbackup/{{ pkg }} {{ mluser }}@{{ item }}:/tmp/ 

Upvotes: 0

Views: 440

Answers (1)

Shubham Vaishnav
Shubham Vaishnav

Reputation: 1720

Try something like this,

---
- hosts: all
  gather_facts: no
  tasks:
    - name: Add a line to a file if the file does not exist, without passing regexp
      debug:
        msg: "{{ item }}"
      with_items: " {{ groups[group_name] }} "

And you can test the above changes using,

ansible-playbook -i hosts main.yml -e group_name="all"

Upvotes: 1

Related Questions