github.com/hashicorp/packer@v1.14.3/post-processor/artifice/post-processor.go (about)

     1  // Copyright (c) HashiCorp, Inc.
     2  // SPDX-License-Identifier: BUSL-1.1
     3  
     4  //go:generate packer-sdc mapstructure-to-hcl2 -type Config
     5  
     6  package artifice
     7  
     8  import (
     9  	"context"
    10  	"fmt"
    11  	"strings"
    12  
    13  	"github.com/hashicorp/hcl/v2/hcldec"
    14  	"github.com/hashicorp/packer-plugin-sdk/common"
    15  	packersdk "github.com/hashicorp/packer-plugin-sdk/packer"
    16  	"github.com/hashicorp/packer-plugin-sdk/template/config"
    17  	"github.com/hashicorp/packer-plugin-sdk/template/interpolate"
    18  )
    19  
    20  // The artifact-override post-processor allows you to specify arbitrary files as
    21  // artifacts. These will override any other artifacts created by the builder.
    22  // This allows you to use a builder and provisioner to create some file, such as
    23  // a compiled binary or tarball, extract it from the builder (VM or container)
    24  // and then save that binary or tarball and throw away the builder.
    25  
    26  type Config struct {
    27  	common.PackerConfig `mapstructure:",squash"`
    28  
    29  	Files []string `mapstructure:"files"`
    30  	Keep  bool     `mapstructure:"keep_input_artifact"`
    31  
    32  	ctx interpolate.Context
    33  }
    34  
    35  type PostProcessor struct {
    36  	config Config
    37  }
    38  
    39  func (p *PostProcessor) ConfigSpec() hcldec.ObjectSpec { return p.config.FlatMapstructure().HCL2Spec() }
    40  
    41  func (p *PostProcessor) Configure(raws ...interface{}) error {
    42  	err := config.Decode(&p.config, &config.DecodeOpts{
    43  		PluginType:         "artifice",
    44  		Interpolate:        true,
    45  		InterpolateContext: &p.config.ctx,
    46  		InterpolateFilter: &interpolate.RenderFilter{
    47  			Exclude: []string{},
    48  		},
    49  	}, raws...)
    50  	if err != nil {
    51  		return err
    52  	}
    53  
    54  	if len(p.config.Files) == 0 {
    55  		return fmt.Errorf("No files specified in artifice configuration")
    56  	}
    57  
    58  	return nil
    59  }
    60  
    61  func (p *PostProcessor) PostProcess(ctx context.Context, ui packersdk.Ui, artifact packersdk.Artifact) (packersdk.Artifact, bool, bool, error) {
    62  	if len(artifact.Files()) > 0 {
    63  		ui.Say(fmt.Sprintf("Discarding files from artifact: %s", strings.Join(artifact.Files(), ", ")))
    64  	}
    65  
    66  	artifact, err := NewArtifact(p.config.Files)
    67  	ui.Say(fmt.Sprintf("Using these artifact files: %s", strings.Join(artifact.Files(), ", ")))
    68  
    69  	return artifact, true, false, err
    70  }