1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2024-09-14 20:13:21 +02:00

Add an additional way to dereference a variable in a playbook, $foo

(Using varReplace function originally from yum, thanks Seth)
This commit is contained in:
Michael DeHaan 2012-03-19 19:32:38 -04:00
parent af9596307d
commit 5ed2b894d9
3 changed files with 39 additions and 6 deletions

View file

@ -20,6 +20,7 @@
import sys import sys
import os import os
import shlex import shlex
import re
import jinja2 import jinja2
try: try:
@ -224,8 +225,41 @@ def parse_json(data):
return { "failed" : True, "parsed" : False, "msg" : data } return { "failed" : True, "parsed" : False, "msg" : data }
return results 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): def template(text, vars):
''' run a text buffer through the templating engine ''' ''' run a text buffer through the templating engine '''
text = varReplace(text, vars)
template = jinja2.Template(text) template = jinja2.Template(text)
return template.render(vars) return template.render(vars)

View file

@ -52,7 +52,7 @@
[ [
"task start", "task start",
[ [
"test basic shell", "test basic shell, plus two ways to dereference a variable",
false false
] ]
], ],
@ -61,10 +61,10 @@
[ [
"127.0.0.1", "127.0.0.1",
{ {
"cmd": "echo $HOME ", "cmd": "echo $HOME 5150 5150 ",
"rc": 0, "rc": 0,
"stderr": "", "stderr": "",
"stdout": "/root" "stdout": "/root 5150 5150"
} }
] ]
], ],
@ -200,4 +200,3 @@
} }
} }
} }

View file

@ -13,8 +13,8 @@
- name: test basic success command 2 - name: test basic success command 2
action: command /bin/true action: command /bin/true
- name: test basic shell - name: test basic shell, plus two ways to dereference a variable
action: shell echo $HOME action: shell echo $HOME $port {{ port }}
# in the command below, the test file should contain a valid template # in the command below, the test file should contain a valid template
# and trigger the change handler # and trigger the change handler