packer-cn/post-processor/docker-save/post-processor.go

89 lines
2.0 KiB
Go
Raw Normal View History

//go:generate mapstructure-to-hcl2 -type Config
2014-07-20 16:58:07 -04:00
package dockersave
import (
2019-03-22 09:56:02 -04:00
"context"
2014-07-20 16:58:07 -04:00
"fmt"
"os"
2017-04-04 16:39:01 -04:00
"github.com/hashicorp/packer/builder/docker"
"github.com/hashicorp/packer/common"
"github.com/hashicorp/packer/helper/config"
"github.com/hashicorp/packer/packer"
2019-03-22 09:56:02 -04:00
dockerimport "github.com/hashicorp/packer/post-processor/docker-import"
dockertag "github.com/hashicorp/packer/post-processor/docker-tag"
2017-04-04 16:39:01 -04:00
"github.com/hashicorp/packer/template/interpolate"
2014-07-20 16:58:07 -04:00
)
const BuilderId = "packer.post-processor.docker-save"
type Config struct {
common.PackerConfig `mapstructure:",squash"`
Path string `mapstructure:"path"`
ctx interpolate.Context
2014-07-20 16:58:07 -04:00
}
type PostProcessor struct {
Driver docker.Driver
config Config
}
func (p *PostProcessor) Configure(raws ...interface{}) error {
err := config.Decode(&p.config, &config.DecodeOpts{
Interpolate: true,
InterpolateContext: &p.config.ctx,
InterpolateFilter: &interpolate.RenderFilter{
Exclude: []string{},
},
}, raws...)
2014-07-20 16:58:07 -04:00
if err != nil {
return err
}
return nil
}
func (p *PostProcessor) PostProcess(ctx context.Context, ui packer.Ui, artifact packer.Artifact) (packer.Artifact, bool, bool, error) {
if artifact.BuilderId() != dockerimport.BuilderId &&
artifact.BuilderId() != dockertag.BuilderId {
2014-07-20 16:58:07 -04:00
err := fmt.Errorf(
"Unknown artifact type: %s\nCan only save Docker builder artifacts.",
artifact.BuilderId())
2019-04-02 19:51:58 -04:00
return nil, false, false, err
2014-07-20 16:58:07 -04:00
}
path := p.config.Path
// Open the file that we're going to write to
f, err := os.Create(path)
if err != nil {
err := fmt.Errorf("Error creating output file: %s", err)
2019-04-02 19:51:58 -04:00
return nil, false, false, err
2014-07-20 16:58:07 -04:00
}
driver := p.Driver
if driver == nil {
// If no driver is set, then we use the real driver
driver = &docker.DockerDriver{Ctx: &p.config.ctx, Ui: ui}
2014-07-20 16:58:07 -04:00
}
ui.Message("Saving image: " + artifact.Id())
if err := driver.SaveImage(artifact.Id(), f); err != nil {
f.Close()
os.Remove(f.Name())
2019-04-02 19:51:58 -04:00
return nil, false, false, err
2014-07-20 16:58:07 -04:00
}
f.Close()
ui.Message("Saved to: " + path)
2019-04-02 19:51:58 -04:00
return artifact, true, false, nil
2014-07-20 16:58:07 -04:00
}