From 5ed2b894d9344ae10ecea37f1376dae00b3d15e3 Mon Sep 17 00:00:00 2001 From: Michael DeHaan Date: Mon, 19 Mar 2012 19:32:38 -0400 Subject: [PATCH] Add an additional way to dereference a variable in a playbook, $foo (Using varReplace function originally from yum, thanks Seth) --- lib/ansible/utils.py | 34 ++++++++++++++++++++++++++++++++++ test/playbook1.events | 7 +++---- test/playbook1.yml | 4 ++-- 3 files changed, 39 insertions(+), 6 deletions(-) diff --git a/lib/ansible/utils.py b/lib/ansible/utils.py index 396f63298d0..28aa69ccf86 100755 --- a/lib/ansible/utils.py +++ b/lib/ansible/utils.py @@ -20,6 +20,7 @@ import sys import os import shlex +import re import jinja2 try: @@ -224,8 +225,41 @@ def parse_json(data): return { "failed" : True, "parsed" : False, "msg" : data } return results +_KEYCRE = re.compile(r"\$(\w+)") + +def varReplace(raw, vars): + '''Perform variable replacement of $vars + + @param raw: String to perform substitution on. + @param vars: Dictionary of variables to replace. Key is variable name + (without $ prefix). Value is replacement string. + @return: Input raw string with substituted values. + ''' + # this code originally from yum + + done = [] # Completed chunks to return + + while raw: + m = _KEYCRE.search(raw) + if not m: + done.append(raw) + break + + # Determine replacement value (if unknown variable then preserve + # original) + varname = m.group(1).lower() + replacement = vars.get(varname, m.group()) + + start, end = m.span() + done.append(raw[:start]) # Keep stuff leading up to token + done.append(replacement) # Append replacement value + raw = raw[end:] # Continue with remainder of string + + return ''.join(done) + def template(text, vars): ''' run a text buffer through the templating engine ''' + text = varReplace(text, vars) template = jinja2.Template(text) return template.render(vars) diff --git a/test/playbook1.events b/test/playbook1.events index 9a0a2a82f8b..9fdf1912b60 100644 --- a/test/playbook1.events +++ b/test/playbook1.events @@ -52,7 +52,7 @@ [ "task start", [ - "test basic shell", + "test basic shell, plus two ways to dereference a variable", false ] ], @@ -61,10 +61,10 @@ [ "127.0.0.1", { - "cmd": "echo $HOME ", + "cmd": "echo $HOME 5150 5150 ", "rc": 0, "stderr": "", - "stdout": "/root" + "stdout": "/root 5150 5150" } ] ], @@ -200,4 +200,3 @@ } } } - diff --git a/test/playbook1.yml b/test/playbook1.yml index d1f6b2902c1..d214b67a200 100644 --- a/test/playbook1.yml +++ b/test/playbook1.yml @@ -13,8 +13,8 @@ - name: test basic success command 2 action: command /bin/true - - name: test basic shell - action: shell echo $HOME + - name: test basic shell, plus two ways to dereference a variable + action: shell echo $HOME $port {{ port }} # in the command below, the test file should contain a valid template # and trigger the change handler