@ -27,6 +27,7 @@ import shlex
import re
import ast
class InventoryParser ( object ) :
"""
Host inventory for ansible .
@ -47,7 +48,6 @@ class InventoryParser(object):
self . _parse_group_variables ( )
return self . groups
# [webservers]
# alpha
# beta:2345
@ -65,7 +65,34 @@ class InventoryParser(object):
active_group_name = ' ungrouped '
for line in self . lines :
line = line . split ( " # " ) [ 0 ] . strip ( )
# Split off any comments that are not contained in a variable.
if " # " in line :
split_line = line . split ( " # " )
instances = len ( split_line ) - 1
if instances > 0 :
marker = 0
while marker < instances :
if ( " = \" " in split_line [ marker ] and " \" " in split_line [ marker + 1 ] ) or (
" = ' " in split_line [ marker ] and " ' " in split_line [ marker + 1 ] ) :
marker + = 1
else :
if marker == 0 :
line = split_line [ marker ]
else :
# We have multiple fragments that we need to combine back together.
# rekram is us reversing that work we did with marker.
rekram = 0
new_line = split_line [ rekram ]
while marker > rekram :
rekram + = 1
new_line = new_line + " # " + split_line [ rekram ]
line = new_line
break
# Clean up the end of the line.
line = line . strip ( )
if line . startswith ( " [ " ) and line . endswith ( " ] " ) :
active_group_name = line . replace ( " [ " , " " ) . replace ( " ] " , " " )
if line . find ( " :vars " ) != - 1 or line . find ( " :children " ) != - 1 :
@ -101,14 +128,12 @@ class InventoryParser(object):
( hostname . find ( " ] " ) == - 1 and hostname . find ( " : " ) != - 1 ) ) :
( hostname , port ) = hostname . rsplit ( " : " , 1 )
hostnames = [ ]
if detect_range ( hostname ) :
hostnames = expand_hostname_range ( hostname )
else :
hostnames = [ hostname ]
for hn in hostnames :
host = None
if hn in self . hosts :
host = self . hosts [ hn ]
else :
@ -122,11 +147,20 @@ class InventoryParser(object):
( k , v ) = t . split ( " = " , 1 )
except ValueError , e :
raise errors . AnsibleError ( " Invalid ini entry: %s - %s " % ( t , str ( e ) ) )
# I am not sure where a variable with a hash needs to be evaluated via ast.
# If an instance comes up this is the condition we need to modify.
if " # " in v :
host . set_variable ( k , v )
else :
try :
host . set_variable ( k , ast . literal_eval ( v ) )
except :
# most likely a string that literal_eval
# doesn't like, so just set it
# Using explicit exceptions.
# Likely a string that literal_eval does not like. We wil then just set it.
except ValueError :
# For some reason this was thought to be malformed.
host . set_variable ( k , v )
except SyntaxError :
# Is this a hash with an equals at the end?
host . set_variable ( k , v )
self . groups [ active_group_name ] . add_host ( host )
@ -157,7 +191,6 @@ class InventoryParser(object):
else :
group . add_child_group ( kid_group )
# [webservers:vars]
# http_port=1234
# maxRequestsPerChild=200