-
Notifications
You must be signed in to change notification settings - Fork 0
/
packer
executable file
·185 lines (133 loc) · 5.06 KB
/
packer
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
#!/usr/bin/env python
import argparse
import errno
import getpass
import os
import shutil
import re
import subprocess
import sys
import urllib
import tarfile
import json
from pprint import pprint, pformat
from yaml import dump, load
try:
from yaml import CLoader as Loader, CDumper as Dumper
except ImportError:
from yaml import Loader, Dumper
colors = {
'black': 0,
'red': 1,
'green': 2,
'yellow': 3,
'blue': 4,
'magenta': 5,
'cyan': 6,
'white': 7,
'default': 9
}
styles = {'normal': 0, 'bold': 1, 'light': 2, 'inverse': 3, 'underline': 4}
def main():
parser = argparse.ArgumentParser(description='packer builder wrapper')
parser.add_argument(
'template',
type=str,
metavar='packer template',
help='packer template to build')
parser.add_argument(
'--verbose', '-v', action='count', help='set output verbosity')
args = parser.parse_args()
root_dir = os.path.dirname(os.path.abspath(__file__))
configfile = 'config.yml'
if not os.path.exists(configfile):
configfile = configfile + '.dist'
config = load(file(configfile))
templates_config = load(file(root_dir+'/templates.yml'))
templates = templates_config['templates']
if args.template not in templates:
print colorize('{} is not in templates list', 'red').format(args.template)
sys.exit(1)
build_template(args.template, templates[args.template], config, root_dir)
def build_template(template_name, template, config, root_dir):
template_dir = os.path.join(root_dir, template_name)
box_dir = os.path.join(root_dir, 'box')
build_dir = os.path.join(root_dir, 'build', template_name)
if not os.path.exists(build_dir):
os.makedirs(build_dir)
template_type = template.get('type', 'virtualbox-iso')
box_name = template.get('name', template_name)
box_version = template.get('version', '0.0.1')
box_filename = "{}_{}.box".format(box_name, box_version)
if template_type == 'virtualbox-ovf':
ovf = download_box(template['box'], box_dir)
os.chdir(template_dir)
varsfile = template_dir+'/vars.json'
with open(varsfile, 'w') as f:
varsconfig = dict(config.items() + template.get('vars', {}).items())
varsconfig['box_name'] = box_name
varsconfig['box_version'] = box_version
varsconfig['box_description'] = template.get('description', '')
if ovf :
varsconfig['box_source_path'] = ovf
f.write(json.dumps(varsconfig, sort_keys=True, indent=2, separators=(',', ': ')))
packer_output_dir = os.path.join(template_dir, 'output-'+template_type)
if os.path.exists(packer_output_dir):
shutil.rmtree(packer_output_dir, True)
cmd = ['packer', 'build', '--only=' + template_type, '-var-file=' + varsfile, 'packer.json']
if shellpipe(cmd) == 0:
box_path = os.path.join(template_dir, box_filename)
box_final_path = os.path.join(build_dir, box_filename)
if os.path.exists(box_final_path):
os.remove(box_final_path)
if os.path.exists(box_path):
print "box saved to {}".format(box_final_path)
shutil.move(box_path, build_dir)
if os.path.exists(packer_output_dir):
shutil.rmtree(packer_output_dir, True)
os.chdir(root_dir)
def download_box(box_infos, box_dir):
target_dir = os.path.join(box_dir, box_infos.get('name', 'box'), box_infos.get('version', ''))
box = target_dir+'/virtualbox.box'
ovf = target_dir+'/box.ovf'
if not os.path.exists(target_dir):
os.makedirs(target_dir)
if not os.path.exists(box):
shellpipe(['wget', '-O', box, box_infos['url']])
if not os.path.exists(ovf):
shellpipe(['tar', '-C', target_dir, '-xf', box])
return ovf
def shell(cmd, cwd=None, verbose=0):
try:
if (verbose > 0):
print 'running ' + colorize(' '.join(cmd), 'yellow')
out = subprocess.check_output(
cmd, cwd=cwd, universal_newlines=True, stderr=subprocess.STDOUT)
return out, 0
except subprocess.CalledProcessError as e:
return e.output, e.returncode
def shellpipe(cmd):
print 'running ' + colorize(' '.join(cmd), 'yellow')
process = subprocess.Popen(cmd, stdout=subprocess.PIPE)
while True:
output = process.stdout.readline()
if output == '' and process.poll() is not None:
break
if output:
print output.strip()
rc = process.poll()
return rc
def colorize(text, color='default', style='normal', background='default'):
return '{}{}{}'.format(
get_color(color, style, background), text, get_color('reset'))
def get_color(color='default', style='normal', background='default'):
if color == 'reset':
style = 'normal'
seq = [str(styles[style])]
if color in colors and color != 'reset':
seq.append('3' + str(colors[color]))
if background in colors and color != 'reset':
seq.append('4' + str(colors[background]))
return "\033[{}m".format(';'.join(seq))
if __name__ == '__main__':
main()