2014-10-02 17:07:05 +00:00
|
|
|
# (c) 2012-2014, Michael DeHaan <michael.dehaan@gmail.com>
|
|
|
|
#
|
|
|
|
# This file is part of Ansible
|
|
|
|
#
|
|
|
|
# Ansible is free software: you can redistribute it and/or modify
|
|
|
|
# it under the terms of the GNU General Public License as published by
|
|
|
|
# the Free Software Foundation, either version 3 of the License, or
|
|
|
|
# (at your option) any later version.
|
|
|
|
#
|
|
|
|
# Ansible is distributed in the hope that it will be useful,
|
|
|
|
# but WITHOUT ANY WARRANTY; without even the implied warranty of
|
|
|
|
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
|
|
|
# GNU General Public License for more details.
|
|
|
|
#
|
|
|
|
# You should have received a copy of the GNU General Public License
|
|
|
|
# along with Ansible. If not, see <http://www.gnu.org/licenses/>.
|
|
|
|
|
2014-10-15 23:22:54 +00:00
|
|
|
# Make coding more python3-ish
|
|
|
|
from __future__ import (absolute_import, division, print_function)
|
|
|
|
__metaclass__ = type
|
|
|
|
|
2016-11-21 22:57:27 +00:00
|
|
|
import re
|
|
|
|
|
2015-06-27 19:37:10 +00:00
|
|
|
from jinja2.exceptions import UndefinedError
|
|
|
|
|
2015-10-16 00:55:23 +00:00
|
|
|
from ansible.compat.six import text_type
|
2015-12-19 17:49:06 +00:00
|
|
|
from ansible.errors import AnsibleError, AnsibleUndefinedVariable
|
2014-11-14 22:14:08 +00:00
|
|
|
from ansible.playbook.attribute import FieldAttribute
|
|
|
|
from ansible.template import Templar
|
2016-09-16 05:14:53 +00:00
|
|
|
from ansible.module_utils._text import to_native
|
2016-12-13 17:14:47 +00:00
|
|
|
from ansible.vars.unsafe_proxy import wrap_var
|
2014-11-14 22:14:08 +00:00
|
|
|
|
2016-11-21 22:57:27 +00:00
|
|
|
DEFINED_REGEX = re.compile(r'(hostvars\[.+\]|[\w_]+)\s+(not\s+is|is|is\s+not)\s+(defined|undefined)')
|
2016-12-13 17:14:47 +00:00
|
|
|
LOOKUP_REGEX = re.compile(r'lookup\s*\(')
|
2016-11-21 22:57:27 +00:00
|
|
|
|
2014-10-15 23:37:29 +00:00
|
|
|
class Conditional:
|
2014-10-02 17:07:05 +00:00
|
|
|
|
2014-11-14 22:14:08 +00:00
|
|
|
'''
|
|
|
|
This is a mix-in class, to be used with Base to allow the object
|
|
|
|
to be run conditionally when a condition is met or skipped.
|
|
|
|
'''
|
|
|
|
|
2015-12-09 16:22:58 +00:00
|
|
|
_when = FieldAttribute(isa='list', default=[])
|
2014-11-14 22:14:08 +00:00
|
|
|
|
2015-01-15 07:13:45 +00:00
|
|
|
def __init__(self, loader=None):
|
|
|
|
# when used directly, this class needs a loader, but we want to
|
|
|
|
# make sure we don't trample on the existing one if this class
|
|
|
|
# is used as a mix-in with a playbook base class
|
|
|
|
if not hasattr(self, '_loader'):
|
|
|
|
if loader is None:
|
|
|
|
raise AnsibleError("a loader must be specified when using Conditional() directly")
|
|
|
|
else:
|
|
|
|
self._loader = loader
|
2014-11-14 22:14:08 +00:00
|
|
|
super(Conditional, self).__init__()
|
|
|
|
|
|
|
|
def _validate_when(self, attr, name, value):
|
|
|
|
if not isinstance(value, list):
|
|
|
|
setattr(self, name, [ value ])
|
|
|
|
|
2016-11-11 08:34:01 +00:00
|
|
|
def _get_attr_when(self):
|
|
|
|
'''
|
|
|
|
Override for the 'tags' getattr fetcher, used from Base.
|
|
|
|
'''
|
|
|
|
when = self._attributes['when']
|
|
|
|
if when is None:
|
|
|
|
when = []
|
|
|
|
if hasattr(self, '_get_parent_attribute'):
|
2016-11-14 22:29:13 +00:00
|
|
|
when = self._get_parent_attribute('when', extend=True, prepend=True)
|
2016-11-11 08:34:01 +00:00
|
|
|
return when
|
|
|
|
|
2016-11-21 22:57:27 +00:00
|
|
|
def extract_defined_undefined(self, conditional):
|
|
|
|
results = []
|
|
|
|
|
|
|
|
cond = conditional
|
|
|
|
m = DEFINED_REGEX.search(cond)
|
|
|
|
while m:
|
|
|
|
results.append(m.groups())
|
|
|
|
cond = cond[m.end():]
|
|
|
|
m = DEFINED_REGEX.search(cond)
|
|
|
|
|
|
|
|
return results
|
|
|
|
|
2015-05-04 06:33:10 +00:00
|
|
|
def evaluate_conditional(self, templar, all_vars):
|
2014-11-14 22:14:08 +00:00
|
|
|
'''
|
|
|
|
Loops through the conditionals set on this object, returning
|
|
|
|
False if any of them evaluate as such.
|
|
|
|
'''
|
|
|
|
|
2016-03-10 02:24:04 +00:00
|
|
|
# since this is a mix-in, it may not have an underlying datastructure
|
2015-06-28 04:30:27 +00:00
|
|
|
# associated with it, so we pull it out now in case we need it for
|
|
|
|
# error reporting below
|
|
|
|
ds = None
|
2015-09-15 17:08:54 +00:00
|
|
|
if hasattr(self, '_ds'):
|
|
|
|
ds = getattr(self, '_ds')
|
2015-06-28 04:30:27 +00:00
|
|
|
|
2015-06-27 19:37:10 +00:00
|
|
|
try:
|
2016-09-02 12:53:50 +00:00
|
|
|
# this allows for direct boolean assignments to conditionals "when: False"
|
|
|
|
if isinstance(self.when, bool):
|
|
|
|
return self.when
|
|
|
|
|
2015-06-27 19:37:10 +00:00
|
|
|
for conditional in self.when:
|
|
|
|
if not self._check_conditional(conditional, templar, all_vars):
|
|
|
|
return False
|
2015-08-27 06:16:11 +00:00
|
|
|
except Exception as e:
|
2016-09-16 05:14:53 +00:00
|
|
|
raise AnsibleError("The conditional check '%s' failed. The error was: %s" % (to_native(conditional), to_native(e)), obj=ds)
|
2015-05-04 06:33:10 +00:00
|
|
|
|
2014-11-14 22:14:08 +00:00
|
|
|
return True
|
|
|
|
|
2015-01-15 22:56:54 +00:00
|
|
|
def _check_conditional(self, conditional, templar, all_vars):
|
2014-11-14 22:14:08 +00:00
|
|
|
'''
|
|
|
|
This method does the low-level evaluation of each conditional
|
|
|
|
set on this object, using jinja2 to wrap the conditionals for
|
|
|
|
evaluation.
|
|
|
|
'''
|
|
|
|
|
2015-02-09 22:54:44 +00:00
|
|
|
original = conditional
|
2014-11-14 22:14:08 +00:00
|
|
|
if conditional is None or conditional == '':
|
|
|
|
return True
|
|
|
|
|
2017-01-10 22:54:00 +00:00
|
|
|
if conditional in all_vars and re.match("^[_A-Za-z][_a-zA-Z0-9]*$", conditional):
|
2015-02-10 17:27:45 +00:00
|
|
|
conditional = all_vars[conditional]
|
2014-11-14 22:14:08 +00:00
|
|
|
|
2016-03-10 02:24:04 +00:00
|
|
|
# make sure the templar is using the variables specified with this method
|
2015-06-17 04:09:04 +00:00
|
|
|
templar.set_available_variables(variables=all_vars)
|
|
|
|
|
2015-12-19 17:49:06 +00:00
|
|
|
try:
|
|
|
|
conditional = templar.template(conditional)
|
|
|
|
if not isinstance(conditional, text_type) or conditional == "":
|
|
|
|
return conditional
|
|
|
|
|
|
|
|
# a Jinja2 evaluation that results in something Python can eval!
|
2017-01-10 22:54:00 +00:00
|
|
|
disable_lookups = False
|
|
|
|
if hasattr(conditional, '__UNSAFE__'):
|
|
|
|
disable_lookups = True
|
2016-12-13 17:14:47 +00:00
|
|
|
|
2015-12-19 17:49:06 +00:00
|
|
|
presented = "{%% if %s %%} True {%% else %%} False {%% endif %%}" % conditional
|
2017-01-10 22:54:00 +00:00
|
|
|
val = templar.template(presented, disable_lookups=disable_lookups).strip()
|
2015-12-19 17:49:06 +00:00
|
|
|
if val == "True":
|
|
|
|
return True
|
|
|
|
elif val == "False":
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
raise AnsibleError("unable to evaluate conditional: %s" % original)
|
|
|
|
except (AnsibleUndefinedVariable, UndefinedError) as e:
|
2016-11-21 22:57:27 +00:00
|
|
|
# the templating failed, meaning most likely a variable was undefined. If we happened to be
|
|
|
|
# looking for an undefined variable, return True, otherwise fail
|
|
|
|
try:
|
|
|
|
# first we extract the variable name from the error message
|
|
|
|
var_name = re.compile(r"'(hostvars\[.+\]|[\w_]+)' is undefined").search(str(e)).groups()[0]
|
|
|
|
# next we extract all defined/undefined tests from the conditional string
|
|
|
|
def_undef = self.extract_defined_undefined(conditional)
|
|
|
|
# then we loop through these, comparing the error variable name against
|
|
|
|
# each def/undef test we found above. If there is a match, we determine
|
|
|
|
# whether the logic/state mean the variable should exist or not and return
|
|
|
|
# the corresponding True/False
|
|
|
|
for (du_var, logic, state) in def_undef:
|
|
|
|
# when we compare the var names, normalize quotes because something
|
|
|
|
# like hostvars['foo'] may be tested against hostvars["foo"]
|
|
|
|
if var_name.replace("'", '"') == du_var.replace("'", '"'):
|
|
|
|
# the should exist is a xor test between a negation in the logic portion
|
|
|
|
# against the state (defined or undefined)
|
|
|
|
should_exist = ('not' in logic) != (state == 'defined')
|
|
|
|
if should_exist:
|
|
|
|
return False
|
|
|
|
else:
|
|
|
|
return True
|
|
|
|
# as nothing above matched the failed var name, re-raise here to
|
|
|
|
# trigger the AnsibleUndefinedVariable exception again below
|
|
|
|
raise
|
|
|
|
except Exception as new_e:
|
2016-11-14 22:29:13 +00:00
|
|
|
raise AnsibleUndefinedVariable("error while evaluating conditional (%s): %s" % (original, e))
|
2014-10-02 17:07:05 +00:00
|
|
|
|