Reputation: 91
I'm trying to create an Ansible Inventory file from an existing YAML file. Here is the yaml file I am talking about:
- Fabric: AAA
Hauteur: 20
Nom de l'equipement: AAA-BAT1
Role: BGW
Salle: '1'
Travee: 4
Type de materiel: N9K-C9YTR
- Hauteur: 20
Nom de l'equipement: BBB-BAT2
Role: SP
Salle: '1'
Travee: 4
Type de materiel: N9K-C9YTR
into this inventory:
all:
hosts:
AAA-BAT1:
Type de materiel: "N9K-C9YTR"
Fabric: "AAA"
emplacement:
Salle: "1"
Travee: "4"
Hauteur: "20"
Role: "BGW"
BBB-BAT2:
Type de materiel: "N9K-C9YTR"
Fabric: "BBB"
emplacement:
Salle: "1"
Travee: "4"
Hauteur: "20"
Role: "SP"
Is there a way to do this with Python please?
Upvotes: 1
Views: 355
Reputation: 39119
You can even do all of this with an Ansible playbook, running it on the local - controller node.
Given the playbook:
- hosts: localhost
gather_facts: no
vars:
faking_data:
- Fabric: AAA
Hauteur: 20
Nom de l'equipement: AAA-BAT1
Role: BGW
Salle: '1'
Travee: 4
Type de materiel: N9K-C9YTR
- Fabric: BBB
Hauteur: 20
Nom de l'equipement: BBB-BAT2
Role: SP
Salle: '1'
Travee: 4
Type de materiel: N9K-C9YTR
tasks:
- set_fact:
hosts: "{{ hosts | default({}) | combine({item[\"Nom de l'equipement\"]: transformed_item}) }}"
loop: "{{ faking_data }}"
vars:
transformed_item:
"Type de materiel": "{{ item['Type de materiel'] }}"
Fabric: "{{ item.Fabric }}"
emplacement:
Salle: "{{ item.Salle }}"
Travee: "{{ item.Travee }}"
Hauteur: "{{ item.Hauteur }}"
Role: "{{ item.Role }}"
- copy:
content: "{{ {'all': {'hosts': hosts } } | to_nice_yaml(indent=2) }}"
dest: hosts.yml
This will end in creating a hosts.yml file containing
all:
hosts:
AAA-BAT1:
Fabric: AAA
Role: BGW
Type de materiel: N9K-C9YTR
emplacement:
Hauteur: '20'
Salle: '1'
Travee: '4'
BBB-BAT2:
Fabric: BBB
Role: SP
Type de materiel: N9K-C9YTR
emplacement:
Hauteur: '20'
Salle: '1'
Travee: '4'
Upvotes: 1