2020-06-02 22:25:07 -05:00
|
|
|
#!/usr/bin/env python3
|
2015-06-09 22:12:58 -05:00
|
|
|
|
|
|
|
'''
|
|
|
|
Example custom dynamic inventory script for Ansible, in Python.
|
|
|
|
'''
|
|
|
|
|
|
|
|
import os
|
|
|
|
import sys
|
|
|
|
import argparse
|
2020-06-03 08:52:11 -05:00
|
|
|
import json
|
2015-06-09 22:12:58 -05:00
|
|
|
|
|
|
|
class ExampleInventory(object):
|
|
|
|
|
|
|
|
def __init__(self):
|
|
|
|
self.inventory = {}
|
|
|
|
self.read_cli_args()
|
|
|
|
|
|
|
|
# Called with `--list`.
|
|
|
|
if self.args.list:
|
|
|
|
self.inventory = self.example_inventory()
|
|
|
|
# Called with `--host [hostname]`.
|
|
|
|
elif self.args.host:
|
|
|
|
# Not implemented, since we return _meta info `--list`.
|
|
|
|
self.inventory = self.empty_inventory()
|
2015-10-15 22:06:43 -05:00
|
|
|
# If no groups or vars are present, return empty inventory.
|
2015-06-09 22:12:58 -05:00
|
|
|
else:
|
|
|
|
self.inventory = self.empty_inventory()
|
|
|
|
|
2020-06-02 22:25:07 -05:00
|
|
|
print(json.dumps(self.inventory));
|
2015-06-09 22:12:58 -05:00
|
|
|
|
|
|
|
# Example inventory for testing.
|
|
|
|
def example_inventory(self):
|
|
|
|
return {
|
|
|
|
'group': {
|
2022-11-27 13:33:47 -06:00
|
|
|
'hosts': ['192.168.56.71', '192.168.56.72'],
|
2015-06-09 22:12:58 -05:00
|
|
|
'vars': {
|
2020-05-12 23:11:40 -05:00
|
|
|
'ansible_user': 'vagrant',
|
2015-06-10 23:00:57 -05:00
|
|
|
'ansible_ssh_private_key_file':
|
|
|
|
'~/.vagrant.d/insecure_private_key',
|
2019-08-27 12:41:05 -05:00
|
|
|
'ansible_python_interpreter':
|
|
|
|
'/usr/bin/python3',
|
2015-06-09 22:12:58 -05:00
|
|
|
'example_variable': 'value'
|
|
|
|
}
|
|
|
|
},
|
|
|
|
'_meta': {
|
|
|
|
'hostvars': {
|
2022-11-27 13:33:47 -06:00
|
|
|
'192.168.56.71': {
|
2015-06-09 22:12:58 -05:00
|
|
|
'host_specific_var': 'foo'
|
|
|
|
},
|
2022-11-27 13:33:47 -06:00
|
|
|
'192.168.56.72': {
|
2015-06-09 22:12:58 -05:00
|
|
|
'host_specific_var': 'bar'
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
# Empty inventory for testing.
|
|
|
|
def empty_inventory(self):
|
|
|
|
return {'_meta': {'hostvars': {}}}
|
|
|
|
|
|
|
|
# Read the command line args passed to the script.
|
|
|
|
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.
|
|
|
|
ExampleInventory()
|