Ansible inventaire script - inventaire dynamique vers statique - Conversion JSON YAML INI

Voir :

notes_ansible-inventory

https://docs.ansible.com/automation-controller/latest/html/administration/scm-inv-source.html

INI vers JSON

Pour convertir un inventaire Ansible INI vers JSON

ansible-inventory -i inventory.ini --list > inventory.json

INI vers YAML

Pour convertir un inventaire Ansible de INI vers YAML

ansible-inventory -i inventory.ini -y --list > inventory.yml

JSON vers YAML

cat.py

#! /usr/bin/env python3 import os filename = os.environ["FILENAME"] with open(filename, "r") as f: print(f.read())
env FILENAME=inventaire.json ansible-inventory -i cat.py -y --list> inventaire.yml

JSON vers INI

Reformater l'inventaire JSON

env FILENAME=inventaire.json ansible-inventory -i cat.py --list> inventaire2.json

Script de conversion json_to_ini.py

json_to_ini.py

#! /usr/bin/env python3 import sys import json import configparser import argparse parser = argparse.ArgumentParser( epilog="""Convert Ansible JSON inventory file to INI. JSON inventory must be in ansible-inventory format. """ ) parser.add_argument("-i", help="Input JSON file") parser.add_argument("-o", help="Output INI file") args = parser.parse_args() def convert_json2ini(): config_object = configparser.ConfigParser(delimiters=" ") with open(args.i, "r") as json_file: python_dictionary = json.load(json_file) python_dictionary["all"]["children"].remove("ungrouped") for section in python_dictionary["all"]["children"]: config_object.add_section(section) for options in python_dictionary[section]["hosts"]: suboptions = [] for subsection in python_dictionary["_meta"]["hostvars"][options]: subkey = str(subsection) subvalue = ( '"' + str(python_dictionary["_meta"]["hostvars"][options][subkey]) + '"' ) suboptions.append("=".join([subkey, subvalue])) key = " ".join(suboptions) config_object.set(section, options, key) with open(args.o, "w") as ini_file: config_object.write(ini_file) def main(): if args.i and args.o: convert_json2ini() sys.exit(0) if __name__ == "__main__": main()
./json_to_ini.py -i inventaire2.json -o inventaire.ini