Loop through CSV file

32 views
Skip to first unread message

Delmiro Campelo

unread,
Mar 27, 2022, 3:58:07 PM3/27/22
to Ansible Project

I was hoping that you can give me a hand with an issue here. I have about a thousand routers that I’m trying to configure. I have all the device specific information on a CSV file that I would like to use for populating all the necessary device fields. I would like to loop through this CSV file, so I don’t have create a playbook with a thousand tasks. I have a playbook that works on a single device basis, but I want to expand it to be able to use for as many routers as I can have on a CSV file. Can you give me some ideas here? Thank you for any help or tips you can provide.

 - hosts: vmanage

  connection: local
  gather_facts: no
  vars:
    ansible_user: testing123
    vmanage_ip: 10.10.2.2
    ansible_password: testing123
    state: present
    host_name_var: "{{ lookup('csvfile','123456 file=csvdata.csv delimiter=, col=1') }}"
    system_ip_var: "{{ lookup('csvfile','123456 file=csvdata.csv delimiter=, col=2') }}"
    site_id_var: "{{ lookup('csvfile','123456 file=csvdata.csv delimiter=, col=3') }}"
    vpn_next_hop_0_var: "{{ lookup('csvfile','123456 file=csvdata.csv delimiter=, col=4') }}"
    vpn_next_hop_1_var: "{{ lookup('csvfile','123456 file=csvdata.csv delimiter=, col=5') }}"
    vpn_if_ipv4_1_var: "{{ lookup('csvfile','123456 file=csvdata.csv delimiter=, col=6') }}"
    vpn_if_ipv4_2_var: "{{ lookup('csvfile','123456 file=csvdata.csv delimiter=, col=7') }}"
    vpn_if_ipv4_var: "{{ lookup('csvfile','123456 file=csvdata.csv delimiter=, col=8') }}"

  tasks:
   - vmanage_device_attachment:
       user: "{{ ansible_user }}"
       host: "{{ vmanage_ip }}"
       password: "{{ ansible_password }}"
       validate_certs: false
       device: Branch2
       template: BRANCHES-CSR-TEMPLATEv2
       variables:
         vpn_next_hop_ip_address_0: "{{ vpn_next_hop_0_var }}"
         vpn_next_hop_ip_address_1: "{{ vpn_next_hop_1_var }}"
         vpn_if_ipv4_address_2: "{{ vpn_if_ipv4_1_var }}"
         vpn_if_ipv4_address: "{{ vpn_if_ipv4_2_var }}"
         host-name: "{{ host_name_var }}"
         system-ip: "{{ system_ip_var }}"
         site-id: "{{ site_id_var }}"
         vpn_if_ipv4_address_1: "{{ vpn_if_ipv4_var }}"
       wait: yes
       state: "{{ state }}"

 cat /etc/ansible/python-viptela/ansible/vars/csvdata.csv
system-uuid,hostname,system-ip,site-id,vpn_next_hop_ip_address_0,vpn_next_hop_ip_address_1,vpn_if_ipv4_address_2,vpn_if_ipv4_address,vpn_if_ipv4_address_1
123456,Branch2,100.1.4.1,141,98.1.9.2, 98.1.10.2,98.1.9.1/30,98.1.10.1/30,10.141.0.254/24

Todd Lewis

unread,
Mar 27, 2022, 5:06:46 PM3/27/22
to Ansible Project

Delmiro Campelo

unread,
Mar 28, 2022, 10:42:54 AM3/28/22
to Ansible Project
Thank you for that suggestion. read_csv it's a better option for doing this. 
Reply all
Reply to author
Forward
0 new messages