From f502b09c103b5d8681854b7ab6a3c9655311f73b Mon Sep 17 00:00:00 2001 From: Rodolfo Carvalho Date: Mon, 6 Feb 2017 17:06:18 +0100 Subject: Refactor code to access values from task_vars --- .../openshift_checks/__init__.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) (limited to 'roles/openshift_health_checker/openshift_checks/__init__.py') diff --git a/roles/openshift_health_checker/openshift_checks/__init__.py b/roles/openshift_health_checker/openshift_checks/__init__.py index ff99e7b4c..c31242624 100644 --- a/roles/openshift_health_checker/openshift_checks/__init__.py +++ b/roles/openshift_health_checker/openshift_checks/__init__.py @@ -5,8 +5,10 @@ Health checks for OpenShift clusters. import os from abc import ABCMeta, abstractmethod, abstractproperty from importlib import import_module +import operator import six +from six.moves import reduce class OpenShiftCheckException(Exception): @@ -54,6 +56,22 @@ class OpenShiftCheck(object): yield subclass +def get_var(task_vars, *keys, **kwargs): + """Helper function to get deeply nested values from task_vars. + + Ansible task_vars structures are Python dicts, often mapping strings to + other dicts. This helper makes it easier to get a nested value, raising + OpenShiftCheckException when a key is not found. + """ + try: + value = reduce(operator.getitem, keys, task_vars) + except (KeyError, TypeError): + if "default" in kwargs: + return kwargs["default"] + raise OpenShiftCheckException("'{}' is undefined".format(".".join(map(str, keys)))) + return value + + # Dynamically import all submodules for the side effect of loading checks. EXCLUDES = ( -- cgit v1.2.3