BruH
BruH

Reputation: 35

Ansible with items using multiple variables

Just looking for a bit of help.

Basically what I am trying do is create a file for each network interface my computer has with the filename being a combination of the interface name and mac address.
e.g.

For these interfaces
eth0 with mac 123-456-789
eth1 with mac 987-654-321
eth2 with mac 456-123-789

I expect 3 files created with names:
eth0_123-456-789
eth1_987-654-321
eth2_456-123-789

I currently have this playbook

- hosts: all

  tasks:
    - name: Create files
      block:
        - name: This gets me a list of all eth* interfaces
          shell: ls /sys/class/net/ | grep eth
          register: eth_interface

        - name: This gets the mac address for each of those eth* interfaces
          command: cat /sys/class/net/{{ item }}/address
          with_items: "{{ eth_interface.stdout_lines }}"
          register: mac_address

        - name: Add mac address to its relevant file
          command: touch /tmp/"{{ item.mac }}"_"{{ item.eth }}"
          with_items: 
             - { eth: "{{ eth_interface.stdout_lines }}", mac: "{{ mac_address | json_query('results[*].stdout') }}" }

I expected to get 3 separate files for each interface, but instead I got 1 single file with the name below: [u'123-456-789', u'987-654-321', u'456-123-789'][u'eth0', u'eth1', u'eth2']

It seems to work fine if I use just a single variable like either eth or mac, but breaks when I use the 2 variables together using with_items loop.

Can someone please help?

Upvotes: 1

Views: 543

Answers (1)

Vladimir Botka
Vladimir Botka

Reputation: 68034

The playbook below

shell> cat pb.yml
- hosts: localhost
  vars:
    ifc: [eth0, eth1, eth2]
    mac: [AAA, BBB, CCC]
  tasks:
    - file:
        state: touch
        path: "{{ 'tmp/' ~ item.0 ~ '_' ~ item.1 }}"
      loop: "{{ ifc|zip(mac)|list }}"

creates

shell> tree tmp
tmp
├── eth0_AAA
├── eth1_BBB
└── eth2_CCC

Upvotes: 2

Related Questions