Refactor inventory path in ansible.cfg

This commit is contained in:
2024-10-05 19:26:07 +02:00
parent a78b848ba3
commit 9c02c2b839
4 changed files with 49 additions and 1 deletions
+1 -1
View File
@@ -1,5 +1,5 @@
[defaults] [defaults]
inventory = ./inventory/hosts inventory = ../inventory/hosts
[ssh_connection] [ssh_connection]
ssh_args = -o ControlMaster=auto -o ControlPersist=60s ssh_args = -o ControlMaster=auto -o ControlPersist=60s
+47
View File
@@ -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))
+1
View File
@@ -2,3 +2,4 @@ ansible
ansible-lint ansible-lint
ansible-playbook-grapher ansible-playbook-grapher
passlib passlib
fabric