Create an Ansible inventory from a csv file.
Create an Ansible inventory in YAML format using the following steps.
Assuming that the CSV file has the following structure:
Hostname,IP Address,Variable1,Variable2,Variable3
host1,192.168.1.1,value1,value2,value3
host2,192.168.1.2,value4,value5,value6
-
Convert the CSV file to a YAML file format
-
Use Ansible's
yaml_inventory_plugin
to parse the YAML file and create the inventory
Sample playbook
---
- hosts: localhost
gather_facts: no
vars:
csv_file: /path/to/csv/file.csv
yaml_file: /path/to/yaml/file.yaml
tasks:
- name: Convert CSV to YAML
community.general.csv_to_yaml:
path: "{{ csv_file }}"
output_file: "{{ yaml_file }}"
- name: Create inventory from YAML
ansible.builtin.add_host:
name: "{{ item.Hostname }}"
ansible_host: "{{ item['IP Address'] }}"
variable1: "{{ item.Variable1 }}"
variable2: "{{ item.Variable2 }}"
variable3: "{{ item.Variable3 }}"
loop: "{{ lookup('yaml', yaml_file) }}"
In this example, the csv_to_yaml Ansible Galaxy module is used to convert the CSV file to YAML format. The add_host module is then used to create the inventory based on the YAML file contents.
You can run this playbook with the following command:
ansible-playbook -i localhost, inventory.yml