Ansible PHP Associative Array Filter
"""
Custom filter to take a hash and output a PHP associative array
"""
from __future__ import print_function
import json
from ansible import errors
SPACES_PER_NEST_LEVEL = 4
''' Define how many spaces should be involved in nesting '''
def _var_to_array (contents , nested = 0 ):
''' Takes a variable `contents` & converts to PHP content
:param contents: Variable contents
:type contents: dict|str
'''
whitespace1 = " " * (nested * SPACES_PER_NEST_LEVEL )
whitespace2 = " " * ((1 + nested ) * SPACES_PER_NEST_LEVEL )
if type (contents ) is dict :
return "array(\n {ws2}{array}\n {ws1})" .format (
array = ",\n {}" .format (whitespace2 ).join ([
"'{k}' => {v}" .format (
k = k ,
v = _var_to_array (v , nested + 1 ))
for k , v in contents .iteritems ()
]),
ws1 = whitespace1 ,
ws2 = whitespace2 )
elif type (contents ) is list :
return "array(\n {ws2}{array}\n {ws1})" .format (
array = ",\n {}" .format (whitespace2 ).join ([
_var_to_array (c , nested + 1 ) for c in contents
]),
ws1 = whitespace1 ,
ws2 = whitespace2 )
else :
return str (contents )
def to_php_array (contents , var_name = 'conf' ):
''' Takes the hash `contents` & converts to PHP associative array
:param contents: Variable contents
:type contents: dict
:param var_name: Variable name
:type var_name: str
'''
return "${var_name} = {contents};" .format (
var_name = var_name ,
contents = _var_to_array (contents ))
class FilterModule (object ):
''' A filter to output a hash to PHP code '''
def filters (self ):
return {
'to_php_array' : to_php_array ,
}
if __name__ == '__main__' :
print (to_php_array ({
'error_level' : 'ERROR_REPORTING_HIDE' ,
'redis_client_host' : "'1.2.3.4'" ,
'cache_prefix' : {
'default' : "'prod'" ,
},
'siblings' : [
"'john'" ,
"'paul'" ,
"'ringo'" ,
],
},
'conf' ))
drupal_conf :
siblings :
- john
- paul
- ringo
error_level : " ERROR_REPORTING_HIDE"
redis_client_host : " '1.2.3.4'"
cache_prefix :
default :
" 'prod'"
Template (settings.php.j2)
<?php
{{ drupal_conf | to_php_array ("conf " ) }}
<?php
$ conf = array (
'siblings ' => array (
'john ' ,
'paul ' ,
'ringo '
),
'error_level ' => ERROR_REPORTING_HIDE ,
'redis_client_host ' => '1.2.3.4 ' ,
'cache_prefix ' => array (
'default ' => 'prod '
)
);