Use variables in standard loops

27 views
Skip to first unread message

Vikas Kumar

unread,
Sep 22, 2015, 5:00:24 PM9/22/15
to Ansible Project
I am trying to user variables in the below example described here.


- name: add several users
  user
: name={{ item.name }}
  state
=present groups={{ item.groups }}
  with_items
:
   
- { name: 'testuser1', groups: 'wheel' }
   
- { name: 'testuser2', groups: 'root' }


This works fine, but when I try to infuse variables, it does not works as intended. I am sure, I am doing something wrong.

I've defined two lists in my playbook
  vars:
   
- old:
       
- ens155
       
- ens160
   
- new:
       
- eth0
       
- eth1


I am trying to make below code work like ens155 is eth0 and ens160 is eth1, but this code shows this message - [ens155, ens160] is [eth0, eth1]

- shell: echo {{ item.old }} is {{ item.new }}
    with_items
:
     
- { old: '{{ old }}', new: '{{ new }}' }

How can I make this work ? If required, I am happy to change the way my variables are defined.

Regards.

Alwin Schoemaker

unread,
Sep 23, 2015, 2:27:40 AM9/23/15
to Ansible Project
The injected old and new are injected as an array. Try it like this:

- shell: echo {{ item.old }} is {{ item.new }}
    with_items:
      - { old: '{{ old[0] }}', new: '{{ new[0] }}' }
      - { old: '{{ old[1] }}', new: '{{ new[1] }}' }

Vikas Kumar

unread,
Sep 23, 2015, 2:42:44 AM9/23/15
to Ansible Project
Thanks Alwin, the number of elements in the list could vary.  

This is what I was looking for.

    - shell: echo {{ item.0 }} is {{ item.1 }}
      with_together
:
       
- "{{ old }}"
       
- "{{ new }}"

Regards.
Reply all
Reply to author
Forward
0 new messages