github.phpd.cn/hashicorp/packer@v1.3.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  	"log"
     9  	"os"
    10  	"strings"
    11  
    12  	"github.com/aws/aws-sdk-go/service/ec2"
    13  	awscommon "github.com/hashicorp/packer/builder/amazon/common"
    14  	"github.com/hashicorp/packer/common"
    15  	"github.com/hashicorp/packer/helper/communicator"
    16  	"github.com/hashicorp/packer/helper/config"
    17  	"github.com/hashicorp/packer/helper/multistep"
    18  	"github.com/hashicorp/packer/packer"
    19  	"github.com/hashicorp/packer/template/interpolate"
    20  )
    21  
    22  // The unique ID for this builder
    23  const BuilderId = "mitchellh.amazon.instance"
    24  
    25  // Config is the configuration that is chained through the steps and
    26  // settable from the template.
    27  type Config struct {
    28  	common.PackerConfig    `mapstructure:",squash"`
    29  	awscommon.AccessConfig `mapstructure:",squash"`
    30  	awscommon.AMIConfig    `mapstructure:",squash"`
    31  	awscommon.BlockDevices `mapstructure:",squash"`
    32  	awscommon.RunConfig    `mapstructure:",squash"`
    33  
    34  	AccountId           string `mapstructure:"account_id"`
    35  	BundleDestination   string `mapstructure:"bundle_destination"`
    36  	BundlePrefix        string `mapstructure:"bundle_prefix"`
    37  	BundleUploadCommand string `mapstructure:"bundle_upload_command"`
    38  	BundleVolCommand    string `mapstructure:"bundle_vol_command"`
    39  	S3Bucket            string `mapstructure:"s3_bucket"`
    40  	X509CertPath        string `mapstructure:"x509_cert_path"`
    41  	X509KeyPath         string `mapstructure:"x509_key_path"`
    42  	X509UploadPath      string `mapstructure:"x509_upload_path"`
    43  
    44  	ctx interpolate.Context
    45  }
    46  
    47  type Builder struct {
    48  	config Config
    49  	runner multistep.Runner
    50  }
    51  
    52  func (b *Builder) Prepare(raws ...interface{}) ([]string, error) {
    53  	configs := make([]interface{}, len(raws)+1)
    54  	configs[0] = map[string]interface{}{
    55  		"bundle_prefix": "image-{{timestamp}}",
    56  	}
    57  	copy(configs[1:], raws)
    58  
    59  	b.config.ctx.Funcs = awscommon.TemplateFuncs
    60  	err := config.Decode(&b.config, &config.DecodeOpts{
    61  		Interpolate:        true,
    62  		InterpolateContext: &b.config.ctx,
    63  		InterpolateFilter: &interpolate.RenderFilter{
    64  			Exclude: []string{
    65  				"ami_description",
    66  				"bundle_upload_command",
    67  				"bundle_vol_command",
    68  				"run_tags",
    69  				"run_volume_tags",
    70  				"snapshot_tags",
    71  				"tags",
    72  				"spot_tags",
    73  			},
    74  		},
    75  	}, configs...)
    76  	if err != nil {
    77  		return nil, err
    78  	}
    79  
    80  	if b.config.PackerConfig.PackerForce {
    81  		b.config.AMIForceDeregister = true
    82  	}
    83  
    84  	if b.config.BundleDestination == "" {
    85  		b.config.BundleDestination = "/tmp"
    86  	}
    87  
    88  	if b.config.BundleUploadCommand == "" {
    89  		if b.config.IamInstanceProfile != "" {
    90  			b.config.BundleUploadCommand = "sudo -i -n ec2-upload-bundle " +
    91  				"-b {{.BucketName}} " +
    92  				"-m {{.ManifestPath}} " +
    93  				"-d {{.BundleDirectory}} " +
    94  				"--batch " +
    95  				"--region {{.Region}} " +
    96  				"--retry"
    97  		} else {
    98  			b.config.BundleUploadCommand = "sudo -i -n ec2-upload-bundle " +
    99  				"-b {{.BucketName}} " +
   100  				"-m {{.ManifestPath}} " +
   101  				"-a {{.AccessKey}} " +
   102  				"-s {{.SecretKey}} " +
   103  				"-d {{.BundleDirectory}} " +
   104  				"--batch " +
   105  				"--region {{.Region}} " +
   106  				"--retry"
   107  		}
   108  	}
   109  
   110  	if b.config.BundleVolCommand == "" {
   111  		b.config.BundleVolCommand = "sudo -i -n ec2-bundle-vol " +
   112  			"-k {{.KeyPath}} " +
   113  			"-u {{.AccountId}} " +
   114  			"-c {{.CertPath}} " +
   115  			"-r {{.Architecture}} " +
   116  			"-e {{.PrivatePath}}/* " +
   117  			"-d {{.Destination}} " +
   118  			"-p {{.Prefix}} " +
   119  			"--batch " +
   120  			"--no-filter"
   121  	}
   122  
   123  	if b.config.X509UploadPath == "" {
   124  		b.config.X509UploadPath = "/tmp"
   125  	}
   126  
   127  	// Accumulate any errors
   128  	var errs *packer.MultiError
   129  	errs = packer.MultiErrorAppend(errs, b.config.AccessConfig.Prepare(&b.config.ctx)...)
   130  	errs = packer.MultiErrorAppend(errs, b.config.BlockDevices.Prepare(&b.config.ctx)...)
   131  	errs = packer.MultiErrorAppend(errs,
   132  		b.config.AMIConfig.Prepare(&b.config.AccessConfig, &b.config.ctx)...)
   133  	errs = packer.MultiErrorAppend(errs, b.config.RunConfig.Prepare(&b.config.ctx)...)
   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 b.config.IsSpotInstance() && ((b.config.AMIENASupport != nil && *b.config.AMIENASupport) || b.config.AMISriovNetSupport) {
   160  		errs = packer.MultiErrorAppend(errs,
   161  			fmt.Errorf("Spot instances do not support modification, which is required "+
   162  				"when either `ena_support` or `sriov_support` are set. Please ensure "+
   163  				"you use an AMI that already has either SR-IOV or ENA enabled."))
   164  	}
   165  
   166  	if errs != nil && len(errs.Errors) > 0 {
   167  		return nil, errs
   168  	}
   169  	packer.LogSecretFilter.Set(b.config.AccessKey, b.config.SecretKey, b.config.Token)
   170  	return nil, nil
   171  }
   172  
   173  func (b *Builder) Run(ui packer.Ui, hook packer.Hook, cache packer.Cache) (packer.Artifact, error) {
   174  	session, err := b.config.Session()
   175  	if err != nil {
   176  		return nil, err
   177  	}
   178  	ec2conn := ec2.New(session)
   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("awsSession", session)
   185  	state.Put("hook", hook)
   186  	state.Put("ui", ui)
   187  
   188  	var instanceStep multistep.Step
   189  
   190  	if b.config.IsSpotInstance() {
   191  		instanceStep = &awscommon.StepRunSpotInstance{
   192  			AssociatePublicIpAddress: b.config.AssociatePublicIpAddress,
   193  			BlockDevices:             b.config.BlockDevices,
   194  			BlockDurationMinutes:     b.config.BlockDurationMinutes,
   195  			Ctx:                      b.config.ctx,
   196  			Comm:                     &b.config.RunConfig.Comm,
   197  			Debug:                    b.config.PackerDebug,
   198  			EbsOptimized:             b.config.EbsOptimized,
   199  			IamInstanceProfile:       b.config.IamInstanceProfile,
   200  			InstanceType:             b.config.InstanceType,
   201  			SourceAMI:                b.config.SourceAmi,
   202  			SpotPrice:                b.config.SpotPrice,
   203  			SpotPriceProduct:         b.config.SpotPriceAutoProduct,
   204  			Tags:                     b.config.RunTags,
   205  			SpotTags:                 b.config.SpotTags,
   206  			UserData:                 b.config.UserData,
   207  			UserDataFile:             b.config.UserDataFile,
   208  		}
   209  	} else {
   210  		instanceStep = &awscommon.StepRunSourceInstance{
   211  			AssociatePublicIpAddress: b.config.AssociatePublicIpAddress,
   212  			BlockDevices:             b.config.BlockDevices,
   213  			Comm:                     &b.config.RunConfig.Comm,
   214  			Ctx:                      b.config.ctx,
   215  			Debug:                    b.config.PackerDebug,
   216  			EbsOptimized:             b.config.EbsOptimized,
   217  			EnableT2Unlimited:        b.config.EnableT2Unlimited,
   218  			IamInstanceProfile:       b.config.IamInstanceProfile,
   219  			InstanceType:             b.config.InstanceType,
   220  			IsRestricted:             b.config.IsChinaCloud() || b.config.IsGovCloud(),
   221  			SourceAMI:                b.config.SourceAmi,
   222  			Tags:                     b.config.RunTags,
   223  			UserData:                 b.config.UserData,
   224  			UserDataFile:             b.config.UserDataFile,
   225  		}
   226  	}
   227  
   228  	// Build the steps
   229  	steps := []multistep.Step{
   230  		&awscommon.StepPreValidate{
   231  			DestAmiName:     b.config.AMIName,
   232  			ForceDeregister: b.config.AMIForceDeregister,
   233  		},
   234  		&awscommon.StepSourceAMIInfo{
   235  			SourceAmi:                b.config.SourceAmi,
   236  			EnableAMISriovNetSupport: b.config.AMISriovNetSupport,
   237  			EnableAMIENASupport:      b.config.AMIENASupport,
   238  			AmiFilters:               b.config.SourceAmiFilter,
   239  			AMIVirtType:              b.config.AMIVirtType,
   240  		},
   241  		&awscommon.StepNetworkInfo{
   242  			VpcId:               b.config.VpcId,
   243  			VpcFilter:           b.config.VpcFilter,
   244  			SecurityGroupIds:    b.config.SecurityGroupIds,
   245  			SecurityGroupFilter: b.config.SecurityGroupFilter,
   246  			SubnetId:            b.config.SubnetId,
   247  			SubnetFilter:        b.config.SubnetFilter,
   248  			AvailabilityZone:    b.config.AvailabilityZone,
   249  		},
   250  		&awscommon.StepKeyPair{
   251  			Debug:        b.config.PackerDebug,
   252  			Comm:         &b.config.RunConfig.Comm,
   253  			DebugKeyPath: fmt.Sprintf("ec2_%s.pem", b.config.PackerBuildName),
   254  		},
   255  		&awscommon.StepSecurityGroup{
   256  			CommConfig:            &b.config.RunConfig.Comm,
   257  			SecurityGroupFilter:   b.config.SecurityGroupFilter,
   258  			SecurityGroupIds:      b.config.SecurityGroupIds,
   259  			TemporarySGSourceCidr: b.config.TemporarySGSourceCidr,
   260  		},
   261  		instanceStep,
   262  		&awscommon.StepGetPassword{
   263  			Debug:     b.config.PackerDebug,
   264  			Comm:      &b.config.RunConfig.Comm,
   265  			Timeout:   b.config.WindowsPasswordTimeout,
   266  			BuildName: b.config.PackerBuildName,
   267  		},
   268  		&communicator.StepConnect{
   269  			Config: &b.config.RunConfig.Comm,
   270  			Host: awscommon.SSHHost(
   271  				ec2conn,
   272  				b.config.Comm.SSHInterface),
   273  			SSHConfig: b.config.RunConfig.Comm.SSHConfigFunc(),
   274  		},
   275  		&common.StepProvision{},
   276  		&common.StepCleanupTempKeys{
   277  			Comm: &b.config.RunConfig.Comm,
   278  		},
   279  		&StepUploadX509Cert{},
   280  		&StepBundleVolume{
   281  			Debug: b.config.PackerDebug,
   282  		},
   283  		&StepUploadBundle{
   284  			Debug: b.config.PackerDebug,
   285  		},
   286  		&awscommon.StepDeregisterAMI{
   287  			AccessConfig:        &b.config.AccessConfig,
   288  			ForceDeregister:     b.config.AMIForceDeregister,
   289  			ForceDeleteSnapshot: b.config.AMIForceDeleteSnapshot,
   290  			AMIName:             b.config.AMIName,
   291  			Regions:             b.config.AMIRegions,
   292  		},
   293  		&StepRegisterAMI{
   294  			EnableAMISriovNetSupport: b.config.AMISriovNetSupport,
   295  			EnableAMIENASupport:      b.config.AMIENASupport,
   296  		},
   297  		&awscommon.StepAMIRegionCopy{
   298  			AccessConfig:      &b.config.AccessConfig,
   299  			Regions:           b.config.AMIRegions,
   300  			RegionKeyIds:      b.config.AMIRegionKMSKeyIDs,
   301  			EncryptBootVolume: b.config.AMIEncryptBootVolume,
   302  			Name:              b.config.AMIName,
   303  		},
   304  		&awscommon.StepModifyAMIAttributes{
   305  			Description:    b.config.AMIDescription,
   306  			Users:          b.config.AMIUsers,
   307  			Groups:         b.config.AMIGroups,
   308  			ProductCodes:   b.config.AMIProductCodes,
   309  			SnapshotUsers:  b.config.SnapshotUsers,
   310  			SnapshotGroups: b.config.SnapshotGroups,
   311  			Ctx:            b.config.ctx,
   312  		},
   313  		&awscommon.StepCreateTags{
   314  			Tags:         b.config.AMITags,
   315  			SnapshotTags: b.config.SnapshotTags,
   316  			Ctx:          b.config.ctx,
   317  		},
   318  	}
   319  
   320  	// Run!
   321  	b.runner = common.NewRunner(steps, b.config.PackerConfig, ui)
   322  	b.runner.Run(state)
   323  
   324  	// If there was an error, return that
   325  	if rawErr, ok := state.GetOk("error"); ok {
   326  		return nil, rawErr.(error)
   327  	}
   328  
   329  	// If there are no AMIs, then just return
   330  	if _, ok := state.GetOk("amis"); !ok {
   331  		return nil, nil
   332  	}
   333  
   334  	// Build the artifact and return it
   335  	artifact := &awscommon.Artifact{
   336  		Amis:           state.Get("amis").(map[string]string),
   337  		BuilderIdValue: BuilderId,
   338  		Session:        session,
   339  	}
   340  
   341  	return artifact, nil
   342  }
   343  
   344  func (b *Builder) Cancel() {
   345  	if b.runner != nil {
   346  		log.Println("Cancelling the step runner...")
   347  		b.runner.Cancel()
   348  	}
   349  }