github.com/victortrac/packer@v0.7.6-0.20160602180447-63c7fdb6e41f/builder/amazon/ebs/builder.go (about)

     1  // The amazonebs package contains a packer.Builder implementation that
     2  // builds AMIs for Amazon EC2.
     3  //
     4  // In general, there are two types of AMIs that can be created: ebs-backed or
     5  // instance-store. This builder _only_ builds ebs-backed images.
     6  package ebs
     7  
     8  import (
     9  	"fmt"
    10  	"log"
    11  
    12  	"github.com/aws/aws-sdk-go/aws/session"
    13  	"github.com/aws/aws-sdk-go/service/ec2"
    14  	"github.com/mitchellh/multistep"
    15  	awscommon "github.com/mitchellh/packer/builder/amazon/common"
    16  	"github.com/mitchellh/packer/common"
    17  	"github.com/mitchellh/packer/helper/communicator"
    18  	"github.com/mitchellh/packer/helper/config"
    19  	"github.com/mitchellh/packer/packer"
    20  	"github.com/mitchellh/packer/template/interpolate"
    21  )
    22  
    23  // The unique ID for this builder
    24  const BuilderId = "mitchellh.amazonebs"
    25  
    26  type Config struct {
    27  	common.PackerConfig    `mapstructure:",squash"`
    28  	awscommon.AccessConfig `mapstructure:",squash"`
    29  	awscommon.AMIConfig    `mapstructure:",squash"`
    30  	awscommon.BlockDevices `mapstructure:",squash"`
    31  	awscommon.RunConfig    `mapstructure:",squash"`
    32  	VolumeRunTags          map[string]string `mapstructure:"run_volume_tags"`
    33  
    34  	ctx interpolate.Context
    35  }
    36  
    37  type Builder struct {
    38  	config Config
    39  	runner multistep.Runner
    40  }
    41  
    42  func (b *Builder) Prepare(raws ...interface{}) ([]string, error) {
    43  	b.config.ctx.Funcs = awscommon.TemplateFuncs
    44  	err := config.Decode(&b.config, &config.DecodeOpts{
    45  		Interpolate:        true,
    46  		InterpolateContext: &b.config.ctx,
    47  	}, raws...)
    48  	if err != nil {
    49  		return nil, err
    50  	}
    51  
    52  	// Accumulate any errors
    53  	var errs *packer.MultiError
    54  	errs = packer.MultiErrorAppend(errs, b.config.AccessConfig.Prepare(&b.config.ctx)...)
    55  	errs = packer.MultiErrorAppend(errs, b.config.BlockDevices.Prepare(&b.config.ctx)...)
    56  	errs = packer.MultiErrorAppend(errs, b.config.AMIConfig.Prepare(&b.config.ctx)...)
    57  	errs = packer.MultiErrorAppend(errs, b.config.RunConfig.Prepare(&b.config.ctx)...)
    58  
    59  	if errs != nil && len(errs.Errors) > 0 {
    60  		return nil, errs
    61  	}
    62  
    63  	log.Println(common.ScrubConfig(b.config, b.config.AccessKey, b.config.SecretKey))
    64  	return nil, nil
    65  }
    66  
    67  func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) {
    68  	config, err := b.config.Config()
    69  	if err != nil {
    70  		return nil, err
    71  	}
    72  
    73  	session := session.New(config)
    74  	ec2conn := ec2.New(session)
    75  
    76  	// If the subnet is specified but not the AZ, try to determine the AZ automatically
    77  	if b.config.SubnetId != "" && b.config.AvailabilityZone == "" {
    78  		log.Printf("[INFO] Finding AZ for the given subnet '%s'", b.config.SubnetId)
    79  		resp, err := ec2conn.DescribeSubnets(&ec2.DescribeSubnetsInput{SubnetIds: []*string{&b.config.SubnetId}})
    80  		if err != nil {
    81  			return nil, err
    82  		}
    83  		b.config.AvailabilityZone = *resp.Subnets[0].AvailabilityZone
    84  		log.Printf("[INFO] AZ found: '%s'", b.config.AvailabilityZone)
    85  	}
    86  
    87  	// Setup the state bag and initial state for the steps
    88  	state := new(multistep.BasicStateBag)
    89  	state.Put("config", b.config)
    90  	state.Put("ec2", ec2conn)
    91  	state.Put("hook", hook)
    92  	state.Put("ui", ui)
    93  
    94  	// Build the steps
    95  	steps := []multistep.Step{
    96  		&awscommon.StepPreValidate{
    97  			DestAmiName:     b.config.AMIName,
    98  			ForceDeregister: b.config.AMIForceDeregister,
    99  		},
   100  		&awscommon.StepSourceAMIInfo{
   101  			SourceAmi:          b.config.SourceAmi,
   102  			EnhancedNetworking: b.config.AMIEnhancedNetworking,
   103  		},
   104  		&awscommon.StepKeyPair{
   105  			Debug:                b.config.PackerDebug,
   106  			DebugKeyPath:         fmt.Sprintf("ec2_%s.pem", b.config.PackerBuildName),
   107  			KeyPairName:          b.config.SSHKeyPairName,
   108  			TemporaryKeyPairName: b.config.TemporaryKeyPairName,
   109  			PrivateKeyFile:       b.config.RunConfig.Comm.SSHPrivateKey,
   110  		},
   111  		&awscommon.StepSecurityGroup{
   112  			SecurityGroupIds: b.config.SecurityGroupIds,
   113  			CommConfig:       &b.config.RunConfig.Comm,
   114  			VpcId:            b.config.VpcId,
   115  		},
   116  		&stepCleanupVolumes{
   117  			BlockDevices: b.config.BlockDevices,
   118  		},
   119  		&awscommon.StepRunSourceInstance{
   120  			Debug:                    b.config.PackerDebug,
   121  			ExpectedRootDevice:       "ebs",
   122  			SpotPrice:                b.config.SpotPrice,
   123  			SpotPriceProduct:         b.config.SpotPriceAutoProduct,
   124  			InstanceType:             b.config.InstanceType,
   125  			UserData:                 b.config.UserData,
   126  			UserDataFile:             b.config.UserDataFile,
   127  			SourceAMI:                b.config.SourceAmi,
   128  			IamInstanceProfile:       b.config.IamInstanceProfile,
   129  			SubnetId:                 b.config.SubnetId,
   130  			AssociatePublicIpAddress: b.config.AssociatePublicIpAddress,
   131  			EbsOptimized:             b.config.EbsOptimized,
   132  			AvailabilityZone:         b.config.AvailabilityZone,
   133  			BlockDevices:             b.config.BlockDevices,
   134  			Tags:                     b.config.RunTags,
   135  		},
   136  		&stepTagEBSVolumes{
   137  			VolumeRunTags: b.config.VolumeRunTags,
   138  		},
   139  		&awscommon.StepGetPassword{
   140  			Debug:   b.config.PackerDebug,
   141  			Comm:    &b.config.RunConfig.Comm,
   142  			Timeout: b.config.WindowsPasswordTimeout,
   143  		},
   144  		&communicator.StepConnect{
   145  			Config: &b.config.RunConfig.Comm,
   146  			Host: awscommon.SSHHost(
   147  				ec2conn,
   148  				b.config.SSHPrivateIp),
   149  			SSHConfig: awscommon.SSHConfig(
   150  				b.config.RunConfig.Comm.SSHUsername),
   151  		},
   152  		&common.StepProvision{},
   153  		&stepStopInstance{
   154  			SpotPrice:           b.config.SpotPrice,
   155  			DisableStopInstance: b.config.DisableStopInstance,
   156  		},
   157  		// TODO(mitchellh): verify works with spots
   158  		&stepModifyInstance{},
   159  		&awscommon.StepDeregisterAMI{
   160  			ForceDeregister: b.config.AMIForceDeregister,
   161  			AMIName:         b.config.AMIName,
   162  		},
   163  		&stepCreateAMI{},
   164  		&awscommon.StepAMIRegionCopy{
   165  			AccessConfig: &b.config.AccessConfig,
   166  			Regions:      b.config.AMIRegions,
   167  			Name:         b.config.AMIName,
   168  		},
   169  		&awscommon.StepModifyAMIAttributes{
   170  			Description:  b.config.AMIDescription,
   171  			Users:        b.config.AMIUsers,
   172  			Groups:       b.config.AMIGroups,
   173  			ProductCodes: b.config.AMIProductCodes,
   174  		},
   175  		&awscommon.StepCreateTags{
   176  			Tags: b.config.AMITags,
   177  		},
   178  	}
   179  
   180  	// Run!
   181  	if b.config.PackerDebug {
   182  		b.runner = &multistep.DebugRunner{
   183  			Steps:   steps,
   184  			PauseFn: common.MultistepDebugFn(ui),
   185  		}
   186  	} else {
   187  		b.runner = &multistep.BasicRunner{Steps: steps}
   188  	}
   189  
   190  	b.runner.Run(state)
   191  
   192  	// If there was an error, return that
   193  	if rawErr, ok := state.GetOk("error"); ok {
   194  		return nil, rawErr.(error)
   195  	}
   196  
   197  	// If there are no AMIs, then just return
   198  	if _, ok := state.GetOk("amis"); !ok {
   199  		return nil, nil
   200  	}
   201  
   202  	// Build the artifact and return it
   203  	artifact := &awscommon.Artifact{
   204  		Amis:           state.Get("amis").(map[string]string),
   205  		BuilderIdValue: BuilderId,
   206  		Conn:           ec2conn,
   207  	}
   208  
   209  	return artifact, nil
   210  }
   211  
   212  func (b *Builder) Cancel() {
   213  	if b.runner != nil {
   214  		log.Println("Cancelling the step runner...")
   215  		b.runner.Cancel()
   216  	}
   217  }