#xiaorui. cc
Import Base64
Import JSON
Import Os.path
Import Yaml
Import types
Import Pipes
Import Glob
Import re
Import operator as Py_operator
From ansible Import Errors
From ansible.utils import md5s
From distutils.version import looseversion, strictversion
From random import Systemrandom
From jinja2.filters import Environmentfilter
def to_nice_yaml (*a, **kw):
' Make verbose, human readable yaml '
Return Yaml.safe_dump (*a, indent=4, Allow_unicode=true, Default_flow_style=false, **kw)
Def To_json (A, *args, **kw):
"Convert the value to JSON" "
Return Json.dumps (A, *args, **kw)
Def To_nice_json (A, *args, **kw):
' Make verbose, human readable JSON '
Return Json.dumps (A, indent=4, Sort_keys=true, *args, **kw)
Def failed (*a, **kw):
' Test If task result yields failed '
item = a[0]
If Type (item)!= dict:
Raise errors. Ansiblefiltererror ("|failed expects a dictionary")
rc = item.get (' RC ', 0)
Failed = Item.get (' failed ', False)
If RC!= 0 or failed:
Return True
Else
Return False
def success (*a, **kw):
' Test If task result yields success '
Return not failed (*a, **kw)
def changed (*a, **kw):
' Test If task result yields changed '
item = a[0]
If Type (item)!= dict:
Raise errors. Ansiblefiltererror ("|changed expects a dictionary")
If not ' changed ' in item:
Changed = False
if (' Results ' in Item # Some modules return a ' results ' key
and type (item[' results ']) = = List
and type (item[' results '][0]) = = Dict):
For result in item[' results ']:
Changed = changed or Result.get (' changed ', False)
Else
Changed = Item.get (' changed ', False)
Return changed
def skipped (*a, **kw):
' Test If task result yields skipped '
item = a[0]
If Type (item)!= dict:
Raise errors. Ansiblefiltererror ("|skipped expects a dictionary")
skipped = Item.get (' skipped ', False)
Return skipped
def mandatory (a):
' Make a variable mandatory '
Try
A
Except Nameerror:
Raise errors. Ansiblefiltererror (' mandatory variable not defined. ')
Else
Return a
def bool (a):
' Return a bool to the ARG '
If a is None or type (a) = = bool:
Return a
If type (a) in types. Stringtypes:
A = A.lower ()
If a in [' Yes ', ' on ', ' 1 ', ' true ', 1]:
Return True
Else
Return False
DEF quote (a):
"' return it argument quoted for shell usage '"
Return Pipes.quote (a)
def fileglob (pathname):
' Return list of matched files for Glob '
return Glob.glob (pathname)
def regex (value= ', pattern= ', Ignorecase=false, match_type= ' search '):
' Expose ' re ' as a Boolean filter using the ' Search ' method by default.
This is likely only useful for ' search ' and ' match ' which already
have their own filters.
'''
If ignorecase:
Flags = Re. I
Else
Flags = 0
_re = Re.compile (pattern, flags=flags)
_bool = __builtins__.get (' bool ')
Return _bool (GetAttr (_re, Match_type, ' Search ') (value)
Def match (value, pattern= ', ignorecase=false):
' Perform a ' re.match ' returning a Boolean '
return Regex (value, pattern, ignorecase, ' match ')
def search (value, pattern= ', ignorecase=false):
' Perform a ' re.search ' returning a Boolean '
return Regex (value, pattern, ignorecase, ' search ')
def regex_replace (value= ', pattern= ', replacement= ', ignorecase=false):
' Perform a ' re.sub ' returning a string '
If not isinstance (value, basestring):
Value = str (value)
If ignorecase:
Flags = Re. I
Else
Flags = 0
_re = Re.compile (pattern, flags=flags)
Return _re.sub (replacement, value)
def unique (a):
return set (a)
def intersect (A, B):
return set (a). Intersection (b)
def difference (A, B):
return set (a). Difference (b)
Def symmetric_difference (A, B):
return set (a). Symmetric_difference (b)
Def union (A, B):
return set (a). Union (b)
def version_compare (value, version, operator= ' eq ', strict=false):
"' Perform a version comparison on a value '"
Op_map = {
' = = ': ' eq ', ' = ': ' eq ', ' welfare ': ' eq ',
' < ': ' lt ', ' lt ': ' Lt ',
' <= ': ' Le ', ' le ': ' Le ',
' > ': ' GT ', ' GT ': ' GT ',
' >= ': ' ge ', ' ge ': ' ge ',
'!= ': ' ne ', ' <> ': ' ne ', ' ne ': ' ne '
}
If strict:
Version = Strictversion
Else
Version = Looseversion
If operator in Op_map:
operator = Op_map[operator]
Else
Raise errors. Ansiblefiltererror (' Invalid operator type ')
Try
method = GetAttr (Py_operator, operator)
Return method (Version (str (value)), Version (str (version))
Except Exception, E:
Raise errors. Ansiblefiltererror (' Version comparison:%s '% e)
@environmentfilter
def rand (Environment, end, Start=none, Step=none):
R = Systemrandom ()
If Isinstance (end, (int, long)):
If not start:
Start = 0
If not step:
Step = 1
Return R.randrange (Start, end, step)
Elif hasattr (end, ' __iter__ '):
If Start or step:
Raise errors. Ansiblefiltererror (' Start and step can ' is used with integer values ')
return R.choice (end)
Else
Raise errors. Ansiblefiltererror (' Random can is used on sequences and integers ')
Class Filtermodule (object):
"' Ansible core jinja2 filters '"
def filters (self):
return {
# Base 64
' B64decode ': Base64.b64decode,
' B64encode ': Base64.b64encode,
# JSON
' To_json ': To_json,
' To_nice_json ': To_nice_json,
' From_json ': json.loads,
# YAML
' To_yaml ': Yaml.safe_dump,
' To_nice_yaml ': To_nice_yaml,
' From_yaml ': yaml.safe_load,
# path
' basename ': Os.path.basename,
' DirName ': Os.path.dirname,
' Expanduser ': Os.path.expanduser,
' Realpath ': Os.path.realpath,
' RelPath ': Os.path.relpath,
# Failure Testing
' Failed ': failed,
' Success ': Success,
# changed testing
' Changed ': Changed,
# Skip Testing
' Skipped ': Skipped,
# variable existence
' Mandatory ': mandatory,
# Value As Boolean
' BOOL ': bool,
# Quote string for Shell usage
' Quote ': quote,
# MD5 Hex Digest of string
' MD5 ': md5s,
# file Glob
' Fileglob ': Fileglob,
# regex
' Match ': match,
' Search ': Search,
' Regex ': Regex,
' Regex_replace ': regex_replace,
# list
' Unique ': unique,
' intersect ': intersect,
' Difference ': difference,
' Symmetric_difference ': symmetric_difference,
' Union ': union,
# version Comparison
' Version_compare ': Version_compare,
# random Numbers
' Random ': Rand,
}
|