AniNIX/Wiki#21 -- effecting renames for policy
This commit is contained in:
63
bin/kapisi_lib.py
Normal file
63
bin/kapisi_lib.py
Normal file
@@ -0,0 +1,63 @@
|
||||
import re
|
||||
import yaml
|
||||
from types import SimpleNamespace
|
||||
from yamlpath.common import Parsers
|
||||
from yamlpath.wrappers import ConsolePrinter
|
||||
from yamlpath import Processor
|
||||
from yamlpath import YAMLPath
|
||||
from yamlpath.exceptions import YAMLPathException
|
||||
|
||||
def TrackIPEntries(yaml_file,searchstring='all.children.**.ip'):
|
||||
### Try to parse an Ansible inventory for hosts with the 'ip' attribute.
|
||||
# param file: the file to parse
|
||||
# return: a populated entry set in form [{Host,[ip,mac]},...]
|
||||
|
||||
# Borrowing from upstream author's example at https://pypi.org/project/yamlpath/
|
||||
|
||||
entryset = {}
|
||||
|
||||
# The various classes of this library must be able to write messages somewhere
|
||||
# when things go bad.
|
||||
#logging_args = SimpleNamespace(quiet=True, verbose=False, debug=False)
|
||||
logging_args = SimpleNamespace(quiet=True, verbose=True, debug=True)
|
||||
log = ConsolePrinter(logging_args)
|
||||
|
||||
# Prep the YAML parser
|
||||
yaml = Parsers.get_yaml_editor()
|
||||
(yaml_data, doc_loaded) = Parsers.get_yaml_data(yaml, log, yaml_file)
|
||||
if not doc_loaded:
|
||||
exit(1)
|
||||
processor = Processor(log, yaml_data)
|
||||
|
||||
yaml_path = YAMLPath(searchstring)
|
||||
|
||||
# Create a regex pattern to remove the end of the path
|
||||
ippattern = re.compile('\.ip$')
|
||||
try:
|
||||
for node_coordinate in processor.get_nodes(yaml_path, mustexist=True):
|
||||
# Strip the path to the host entry.
|
||||
path = ippattern.sub("",str(node_coordinate.path))
|
||||
# Pull the IP
|
||||
ip = str(node_coordinate.node)
|
||||
# Pull the hosname
|
||||
splitpath = path.split('.')
|
||||
hostname = splitpath[len(splitpath)-1]
|
||||
#print("Got {} from '{}''.".format(ip,path))
|
||||
|
||||
# Path the MAC
|
||||
mac_yaml_path = YAMLPath(path+".mac")
|
||||
mac=""
|
||||
try:
|
||||
for node_coordinate in processor.get_nodes(mac_yaml_path, mustexist=True):
|
||||
mac = str(node_coordinate.node)
|
||||
except YAMLPathException as ex:
|
||||
log.error(ex)
|
||||
|
||||
# Add the host to the entryset.
|
||||
entryset.update({ hostname : [ip,mac] })
|
||||
|
||||
except YAMLPathException as ex:
|
||||
log.error(ex)
|
||||
|
||||
finally:
|
||||
return entryset
|
||||
Reference in New Issue
Block a user