others/ec2_ami_parser.py
author Paul Tonelli <paul.tonelli@logilab.fr>
Tue, 12 Mar 2013 11:51:26 +0100
changeset 66 23a31e4cbb65
parent 60 ea9ba2e759fc
child 68 601c145e6326
permissions -rw-r--r--
the scripts now cleans the ssh keys if present as well as the apt cache

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# author: Paul Tonelli <ptonelli@logilab.fr>

import urllib, os
from time import sleep
from salt import grains
from sys import argv
from subprocess import Popen

url = 'http://169.254.169.254/2008-02-01/user-data'

def parse_line(line):
    '''
    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 line.startswith('address:'):
        #grains.present(name='custom_hg_address', value=line)
        Popen(['salt-call', 'state.single', 'grains.present',
            'name=ami_hg_address', 'value=' +
            line.split(':',1)[-1].lstrip().rstrip()])
    elif line.startswith('rev:') or line.startswith('revision:') :
        Popen(['salt-call', 'state.single', 'grains.present',
            'name=ami_hg_revision', 'value=' + line.split(':',1)[-1].lstrip().rstrip()])
    elif line.startswith('origin:'):
        Popen(['salt-call', 'state.single', 'grains.present',
            'name=ami_origin', 'value=' + line.split(':',1)[-1].lstrip().rstrip()])
    sleep(1)

if __name__ == "__main__":
    os.chdir('/tmp')
    if len(argv)>1: #we have a filename, no need to download it
        myfile = open(argv[1],'r')
    else:
        myfile = open(urllib.urlretrieve(url)[0],'r')
    for line in myfile:
        parse_line(line)