github.com/phobos182/packer@v0.2.3-0.20130819023704-c84d2aeffc68/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  	Tags                map[string]string
    37  	X509CertPath        string `mapstructure:"x509_cert_path"`
    38  	X509KeyPath         string `mapstructure:"x509_key_path"`
    39  	X509UploadPath      string `mapstructure:"x509_upload_path"`
    40  
    41  	tpl *packer.ConfigTemplate
    42  }
    43  
    44  type Builder struct {
    45  	config Config
    46  	runner multistep.Runner
    47  }
    48  
    49  func (b *Builder) Prepare(raws ...interface{}) error {
    50  	md, err := common.DecodeConfig(&b.config, raws...)
    51  	if err != nil {
    52  		return err
    53  	}
    54  
    55  	b.config.tpl, err = packer.NewConfigTemplate()
    56  	if err != nil {
    57  		return err
    58  	}
    59  	b.config.tpl.UserVars = b.config.PackerUserVars
    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  			"--retry"
    78  	}
    79  
    80  	if b.config.BundleVolCommand == "" {
    81  		b.config.BundleVolCommand = "sudo -n ec2-bundle-vol " +
    82  			"-k {{.KeyPath}} " +
    83  			"-u {{.AccountId}} " +
    84  			"-c {{.CertPath}} " +
    85  			"-r {{.Architecture}} " +
    86  			"-e {{.PrivatePath}} " +
    87  			"-d {{.Destination}} " +
    88  			"-p {{.Prefix}} " +
    89  			"--batch"
    90  	}
    91  
    92  	if b.config.X509UploadPath == "" {
    93  		b.config.X509UploadPath = "/tmp"
    94  	}
    95  
    96  	// Accumulate any errors
    97  	errs := common.CheckUnusedConfig(md)
    98  	errs = packer.MultiErrorAppend(errs, b.config.AccessConfig.Prepare(b.config.tpl)...)
    99  	errs = packer.MultiErrorAppend(errs, b.config.AMIConfig.Prepare(b.config.tpl)...)
   100  	errs = packer.MultiErrorAppend(errs, b.config.RunConfig.Prepare(b.config.tpl)...)
   101  
   102  	validates := map[string]*string{
   103  		"bundle_upload_command": &b.config.BundleUploadCommand,
   104  		"bundle_vol_command":    &b.config.BundleVolCommand,
   105  	}
   106  
   107  	for n, ptr := range validates {
   108  		if err := b.config.tpl.Validate(*ptr); err != nil {
   109  			errs = packer.MultiErrorAppend(
   110  				errs, fmt.Errorf("Error parsing %s: %s", n, err))
   111  		}
   112  	}
   113  
   114  	templates := map[string]*string{
   115  		"account_id":         &b.config.AccountId,
   116  		"ami_name":           &b.config.AMIName,
   117  		"bundle_destination": &b.config.BundleDestination,
   118  		"bundle_prefix":      &b.config.BundlePrefix,
   119  		"s3_bucket":          &b.config.S3Bucket,
   120  		"x509_cert_path":     &b.config.X509CertPath,
   121  		"x509_key_path":      &b.config.X509KeyPath,
   122  		"x509_upload_path":   &b.config.X509UploadPath,
   123  	}
   124  
   125  	for n, ptr := range templates {
   126  		var err error
   127  		*ptr, err = b.config.tpl.Process(*ptr, nil)
   128  		if err != nil {
   129  			errs = packer.MultiErrorAppend(
   130  				errs, fmt.Errorf("Error processing %s: %s", n, err))
   131  		}
   132  	}
   133  
   134  	if b.config.AccountId == "" {
   135  		errs = packer.MultiErrorAppend(errs, errors.New("account_id is required"))
   136  	} else {
   137  		b.config.AccountId = strings.Replace(b.config.AccountId, "-", "", -1)
   138  	}
   139  
   140  	if b.config.S3Bucket == "" {
   141  		errs = packer.MultiErrorAppend(errs, errors.New("s3_bucket is required"))
   142  	}
   143  
   144  	if b.config.X509CertPath == "" {
   145  		errs = packer.MultiErrorAppend(errs, errors.New("x509_cert_path is required"))
   146  	} else if _, err := os.Stat(b.config.X509CertPath); err != nil {
   147  		errs = packer.MultiErrorAppend(
   148  			errs, fmt.Errorf("x509_cert_path points to bad file: %s", err))
   149  	}
   150  
   151  	if b.config.X509KeyPath == "" {
   152  		errs = packer.MultiErrorAppend(errs, errors.New("x509_key_path is required"))
   153  	} else if _, err := os.Stat(b.config.X509KeyPath); err != nil {
   154  		errs = packer.MultiErrorAppend(
   155  			errs, fmt.Errorf("x509_key_path points to bad file: %s", err))
   156  	}
   157  
   158  	if errs != nil && len(errs.Errors) > 0 {
   159  		return errs
   160  	}
   161  
   162  	log.Printf("Config: %+v", b.config)
   163  	return nil
   164  }
   165  
   166  func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) {
   167  	region, err := b.config.Region()
   168  	if err != nil {
   169  		return nil, err
   170  	}
   171  
   172  	auth, err := b.config.AccessConfig.Auth()
   173  	if err != nil {
   174  		return nil, err
   175  	}
   176  
   177  	ec2conn := ec2.New(auth, region)
   178  
   179  	// Setup the state bag and initial state for the steps
   180  	state := make(map[string]interface{})
   181  	state["config"] = &b.config
   182  	state["ec2"] = ec2conn
   183  	state["hook"] = hook
   184  	state["ui"] = ui
   185  
   186  	// Build the steps
   187  	steps := []multistep.Step{
   188  		&awscommon.StepKeyPair{},
   189  		&awscommon.StepSecurityGroup{
   190  			SecurityGroupId: b.config.SecurityGroupId,
   191  			SSHPort:         b.config.SSHPort,
   192  			VpcId:           b.config.VpcId,
   193  		},
   194  		&awscommon.StepRunSourceInstance{
   195  			ExpectedRootDevice: "instance-store",
   196  			InstanceType:       b.config.InstanceType,
   197  			IamInstanceProfile: b.config.IamInstanceProfile,
   198  			UserData:           b.config.UserData,
   199  			UserDataFile:       b.config.UserDataFile,
   200  			SourceAMI:          b.config.SourceAmi,
   201  			SubnetId:           b.config.SubnetId,
   202  			BlockDevices:       b.config.BlockDevices,
   203  		},
   204  		&common.StepConnectSSH{
   205  			SSHAddress:     awscommon.SSHAddress(ec2conn, b.config.SSHPort),
   206  			SSHConfig:      awscommon.SSHConfig(b.config.SSHUsername),
   207  			SSHWaitTimeout: b.config.SSHTimeout(),
   208  		},
   209  		&common.StepProvision{},
   210  		&StepUploadX509Cert{},
   211  		&StepBundleVolume{},
   212  		&StepUploadBundle{},
   213  		&StepRegisterAMI{},
   214  		&awscommon.StepCreateTags{Tags: b.config.Tags},
   215  		&awscommon.StepModifyAMIAttributes{
   216  			Description:  b.config.AMIDescription,
   217  			Users:        b.config.AMIUsers,
   218  			Groups:       b.config.AMIGroups,
   219  			ProductCodes: b.config.AMIProductCodes,
   220  		},
   221  	}
   222  
   223  	// Run!
   224  	if b.config.PackerDebug {
   225  		b.runner = &multistep.DebugRunner{
   226  			Steps:   steps,
   227  			PauseFn: common.MultistepDebugFn(ui),
   228  		}
   229  	} else {
   230  		b.runner = &multistep.BasicRunner{Steps: steps}
   231  	}
   232  
   233  	b.runner.Run(state)
   234  
   235  	// If there was an error, return that
   236  	if rawErr, ok := state["error"]; ok {
   237  		return nil, rawErr.(error)
   238  	}
   239  
   240  	// If there are no AMIs, then just return
   241  	if _, ok := state["amis"]; !ok {
   242  		return nil, nil
   243  	}
   244  
   245  	// Build the artifact and return it
   246  	artifact := &awscommon.Artifact{
   247  		Amis:           state["amis"].(map[string]string),
   248  		BuilderIdValue: BuilderId,
   249  		Conn:           ec2conn,
   250  	}
   251  
   252  	return artifact, nil
   253  }
   254  
   255  func (b *Builder) Cancel() {
   256  	if b.runner != nil {
   257  		log.Println("Cancelling the step runner...")
   258  		b.runner.Cancel()
   259  	}
   260  }