From 4e9a9706165ee01bc2f5d700dbcbddb051ed8c4e Mon Sep 17 00:00:00 2001 From: Dag Wieers Date: Mon, 24 Sep 2012 21:06:34 +0200 Subject: [PATCH] Add an only_if option to vars_prompt to make prompts conditional Sometimes you may want to allow variables through host_vars or inventory, but prompt for a value if it is not set or if the value does not conform to something specific. This option allows you to specify when you want to offer a prompt. This patch also moves check_conditional to utils, and adds an is_unset() function which is nicer to read: only_if: "not is_set('${var}')" vs only_if: "is_unset('${var}')" --- lib/ansible/playbook/play.py | 4 +++- lib/ansible/runner/__init__.py | 6 +----- lib/ansible/utils.py | 7 +++++++ 3 files changed, 11 insertions(+), 6 deletions(-) diff --git a/lib/ansible/playbook/play.py b/lib/ansible/playbook/play.py index e2b57064e7b..4e53449d61e 100644 --- a/lib/ansible/playbook/play.py +++ b/lib/ansible/playbook/play.py @@ -172,8 +172,10 @@ class Play(object): encrypt = var.get("encrypt", None) salt_size = var.get("salt_size", None) salt = var.get("salt", None) + conditional = var.get("only_if", 'True') - vars[vname] = self.playbook.callbacks.on_vars_prompt(vname, private, prompt,encrypt, confirm, salt_size, salt) + if utils.check_conditional(conditional): + vars[vname] = self.playbook.callbacks.on_vars_prompt(vname, private, prompt,encrypt, confirm, salt_size, salt) elif type(self.vars_prompt) == dict: for (vname, prompt) in self.vars_prompt.iteritems(): diff --git a/lib/ansible/runner/__init__.py b/lib/ansible/runner/__init__.py index 1c3977e86b0..328661ddc5e 100644 --- a/lib/ansible/runner/__init__.py +++ b/lib/ansible/runner/__init__.py @@ -329,12 +329,8 @@ class Runner(object): self.module_args = new_args self.module_args = utils.template(self.basedir, self.module_args, inject) - def _check_conditional(conditional): - def is_set(var): - return not var.startswith("$") - return eval(conditional) conditional = utils.template(self.basedir, self.conditional, inject) - if not _check_conditional(conditional): + if not utils.check_conditional(conditional): result = utils.jsonify(dict(skipped=True)) self.callbacks.on_skipped(host, inject.get('item',None)) return ReturnData(host=host, result=result) diff --git a/lib/ansible/utils.py b/lib/ansible/utils.py index 6fefd091640..2e81a5db957 100644 --- a/lib/ansible/utils.py +++ b/lib/ansible/utils.py @@ -93,6 +93,13 @@ def is_failed(result): return ((result.get('rc', 0) != 0) or (result.get('failed', False) in [ True, 'True', 'true'])) +def check_conditional(conditional): + def is_set(var): + return not var.startswith("$") + def is_unset(var): + return var.startswith("$") + return eval(conditional) + def prepare_writeable_dir(tree): ''' make sure a directory exists and is writeable '''