How to convert CSV to Ansible inventory (INI) file?

Viewed 33

I have a simple CSV file. I am trying to figure out how to convert it into an Ansible INI inventory file.

CSV file

id1,comp2
id1,comp4
id2,comp2
id2,comp3
id3,comp4

Desired output

[id1]
comp2
comp4

[id2]
comp2
comp3

[id3]
comp4

Thanks for any suggestions.

1 Answers

Given the file

shell> cat /tmp/hosts.csv
id1,comp2
id1,comp4
id2,comp2
id2,comp3
id3,comp4

Read the file

    - command: cat /tmp/hosts.csv
      register: out

Put the below declarations into the vars

    csv_hosts: "{{ out.stdout_lines|map('split', ',')|groupby('0') }}"
    ini_hosts: |
      {% for group in csv_hosts %}
      [{{ group.0 }}]
      {% for host in group.1|map(attribute='1') %}
      {{ host }}
      {% endfor %}

      {% endfor %}

gives

  ini_hosts: |-
    [id1]
    comp2
    comp4
  
    [id2]
    comp2
    comp3
  
    [id3]
    comp4

Write the file

    - copy:
        dest: /tmp/hosts.ini
        content: "{{ ini_hosts }}"

gives

shell> cat /tmp/hosts.ini
[id1]
comp2
comp4

[id2]
comp2
comp3

[id3]
comp4

Example of a complete playbook for testing

- hosts: localhost
  gather_facts: false
  vars:
    csv_hosts: "{{ out.stdout_lines|map('split', ',')|groupby('0') }}"
    ini_hosts: |
      {% for group in csv_hosts %}
      [{{ group.0 }}]
      {% for host in group.1|map(attribute='1') %}
      {{ host }}
      {% endfor %}

      {% endfor %}
  tasks:
    - command: cat /tmp/hosts.csv
      register: out
    - debug:
        var: ini_hosts
    - copy:
        dest: /tmp/hosts.ini
        content: "{{ ini_hosts }}"
Related