11import sh
2+ import os
23
34__version__ = '0.0.1'
45
@@ -18,37 +19,49 @@ def __init__(self, packerfile, exc=None, only=None, vars=None,
1819 :param string vars_file: Path to variables file
1920 :param string exec_path: Path to Packer executable
2021 """
21- self .packerfile = packerfile
22- self .exc = exc if exc else []
23- self .only = only if only else []
24- self .vars = vars if vars else {}
22+ self .packerfile = self ._validate_argtype (packerfile , str )
2523 self .vars_file = vars_file
24+ if not os .path .isfile (self .packerfile ):
25+ raise OSError ('packerfile not found at path: {0}' .format (
26+ self .packerfile ))
27+ self .exc = self ._validate_argtype (exc if exc else [], list )
28+ self .only = self ._validate_argtype (only if only else [], list )
29+ self .vars = self ._validate_argtype (vars if vars else {}, dict )
30+ if not os .path .isfile (self .packerfile ):
31+ raise OSError ('packerfile not found at path: {0}' .format (
32+ self .packerfile ))
2633 self .packer = sh .Command (exec_path )
2734
28- def _append_base_arguments (self , cmd ):
29- """Add base arguments to packer commands.
35+ def _validate_argtype (self , arg , argtype ):
36+ if not isinstance (arg , argtype ):
37+ raise PackerException ('{0} argument must be of type {1}' .format (
38+ arg , argtype ))
39+ return arg
40+
41+ def _append_base_arguments (self , command ):
42+ """Appends base arguments to packer commands.
3043
3144 -except, -only, -var and -vars-file are appeneded to almost
3245 all subcommands in packer. As such this can be called to add
3346 these flags to the subcommand.
3447 """
3548 if self .exc and self .only :
3649 raise PackerException ('Cannot provide both "except" and "only"' )
37- if self .exc :
38- cmd = cmd .bake ('-except={0}' .format (self ._joinc (self .exc )))
39- if self .only :
40- cmd = cmd .bake ('-only={0}' .format (self ._joinc (self .only )))
41- for var , value in self .vars .iteritems ():
42- cmd = cmd .bake ("-var '{0}={1}'" .format (var , value ))
50+ elif self .exc :
51+ command = command .bake ('-except={0}' .format (self ._joinc (self .exc )))
52+ elif self .only :
53+ command = command .bake ('-only={0}' .format (self ._joinc (self .only )))
54+ for var , value in self .vars .items ():
55+ command = command .bake ("-var '{0}={1}'" .format (var , value ))
4356 if self .vars_file :
44- cmd = cmd .bake ('-vars-file={0}' .format (self .vars_file ))
45- return cmd
57+ command = command .bake ('-vars-file={0}' .format (self .vars_file ))
58+ return command
4659
4760 def _joinc (self , lst ):
4861 """Returns a comma delimited string from a list"""
4962 return str (',' .join (lst ))
5063
51- def _join (self , lst ):
64+ def _joins (self , lst ):
5265 """Returns a space delimited string from a list"""
5366 return str (' ' .join (lst ))
5467
@@ -69,35 +82,44 @@ def validate(self, syntax_only=False):
6982 :param bool syntax_only: Whether to validate the syntax only
7083 without validating the configuration itself.
7184 """
72- validator = self .packer .validate
85+ command = self .packer .validate
7386 if syntax_only :
74- validator = validator .bake ('-syntax-only' )
75- validator = self ._append_base_arguments (validator )
76- validator = validator .bake (self .packerfile )
77- validated = validator ()
87+ command = command .bake ('-syntax-only' )
88+ command = self ._append_base_arguments (command )
89+ command = command .bake (self .packerfile )
90+ return command ()
91+ # err.. need to return normal values with validation result
7892 # validated.succeeded = True if validated.exit_code == 0 else False
7993 # validated.failed = not validated.succeeded
80- return validated
8194
8295 def push (self , create = True , token = False ):
8396 """Implmenets the `packer push` function
97+
98+ UNTESTED!
8499 """
85- pusher = self .packer .push
100+ command = self .packer .push
86101 if create :
87- pusher = pusher .bake ('-create=true' )
102+ command = command .bake ('-create=true' )
88103 if token :
89- pusher = pusher .bake ('-token={0}' .format (token ))
90- pusher = pusher .bake (self .packerfile )
91- return pusher ()
104+ command = command .bake ('-token={0}' .format (token ))
105+ command = command .bake (self .packerfile )
106+ return command ()
92107
93108 def fix (self , to_file = None ):
94109 """Implements the `packer fix` function
95110 """
96- fixer = self .packer .fix
97- fixer = fixer .bake (self .packerfile )
111+ cmd = self .packer .fix
112+ cmd = cmd .bake (self .packerfile )
113+ result = cmd ()
98114 if to_file :
99- fixer = fixer .bake (' > {0}' .format (to_file ))
100- return fixer ()
115+ with open (to_file , 'w' ) as f :
116+ f .write (result .stdout )
117+ return result
118+
119+ def _add_opt (self , command , option ):
120+ if option :
121+ return command .bake (option )
122+ return command
101123
102124 def build (self , parallel = True , debug = False , force = False ):
103125 """Executes a Packer build (`packer build`)
@@ -106,16 +128,19 @@ def build(self, parallel=True, debug=False, force=False):
106128 :param bool debug: Run in debug mode
107129 :param bool force: Force artifact output even if exists
108130 """
109- builder = self .packer .build
110- if parallel :
111- builder = builder .bake ('-parallel=true' )
112- if debug :
113- builder = builder .bake ('-debug' )
114- if force :
115- builder = builder .bake ('-force' )
116- builder = self ._append_base_arguments (builder )
117- builder = builder .bake (self .packerfile )
118- return builder ()
131+ cmd = self .packer .build
132+ cmd = self ._add_opt (cmd , '-parallel=true' if parallel else None )
133+ cmd = self ._add_opt (cmd , '-debug' if debug else None )
134+ cmd = self ._add_opt (cmd , '-force' if force else None )
135+ # if parallel:
136+ # cmd = cmd.bake('-parallel=true')
137+ # if debug:
138+ # cmd = cmd.bake('-debug')
139+ # if force:
140+ # cmd = cmd.bake('-force')
141+ cmd = self ._append_base_arguments (cmd )
142+ cmd = cmd .bake (self .packerfile )
143+ return cmd ()
119144
120145 def inspect (self ):
121146 """Inspects a Packer Templates file (`packer inspect -machine-readable`)
@@ -145,12 +170,12 @@ def inspect(self):
145170 }
146171 ]
147172 """
148- inspector = self .packer .inspect
149- inspector = inspector .bake ('-machine-readable' , self .packerfile )
150- inspected = inspector ()
151- inspected .parsed_output = self ._parse_inspection_output (
152- inspected .stdout )
153- return inspected
173+ command = self .packer .inspect
174+ command = command .bake ('-machine-readable' , self .packerfile )
175+ result = command ()
176+ result .parsed_output = self ._parse_inspection_output (
177+ result .stdout )
178+ return result
154179
155180 def _parse_inspection_output (self , output ):
156181 """Parses the machine-readable output `packer inspect` provides.
@@ -176,5 +201,5 @@ def _parse_inspection_output(self, output):
176201 return parts
177202
178203
179- class PackerException ():
204+ class PackerException (Exception ):
180205 pass
0 commit comments