Ansible AWX/Tower Check_MK inventory plugin

Das Script kann als Inventory Plugin verwendet werden für AWX / Tower um Hosts von Check_MK in AWX / Tower zu importieren. Dazu muss ein View angelegt werden mit folgenden Spalten: Host, IPv4 address, Host Tags

Der Automation User muss Rechte auf den View und die entsprechende Contact Group haben.

#!/usr/bin/bash

cat << EOF > /tmp/check_mk_inventory.py
#!/usr/bin/env python3

########################################################################################################################
# Configuration for Check_MK
username = "automation user"
password = "xxxxxxxxxxxxxxxxxxxx"
base_url = "https://checkmk-dev/dev/check_mk/view.py"
view = "host_inventory"

import urllib.parse
import urllib.request
import os
import re
import sys
import argparse
import ssl

ssl._create_default_https_context = ssl._create_unverified_context

try:
	import json
except ImportError:
	import simplejson as json


class CheckMKInventory(object):

	def __init__(self):
		self.inventory = {}
		self.read_cli_args()

		# Called with `--list`.
		if self.args.list:
			self.inventory = self.checkmk_inventory()
		# Called with `--host [hostname]`.
		elif self.args.host:
			# Not implemented, since we return _meta info `--list`.
			self.inventory = self.empty_inventory()
		# If no groups or vars are present, return an empty inventory.
		else:
			self.inventory = self.empty_inventory()

		print(json.dumps(self.inventory))

	# Generator for key->value from view
	def generator(self, x):
		header = x[:1][0]
		data = x[1:]
		result = []

		for d in data:
			result.append(dict(zip(header, d)))

		return result

	def checkmk_inventory(self):
		# Values for post
		values = {
			"output_format": "python",
			"view_name": view,
			"_username": username,
			"_secret": password
		}

		# Encode and post to check_mk
		proxy_handler = urllib.request.ProxyHandler({})
		opener = urllib.request.build_opener(proxy_handler)
		data = urllib.parse.urlencode(values)
		data = data.encode('utf-8')
		req = urllib.request.Request(base_url, data)
		resp = opener.open(req)

		# Try to read the response
		try:
			hosts_view_raw = eval(resp.read())
			hosts_view_dict = self.generator(hosts_view_raw)

		except Exception as e:
			print(e)
			sys.exit(1)

		results = dict()
		results['_meta'] = {}
		results['_meta']['hostvars'] = {}
		results['checkmk'] = {}
		results['checkmk']['hosts'] = []

		for h in hosts_view_dict:

            try:
				path = re.findall(r".*\/wato\/(.*)\/.*", h['host_tags'])[0]
	
			except Exception as e:
				path = ""
		
			results['_meta']['hostvars'][h['host']] = {
				"ansible_host": h['host_ipv4_address'],
				"path": path,
				
			}
	
			results['checkmk']['hosts'].append(h['host'])

		return results


	# 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.
CheckMKInventory()


EOF

chmod 0500 /tmp/check_mk_inventory.py
unset PYTHONPATH
/tmp/check_mk_inventory.py "$@"
rm -f /tmp/check_mk_inventory.py

1 Gedanke zu „Ansible AWX/Tower Check_MK inventory plugin“

  1. Moin, das ist genau das was ich gesucht habe. leider läuft dein Script nicht bei mir, und ich bin echt nicht gut in Python.
    Könnten wir das eventuell mal zusammen troubleshooten?

    Antworten

Schreibe einen Kommentar

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.