@@ -724,7 +724,7 @@ func CalculateDependencies(stages []config.KanikoStage, opts *config.KanikoOptio
724724}
725725
726726// DoBuild executes building the Dockerfile
727- func DoBuild (opts * config.KanikoOptions ) (v1.Image , error ) {
727+ func DoBuild (opts * config.KanikoOptions ) (image v1.Image , retErr error ) {
728728 t := timing .Start ("Total Build Time" )
729729 digestToCacheKey := make (map [string ]string )
730730 stageIdxToDigest := make (map [int ]string )
@@ -792,6 +792,29 @@ func DoBuild(opts *config.KanikoOptions) (v1.Image, error) {
792792 }
793793 }
794794
795+ if opts .Cleanup {
796+ defer assignIfNil (& retErr , func () error {
797+ if err = util .DeleteFilesystem (); err != nil {
798+ return err
799+ }
800+ err = config .Cleanup ()
801+ if err != nil {
802+ return err
803+ }
804+ if opts .PreserveContext {
805+ if tarball == "" {
806+ return fmt .Errorf ("context snapshot is missing" )
807+ }
808+ _ , err := util .UnpackLocalTarArchive (tarball , config .RootDir )
809+ if err != nil {
810+ return fmt .Errorf ("failed to unpack context snapshot: %w" , err )
811+ }
812+ logrus .Info ("Context restored" )
813+ }
814+ return nil
815+ })
816+ }
817+
795818 for _ , stage := range kanikoStages {
796819 sb , err := newStageBuilder (
797820 args , opts , stage ,
@@ -859,21 +882,6 @@ func DoBuild(opts *config.KanikoOptions) (v1.Image, error) {
859882 if len (opts .Annotations ) > 0 {
860883 sourceImage = mutate .Annotations (sourceImage , opts .Annotations ).(v1.Image )
861884 }
862- if opts .Cleanup {
863- if err = util .DeleteFilesystem (); err != nil {
864- return nil , err
865- }
866- if opts .PreserveContext {
867- if tarball == "" {
868- return nil , fmt .Errorf ("context snapshot is missing" )
869- }
870- _ , err := util .UnpackLocalTarArchive (tarball , config .RootDir )
871- if err != nil {
872- return nil , fmt .Errorf ("failed to unpack context snapshot: %w" , err )
873- }
874- logrus .Info ("Context restored" )
875- }
876- }
877885 timing .DefaultRun .Stop (t )
878886 return sourceImage , nil
879887 }
@@ -919,6 +927,12 @@ func DoBuild(opts *config.KanikoOptions) (v1.Image, error) {
919927 return nil , err
920928}
921929
930+ func assignIfNil (dst * error , fn func () error ) {
931+ if err := fn (); err != nil && * dst == nil {
932+ * dst = err
933+ }
934+ }
935+
922936// filesToSave returns all the files matching the given pattern in deps.
923937// If a file is a symlink, it also returns the target file.
924938func filesToSave (deps []string ) ([]string , error ) {
0 commit comments