~michael.nelson/charms/trusty/logstash/trunk

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#!/usr/bin/env python

import logging
import os
import shutil
from jinja2 import Template
import argparse

logging.basicConfig(level=logging.INFO)


class TemplateWiz:

    def __init__(self, args=None):
        self.values = {}
        parser = argparse.ArgumentParser()
        parser.add_argument("-t", "--template", help="Template Path")
        parser.add_argument("-o", "--output", help="Fullpath to output file")
        parser.add_argument("-O", "--overwrite", help="Overwrite file",
                            action='store_true')
        self.paths, data = parser.parse_known_args(args)
        if data:
        # Process key = value keys
            for item in data:
                kv = item.split('=')
                self.values[kv[0]] = kv[-1]

    def read_template(self):
        if not os.path.exists(self.paths.template):
            raise IOError("Error loading template: %s" % self.paths.template)
        else:
            with open(self.paths.template, 'r') as f:
                self.template = Template(f.read())

    def write_template(self):
        if os.path.exists(self.paths.output) and self.paths.overwrite is False:
            shutil.copy2(self.paths.output, "%s.bak" % self.paths.output)
            logging.info("Saving {f} as {f}.bak".format(f=self.paths.output))
        with open(self.paths.output, 'w+') as f:
            f.write(self.template.render(self.values))
            logging.info('Rendered %s' % self.paths.output)

    def run(self):
        self.read_template()
        self.write_template()


if __name__ == "__main__":
    tw = TemplateWiz()
    tw.run()