convert ami_parser to ConfigParser python library instead of specific parsing
authorPaul Tonelli <paul.tonelli@logilab.fr>
Mon, 15 Apr 2013 14:54:19 +0200
changeset 114 79ef182dcc5e
parent 113 e274a7faca62
child 115 063b9cbe5aa1
convert ami_parser to ConfigParser python library instead of specific parsing
others/ec2_ami_parser.py
--- a/others/ec2_ami_parser.py	Mon Apr 15 16:32:35 2013 +0200
+++ b/others/ec2_ami_parser.py	Mon Apr 15 14:54:19 2013 +0200
@@ -7,21 +7,33 @@
 from salt import grains
 from sys import argv
 from subprocess import Popen
+import ConfigParser
 
 url = 'http://169.254.169.254/2008-02-01/user-data'
 
-def parse_line(line):
+def add_grain(pair):
     '''
     ugly, but did not find how to do it more cleanly
 
     from salt.modules import state
     state.highstate() #does not work and requires __salt__ dict
     '''
-    line = line.rsplit('#')[0].lstrip().rstrip()
-    if ':' in line:
+    if isinstance(pair[1],list) and len(pair[1]) > 0:
+        pair=(pair[0],pair[1][0])
+    if pair[1] != '':
         Popen(['salt-call', 'state.single', 'grains.present',
-            'name=' + line.split(':',1)[0].rstrip(), 'value=' + line.split(':',1)[-1].lstrip()])
-    sleep(1)
+            'name=' + pair[0], 'value=' + pair[1]])
+        sleep(1)
+
+class FakeSecHead(object):
+   def __init__(self, fp):
+     self.fp = fp
+     self.sechead = '[asection]\n'
+   def readline(self):
+     if self.sechead:
+       try: return self.sechead
+       finally: self.sechead = None
+     else: return self.fp.readline()
 
 if __name__ == "__main__":
     os.chdir('/tmp')
@@ -30,8 +42,18 @@
     else:
         myfile = open(urllib.urlretrieve(url)[0],'r')
     found_flag = False
-    for line in myfile:
+    while found_flag == False:
+        line = myfile.readline()
         if line.startswith("#salt-grains"):
             found_flag = True
-        if found_flag:
-            parse_line(line)
+        if line == '':
+            break
+    if found_flag:
+        config = ConfigParser.ConfigParser()
+        try:
+            config.readfp(FakeSecHead(myfile))
+        except ConfigParser.ParsingError:
+            pass
+        for item in config.items('asection'):
+            print item
+            add_grain(item)