From 21145f8cb0fe410cb1c16130cf7f3942443a5cb5 Mon Sep 17 00:00:00 2001 From: Student User Date: Tue, 4 Aug 2026 06:01:02 +0000 Subject: [PATCH] Add dyn inventory --- inventory.py | 80 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100755 inventory.py diff --git a/inventory.py b/inventory.py new file mode 100755 index 0000000..81d1c4e --- /dev/null +++ b/inventory.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python + +''' +This is a python script used for an example of a dynamic inventory script +for use with Ansible. + +call it with --list to show list. +call it with --host [hostname] for specific hosts + + +''' + +import os +import argparse +import sys + +try: + import json +except ImportError: + import simplejson as json + + +class OurInventory(object): + + def __init__(self): + self.inventory = {} + self.read_cli_args() + + # This section is called with `--list`. + if self.args.list: + self.inventory = self.our_inventory() + # this section is called with `--host [hostname]`. + elif self.args.host: + # We return _meta info `--list` so not complete. + self.inventory = self.empty_inventory() + + # No vars or group? Return as an empty inventory. + else: + self.inventory = self.empty_inventory() + + print (json.dumps(self.inventory)); + + # This is an example used simply for testing and so we can run a dymanic script without actualy setting up a server + # + + def our_inventory(self): + return { + 'group': { + 'hosts': ['servera.lab.example.com', 'serverb.lab.example.com'], + 'vars': { + 'ansible_user': 'ansible', + 'instruktor': 'Simonas' + } + }, + '_meta': { + 'hostvars': { + 'servera.lab.example.com': { + 'logs_folder': '/var/log' + }, + 'serverb.lab.example.com': { + 'logs_folder': '/var/log2' + } + } + } + } + + # Empty inventory for testing. + def empty_inventory(self): + return {'_meta': {'hostvars': {}}} + + # Lets take the args passed to us via the command line. + + def read_cli_args(self): + parser = argparse.ArgumentParser() + parser.add_argument('--list', action = 'store_true') + parser.add_argument('--host', action = 'store') + self.args = parser.parse_args() + +# Get the inventory. +OurInventory()