github.com/sneal/packer@v0.5.2/builder/amazon/instance/builder.go (about)

     1  // The instance package contains a packer.Builder implementation that builds
     2  // AMIs for Amazon EC2 backed by instance storage, as opposed to EBS storage.
     3  package instance
     4  
     5  import (
     6  	"errors"
     7  	"fmt"
     8  	"github.com/mitchellh/goamz/ec2"
     9  	"github.com/mitchellh/multistep"
    10  	awscommon "github.com/mitchellh/packer/builder/amazon/common"
    11  	"github.com/mitchellh/packer/common"
    12  	"github.com/mitchellh/packer/packer"
    13  	"log"
    14  	"os"
    15  	"strings"
    16  )
    17  
    18  // The unique ID for this builder
    19  const BuilderId = "mitchellh.amazon.instance"
    20  
    21  // Config is the configuration that is chained through the steps and
    22  // settable from the template.
    23  type Config struct {
    24  	common.PackerConfig    `mapstructure:",squash"`
    25  	awscommon.AccessConfig `mapstructure:",squash"`
    26  	awscommon.AMIConfig    `mapstructure:",squash"`
    27  	awscommon.BlockDevices `mapstructure:",squash"`
    28  	awscommon.RunConfig    `mapstructure:",squash"`
    29  
    30  	AccountId           string `mapstructure:"account_id"`
    31  	BundleDestination   string `mapstructure:"bundle_destination"`
    32  	BundlePrefix        string `mapstructure:"bundle_prefix"`
    33  	BundleUploadCommand string `mapstructure:"bundle_upload_command"`
    34  	BundleVolCommand    string `mapstructure:"bundle_vol_command"`
    35  	S3Bucket            string `mapstructure:"s3_bucket"`
    36  	X509CertPath        string `mapstructure:"x509_cert_path"`
    37  	X509KeyPath         string `mapstructure:"x509_key_path"`
    38  	X509UploadPath      string `mapstructure:"x509_upload_path"`
    39  
    40  	tpl *packer.ConfigTemplate
    41  }
    42  
    43  type Builder struct {
    44  	config Config
    45  	runner multistep.Runner
    46  }
    47  
    48  func (b *Builder) Prepare(raws ...interface{}) ([]string, error) {
    49  	md, err := common.DecodeConfig(&b.config, raws...)
    50  	if err != nil {
    51  		return nil, err
    52  	}
    53  
    54  	b.config.tpl, err = packer.NewConfigTemplate()
    55  	if err != nil {
    56  		return nil, err
    57  	}
    58  	b.config.tpl.UserVars = b.config.PackerUserVars
    59  	b.config.tpl.Funcs(awscommon.TemplateFuncs)
    60  
    61  	if b.config.BundleDestination == "" {
    62  		b.config.BundleDestination = "/tmp"
    63  	}
    64  
    65  	if b.config.BundlePrefix == "" {
    66  		b.config.BundlePrefix = "image-{{timestamp}}"
    67  	}
    68  
    69  	if b.config.BundleUploadCommand == "" {
    70  		b.config.BundleUploadCommand = "sudo -n ec2-upload-bundle " +
    71  			"-b {{.BucketName}} " +
    72  			"-m {{.ManifestPath}} " +
    73  			"-a {{.AccessKey}} " +
    74  			"-s {{.SecretKey}} " +
    75  			"-d {{.BundleDirectory}} " +
    76  			"--batch " +
    77  			"--url https://s3-{{.Region}}.amazonaws.com " +
    78  			"--retry"
    79  	}
    80  
    81  	if b.config.BundleVolCommand == "" {
    82  		b.config.BundleVolCommand = "sudo -n ec2-bundle-vol " +
    83  			"-k {{.KeyPath}} " +
    84  			"-u {{.AccountId}} " +
    85  			"-c {{.CertPath}} " +
    86  			"-r {{.Architecture}} " +
    87  			"-e {{.PrivatePath}}/* " +
    88  			"-d {{.Destination}} " +
    89  			"-p {{.Prefix}} " +
    90  			"--batch"
    91  	}
    92  
    93  	if b.config.X509UploadPath == "" {
    94  		b.config.X509UploadPath = "/tmp"
    95  	}
    96  
    97  	// Accumulate any errors
    98  	errs := common.CheckUnusedConfig(md)
    99  	errs = packer.MultiErrorAppend(errs, b.config.AccessConfig.Prepare(b.config.tpl)...)
   100  	errs = packer.MultiErrorAppend(errs, b.config.AMIConfig.Prepare(b.config.tpl)...)
   101  	errs = packer.MultiErrorAppend(errs, b.config.RunConfig.Prepare(b.config.tpl)...)
   102  
   103  	validates := map[string]*string{
   104  		"bundle_upload_command": &b.config.BundleUploadCommand,
   105  		"bundle_vol_command":    &b.config.BundleVolCommand,
   106  	}
   107  
   108  	for n, ptr := range validates {
   109  		if err := b.config.tpl.Validate(*ptr); err != nil {
   110  			errs = packer.MultiErrorAppend(
   111  				errs, fmt.Errorf("Error parsing %s: %s", n, err))
   112  		}
   113  	}
   114  
   115  	templates := map[string]*string{
   116  		"account_id":         &b.config.AccountId,
   117  		"ami_name":           &b.config.AMIName,
   118  		"bundle_destination": &b.config.BundleDestination,
   119  		"bundle_prefix":      &b.config.BundlePrefix,
   120  		"s3_bucket":          &b.config.S3Bucket,
   121  		"x509_cert_path":     &b.config.X509CertPath,
   122  		"x509_key_path":      &b.config.X509KeyPath,
   123  		"x509_upload_path":   &b.config.X509UploadPath,
   124  	}
   125  
   126  	for n, ptr := range templates {
   127  		var err error
   128  		*ptr, err = b.config.tpl.Process(*ptr, nil)
   129  		if err != nil {
   130  			errs = packer.MultiErrorAppend(
   131  				errs, fmt.Errorf("Error processing %s: %s", n, err))
   132  		}
   133  	}
   134  
   135  	if b.config.AccountId == "" {
   136  		errs = packer.MultiErrorAppend(errs, errors.New("account_id is required"))
   137  	} else {
   138  		b.config.AccountId = strings.Replace(b.config.AccountId, "-", "", -1)
   139  	}
   140  
   141  	if b.config.S3Bucket == "" {
   142  		errs = packer.MultiErrorAppend(errs, errors.New("s3_bucket is required"))
   143  	}
   144  
   145  	if b.config.X509CertPath == "" {
   146  		errs = packer.MultiErrorAppend(errs, errors.New("x509_cert_path is required"))
   147  	} else if _, err := os.Stat(b.config.X509CertPath); err != nil {
   148  		errs = packer.MultiErrorAppend(
   149  			errs, fmt.Errorf("x509_cert_path points to bad file: %s", err))
   150  	}
   151  
   152  	if b.config.X509KeyPath == "" {
   153  		errs = packer.MultiErrorAppend(errs, errors.New("x509_key_path is required"))
   154  	} else if _, err := os.Stat(b.config.X509KeyPath); err != nil {
   155  		errs = packer.MultiErrorAppend(
   156  			errs, fmt.Errorf("x509_key_path points to bad file: %s", err))
   157  	}
   158  
   159  	if errs != nil && len(errs.Errors) > 0 {
   160  		return nil, errs
   161  	}
   162  
   163  	log.Println(common.ScrubConfig(b.config, b.config.AccessKey, b.config.SecretKey))
   164  	return nil, nil
   165  }
   166  
   167  func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) {
   168  	region, err := b.config.Region()
   169  	if err != nil {
   170  		return nil, err
   171  	}
   172  
   173  	auth, err := b.config.AccessConfig.Auth()
   174  	if err != nil {
   175  		return nil, err
   176  	}
   177  
   178  	ec2conn := ec2.New(auth, region)
   179  
   180  	// Setup the state bag and initial state for the steps
   181  	state := new(multistep.BasicStateBag)
   182  	state.Put("config", &b.config)
   183  	state.Put("ec2", ec2conn)
   184  	state.Put("hook", hook)
   185  	state.Put("ui", ui)
   186  
   187  	// Build the steps
   188  	steps := []multistep.Step{
   189  		&awscommon.StepKeyPair{
   190  			Debug:        b.config.PackerDebug,
   191  			DebugKeyPath: fmt.Sprintf("ec2_%s.pem", b.config.PackerBuildName),
   192  			KeyPairName:  b.config.TemporaryKeyPairName,
   193  		},
   194  		&awscommon.StepSecurityGroup{
   195  			SecurityGroupIds: b.config.SecurityGroupIds,
   196  			SSHPort:          b.config.SSHPort,
   197  			VpcId:            b.config.VpcId,
   198  		},
   199  		&awscommon.StepRunSourceInstance{
   200  			Debug:                    b.config.PackerDebug,
   201  			ExpectedRootDevice:       "instance-store",
   202  			InstanceType:             b.config.InstanceType,
   203  			IamInstanceProfile:       b.config.IamInstanceProfile,
   204  			UserData:                 b.config.UserData,
   205  			UserDataFile:             b.config.UserDataFile,
   206  			SourceAMI:                b.config.SourceAmi,
   207  			SubnetId:                 b.config.SubnetId,
   208  			AssociatePublicIpAddress: b.config.AssociatePublicIpAddress,
   209  			AvailabilityZone:         b.config.AvailabilityZone,
   210  			BlockDevices:             b.config.BlockDevices,
   211  			Tags:                     b.config.RunTags,
   212  		},
   213  		&common.StepConnectSSH{
   214  			SSHAddress:     awscommon.SSHAddress(ec2conn, b.config.SSHPort),
   215  			SSHConfig:      awscommon.SSHConfig(b.config.SSHUsername),
   216  			SSHWaitTimeout: b.config.SSHTimeout(),
   217  		},
   218  		&common.StepProvision{},
   219  		&StepUploadX509Cert{},
   220  		&StepBundleVolume{},
   221  		&StepUploadBundle{},
   222  		&StepRegisterAMI{},
   223  		&awscommon.StepAMIRegionCopy{
   224  			Regions: b.config.AMIRegions,
   225  		},
   226  		&awscommon.StepModifyAMIAttributes{
   227  			Description:  b.config.AMIDescription,
   228  			Users:        b.config.AMIUsers,
   229  			Groups:       b.config.AMIGroups,
   230  			ProductCodes: b.config.AMIProductCodes,
   231  		},
   232  		&awscommon.StepCreateTags{
   233  			Tags: b.config.AMITags,
   234  		},
   235  	}
   236  
   237  	// Run!
   238  	if b.config.PackerDebug {
   239  		b.runner = &multistep.DebugRunner{
   240  			Steps:   steps,
   241  			PauseFn: common.MultistepDebugFn(ui),
   242  		}
   243  	} else {
   244  		b.runner = &multistep.BasicRunner{Steps: steps}
   245  	}
   246  
   247  	b.runner.Run(state)
   248  
   249  	// If there was an error, return that
   250  	if rawErr, ok := state.GetOk("error"); ok {
   251  		return nil, rawErr.(error)
   252  	}
   253  
   254  	// If there are no AMIs, then just return
   255  	if _, ok := state.GetOk("amis"); !ok {
   256  		return nil, nil
   257  	}
   258  
   259  	// Build the artifact and return it
   260  	artifact := &awscommon.Artifact{
   261  		Amis:           state.Get("amis").(map[string]string),
   262  		BuilderIdValue: BuilderId,
   263  		Conn:           ec2conn,
   264  	}
   265  
   266  	return artifact, nil
   267  }
   268  
   269  func (b *Builder) Cancel() {
   270  	if b.runner != nil {
   271  		log.Println("Cancelling the step runner...")
   272  		b.runner.Cancel()
   273  	}
   274  }