Ansible – Using Variables in Scripts After Fetching from CSV Files Inside a Loop

ansibleansible-playbook

I am new to Ansible. I want to know how I can read an excel or csv file inside Ansible, store the information in variables and work with those variables.

Actually I want to create VMs. I will use the csv files to get the details (like hostname, partition details, IP details) of the VMs.

If somebody can help me in this regards.

Best Answer

Use read_csv – Read a CSV file module. For example the playbook

- hosts: localhost
  tasks:
    - read_csv:
        path: vms.csv
        key: hostname
      register: vms
    - debug:
        msg: "{{ item.key }}:
              {{ item.value.hostname }},
              {{ item.value.partition }},
              {{ item.value.ip }}"
      loop: "{{ vms.dict|dict2items }}"

with the file

$ cat vms.csv
hostname,partition,ip
hostname1,/dev/sda1,10.1.0.21
hostname2,/dev/sda1,10.1.0.22
hostname3,/dev/sda1,10.1.0.23

gives

  msg: 'hostname1: hostname1, /dev/sda1, 10.1.0.21'
  msg: 'hostname2: hostname2, /dev/sda1, 10.1.0.22'
  msg: 'hostname3: hostname3, /dev/sda1, 10.1.0.23'