Skip to content

Instantly share code, notes, and snippets.

@thejimnicholson
Created February 16, 2024 21:50
Show Gist options
  • Save thejimnicholson/c6560f554dfd94acd387cc970f274a8f to your computer and use it in GitHub Desktop.
Save thejimnicholson/c6560f554dfd94acd387cc970f274a8f to your computer and use it in GitHub Desktop.
from ansible.plugins.inventory import BaseInventoryPlugin
import yaml
class CustomInventoryPlugin(BaseInventoryPlugin):
NAME = 'custom_inventory'
def parse(self, inventory, loader, path, cache=True):
super(CustomInventoryPlugin, self).parse(inventory, loader, path)
# Load the YAML inventory file
with open(path, 'r') as file:
inventory_data = yaml.safe_load(file)
for hostname, hostvars in inventory_data.items():
# Calculate additional variables based on the hostname
if 'hostname_prefix' in hostvars:
hostvars['calculated_value'] = len(hostvars['hostname_prefix'])
# Inject the calculated variables into the host
inventory.add_host(hostname)
inventory.set_host_variable(hostname, 'calculated_value', hostvars.get('calculated_value', 0))
# Set the default group
inventory.add_group('all')
for hostname in inventory_data.keys():
inventory.add_child('all', hostname)
# Required for Ansible to recognize and load the plugin properly
CustomInventoryPlugin()
[defaults]
inventory = /path/to/inventory.yaml
[inventory]
enable_plugins = custom_inventory_plugin.py
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment