2020-10-14 18:06:28 +02:00
from pyexecplugins . pyexecplugins import PyExecPlugin
import tempfile
import json
2020-11-16 17:48:27 +01:00
import logging
2020-10-14 18:06:28 +02:00
import subprocess
2020-11-16 17:48:27 +01:00
from subprocess import PIPE
2020-10-14 18:06:28 +02:00
class Plugin ( PyExecPlugin ) :
name = " Packer "
taskdef = {
" name " : " pypacker " ,
" retryCount " : 0 ,
" description " : " Executes packer.io command line for build and validate. It has been isolated in order to be able to start the worker only where OS dependencies are matched. " ,
" inputKeys " : [ " command " , " template " ] ,
" outputKeys " : [ " results " ] ,
" ownerEmail " : " m.lettere@gmail.com "
}
def __init__ ( self , data = None ) :
super ( ) . __init__ ( data )
self . template = data [ " template " ]
self . command = data . get ( " command " , " build " )
2021-03-22 11:43:41 +01:00
self . extra_vars = data . get ( " extra_vars " , { } )
2020-10-14 18:06:28 +02:00
def execute ( self ) :
2020-11-16 17:48:27 +01:00
fp = tempfile . NamedTemporaryFile ( mode = " w " , delete = False , encoding = ' utf-8 ' )
logging . getLogger ( " pyexec " ) . debug ( " Going to %s template %s " , self . command , self . data )
json . dump ( self . template , fp )
2020-10-14 18:06:28 +02:00
fp . close ( )
2021-03-22 11:43:41 +01:00
cmd = [ " packer " , self . command ]
for k in self . extra_vars :
cmd . append ( " -var " )
cmd . append ( k + " = " + self . extra_vars . get ( k ) )
cmd . append ( fp . name )
logging . getLogger ( " pyexec " ) . debug ( " Packer command is %s " , cmd )
2020-11-16 17:48:27 +01:00
try :
completed = subprocess . run ( cmd , capture_output = True , text = True )
except Exception as e :
completed = subprocess . run ( cmd , stdout = PIPE , stderr = PIPE )
logging . getLogger ( " pyexec " ) . debug ( " Packer outcome is %s " , completed )
2020-10-14 18:06:28 +02:00
if ( completed . returncode != 0 ) :
raise Exception ( " packer.io failed: {} - out: {} - err: {} " . format (
completed . returncode ,
completed . stdout if completed . stdout != None else " " ,
completed . stderr if completed . stderr != None else " " )
)
return {
' results ' : [
{
' returncode ' : completed . returncode ,
2020-11-16 17:48:27 +01:00
' stdout ' : str ( completed . stdout ) ,
' stderr ' : str ( completed . stderr )
2020-10-14 18:06:28 +02:00
}
]
}