From 9c02c2b83942824bb8dcf6e692d49de8c59ee64e Mon Sep 17 00:00:00 2001 From: Alexandre Pires Date: Sat, 5 Oct 2024 19:26:07 +0200 Subject: [PATCH] Refactor inventory path in ansible.cfg --- ansible/ansible.cfg | 2 +- bin/read_system_id.py | 47 ++++++++++++++++++++++++++ {ansible/inventory => inventory}/hosts | 0 requirements.txt | 1 + 4 files changed, 49 insertions(+), 1 deletion(-) create mode 100755 bin/read_system_id.py rename {ansible/inventory => inventory}/hosts (100%) diff --git a/ansible/ansible.cfg b/ansible/ansible.cfg index 7c10acc..6eef302 100644 --- a/ansible/ansible.cfg +++ b/ansible/ansible.cfg @@ -1,5 +1,5 @@ [defaults] -inventory = ./inventory/hosts +inventory = ../inventory/hosts [ssh_connection] ssh_args = -o ControlMaster=auto -o ControlPersist=60s \ No newline at end of file diff --git a/bin/read_system_id.py b/bin/read_system_id.py new file mode 100755 index 0000000..8d4d35b --- /dev/null +++ b/bin/read_system_id.py @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +import argparse +import configparser +import json +import os + +from fabric import Connection + +script_path = os.path.realpath(__file__) + +def parse_ansible_inventory(inventory_file): + parser = configparser.ConfigParser(allow_no_value=True) + parser.read(inventory_file) + + inventory_dict = {} + + for section in parser.sections(): + hosts = [] + + for option in parser.options(section): + hosts.append(option) + + inventory_dict[section] = hosts + + return inventory_dict + +parser = argparse.ArgumentParser(description='Run a command on a group of hosts') +parser.add_argument('group', type=str, help='Group of hosts to run the command on') +parser.add_argument('host', type=str, help='Host to run the command on', default=None, nargs='?') +args = parser.parse_args() + +remote_user = os.environ.get('ANSIBLE_USER', None) +if remote_user is None: + raise ValueError("ANSIBLE_USER environment variable not set") + +inventory_file = f'{os.path.dirname(script_path)}/../inventory/hosts' +inventory_dict = parse_ansible_inventory(inventory_file) + +ids = {} +for host in inventory_dict[args.group]: + if args.host is not None and args.host != host: + continue + result = Connection(host, remote_user).run('sudo read_system_id', hide=True) + ids[host]=(str(result.stdout).strip()) + + +print(json.dumps(ids)) \ No newline at end of file diff --git a/ansible/inventory/hosts b/inventory/hosts similarity index 100% rename from ansible/inventory/hosts rename to inventory/hosts diff --git a/requirements.txt b/requirements.txt index bfad3dc..711f325 100644 --- a/requirements.txt +++ b/requirements.txt @@ -2,3 +2,4 @@ ansible ansible-lint ansible-playbook-grapher passlib +fabric \ No newline at end of file