github.com/raghuse92/packer@v1.3.2/post-processor/docker-save/post-processor.go (about)

     1  package dockersave
     2  
     3  import (
     4  	"fmt"
     5  	"os"
     6  
     7  	"github.com/hashicorp/packer/builder/docker"
     8  	"github.com/hashicorp/packer/common"
     9  	"github.com/hashicorp/packer/helper/config"
    10  	"github.com/hashicorp/packer/packer"
    11  	"github.com/hashicorp/packer/post-processor/docker-import"
    12  	"github.com/hashicorp/packer/post-processor/docker-tag"
    13  	"github.com/hashicorp/packer/template/interpolate"
    14  )
    15  
    16  const BuilderId = "packer.post-processor.docker-save"
    17  
    18  type Config struct {
    19  	common.PackerConfig `mapstructure:",squash"`
    20  
    21  	Path string `mapstructure:"path"`
    22  
    23  	ctx interpolate.Context
    24  }
    25  
    26  type PostProcessor struct {
    27  	Driver docker.Driver
    28  
    29  	config Config
    30  }
    31  
    32  func (p *PostProcessor) Configure(raws ...interface{}) error {
    33  	err := config.Decode(&p.config, &config.DecodeOpts{
    34  		Interpolate:        true,
    35  		InterpolateContext: &p.config.ctx,
    36  		InterpolateFilter: &interpolate.RenderFilter{
    37  			Exclude: []string{},
    38  		},
    39  	}, raws...)
    40  	if err != nil {
    41  		return err
    42  	}
    43  
    44  	return nil
    45  
    46  }
    47  
    48  func (p *PostProcessor) PostProcess(ui packer.Ui, artifact packer.Artifact) (packer.Artifact, bool, error) {
    49  	if artifact.BuilderId() != dockerimport.BuilderId &&
    50  		artifact.BuilderId() != dockertag.BuilderId {
    51  		err := fmt.Errorf(
    52  			"Unknown artifact type: %s\nCan only save Docker builder artifacts.",
    53  			artifact.BuilderId())
    54  		return nil, false, err
    55  	}
    56  
    57  	path := p.config.Path
    58  
    59  	// Open the file that we're going to write to
    60  	f, err := os.Create(path)
    61  	if err != nil {
    62  		err := fmt.Errorf("Error creating output file: %s", err)
    63  		return nil, false, err
    64  	}
    65  
    66  	driver := p.Driver
    67  	if driver == nil {
    68  		// If no driver is set, then we use the real driver
    69  		driver = &docker.DockerDriver{Ctx: &p.config.ctx, Ui: ui}
    70  	}
    71  
    72  	ui.Message("Saving image: " + artifact.Id())
    73  
    74  	if err := driver.SaveImage(artifact.Id(), f); err != nil {
    75  		f.Close()
    76  		os.Remove(f.Name())
    77  
    78  		return nil, false, err
    79  	}
    80  
    81  	f.Close()
    82  	ui.Message("Saved to: " + path)
    83  
    84  	return artifact, true, nil
    85  }