Files

93 lines
2.3 KiB
Go
Raw Permalink Normal View History

2019-10-14 16:43:59 +02:00
//go:generate mapstructure-to-hcl2 -type Config
2014-07-20 21:58:07 +01:00
package dockersave
import (
2019-03-22 14:56:02 +01:00
"context"
2014-07-20 21:58:07 +01:00
"fmt"
"os"
2019-12-17 11:25:56 +01:00
"github.com/hashicorp/hcl/v2/hcldec"
2017-04-04 13:39:01 -07:00
"github.com/hashicorp/packer/builder/docker"
"github.com/hashicorp/packer/packer-plugin-sdk/common"
packersdk "github.com/hashicorp/packer/packer-plugin-sdk/packer"
"github.com/hashicorp/packer/packer-plugin-sdk/template/config"
"github.com/hashicorp/packer/packer-plugin-sdk/template/interpolate"
2019-03-22 14:56:02 +01:00
dockerimport "github.com/hashicorp/packer/post-processor/docker-import"
dockertag "github.com/hashicorp/packer/post-processor/docker-tag"
2014-07-20 21:58:07 +01: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 21:58:07 +01:00
}
type PostProcessor struct {
Driver docker.Driver
config Config
}
2019-12-17 11:25:56 +01:00
func (p *PostProcessor) ConfigSpec() hcldec.ObjectSpec { return p.config.FlatMapstructure().HCL2Spec() }
2014-07-20 21:58:07 +01:00
func (p *PostProcessor) Configure(raws ...interface{}) error {
err := config.Decode(&p.config, &config.DecodeOpts{
PluginType: BuilderId,
2015-06-22 12:24:27 -07:00
Interpolate: true,
InterpolateContext: &p.config.ctx,
InterpolateFilter: &interpolate.RenderFilter{
Exclude: []string{},
},
}, raws...)
2014-07-20 21:58:07 +01:00
if err != nil {
return err
}
return nil
}
2020-11-19 12:17:11 -08:00
func (p *PostProcessor) PostProcess(ctx context.Context, ui packersdk.Ui, artifact packersdk.Artifact) (packersdk.Artifact, bool, bool, error) {
if artifact.BuilderId() != dockerimport.BuilderId &&
artifact.BuilderId() != dockertag.BuilderId {
2014-07-20 21:58:07 +01:00
err := fmt.Errorf(
"Unknown artifact type: %s\nCan only save Docker builder artifacts.",
artifact.BuilderId())
2019-04-02 16:51:58 -07:00
return nil, false, false, err
2014-07-20 21:58:07 +01: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 16:51:58 -07:00
return nil, false, false, err
2014-07-20 21:58:07 +01: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 21:58:07 +01: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 16:51:58 -07:00
return nil, false, false, err
2014-07-20 21:58:07 +01:00
}
f.Close()
ui.Message("Saved to: " + path)
2019-04-02 16:51:58 -07:00
return artifact, true, false, nil
2014-07-20 21:58:07 +01:00
}