github.com/amanya/packer@v0.12.1-0.20161117214323-902ac5ab2eb6/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, err := session.NewSession(config) 74 if err != nil { 75 return nil, err 76 } 77 ec2conn := ec2.New(session) 78 79 // If the subnet is specified but not the AZ, try to determine the AZ automatically 80 if b.config.SubnetId != "" && b.config.AvailabilityZone == "" { 81 log.Printf("[INFO] Finding AZ for the given subnet '%s'", b.config.SubnetId) 82 resp, err := ec2conn.DescribeSubnets(&ec2.DescribeSubnetsInput{SubnetIds: []*string{&b.config.SubnetId}}) 83 if err != nil { 84 return nil, err 85 } 86 b.config.AvailabilityZone = *resp.Subnets[0].AvailabilityZone 87 log.Printf("[INFO] AZ found: '%s'", b.config.AvailabilityZone) 88 } 89 90 // Setup the state bag and initial state for the steps 91 state := new(multistep.BasicStateBag) 92 state.Put("config", b.config) 93 state.Put("ec2", ec2conn) 94 state.Put("hook", hook) 95 state.Put("ui", ui) 96 97 // Build the steps 98 steps := []multistep.Step{ 99 &awscommon.StepPreValidate{ 100 DestAmiName: b.config.AMIName, 101 ForceDeregister: b.config.AMIForceDeregister, 102 }, 103 &awscommon.StepSourceAMIInfo{ 104 SourceAmi: b.config.SourceAmi, 105 EnhancedNetworking: b.config.AMIEnhancedNetworking, 106 AmiFilters: b.config.SourceAmiFilter, 107 }, 108 &awscommon.StepKeyPair{ 109 Debug: b.config.PackerDebug, 110 DebugKeyPath: fmt.Sprintf("ec2_%s.pem", b.config.PackerBuildName), 111 KeyPairName: b.config.SSHKeyPairName, 112 TemporaryKeyPairName: b.config.TemporaryKeyPairName, 113 PrivateKeyFile: b.config.RunConfig.Comm.SSHPrivateKey, 114 }, 115 &awscommon.StepSecurityGroup{ 116 SecurityGroupIds: b.config.SecurityGroupIds, 117 CommConfig: &b.config.RunConfig.Comm, 118 VpcId: b.config.VpcId, 119 }, 120 &stepCleanupVolumes{ 121 BlockDevices: b.config.BlockDevices, 122 }, 123 &awscommon.StepRunSourceInstance{ 124 Debug: b.config.PackerDebug, 125 ExpectedRootDevice: "ebs", 126 SpotPrice: b.config.SpotPrice, 127 SpotPriceProduct: b.config.SpotPriceAutoProduct, 128 InstanceType: b.config.InstanceType, 129 UserData: b.config.UserData, 130 UserDataFile: b.config.UserDataFile, 131 SourceAMI: b.config.SourceAmi, 132 IamInstanceProfile: b.config.IamInstanceProfile, 133 SubnetId: b.config.SubnetId, 134 AssociatePublicIpAddress: b.config.AssociatePublicIpAddress, 135 EbsOptimized: b.config.EbsOptimized, 136 AvailabilityZone: b.config.AvailabilityZone, 137 BlockDevices: b.config.BlockDevices, 138 Tags: b.config.RunTags, 139 InstanceInitiatedShutdownBehavior: b.config.InstanceInitiatedShutdownBehavior, 140 }, 141 &stepTagEBSVolumes{ 142 VolumeRunTags: b.config.VolumeRunTags, 143 }, 144 &awscommon.StepGetPassword{ 145 Debug: b.config.PackerDebug, 146 Comm: &b.config.RunConfig.Comm, 147 Timeout: b.config.WindowsPasswordTimeout, 148 }, 149 &communicator.StepConnect{ 150 Config: &b.config.RunConfig.Comm, 151 Host: awscommon.SSHHost( 152 ec2conn, 153 b.config.SSHPrivateIp), 154 SSHConfig: awscommon.SSHConfig( 155 b.config.RunConfig.Comm.SSHAgentAuth, 156 b.config.RunConfig.Comm.SSHUsername, 157 b.config.RunConfig.Comm.SSHPassword), 158 }, 159 &common.StepProvision{}, 160 &awscommon.StepStopEBSBackedInstance{ 161 SpotPrice: b.config.SpotPrice, 162 DisableStopInstance: b.config.DisableStopInstance, 163 }, 164 &awscommon.StepModifyEBSBackedInstance{ 165 EnableEnhancedNetworking: b.config.AMIEnhancedNetworking, 166 }, 167 &awscommon.StepDeregisterAMI{ 168 ForceDeregister: b.config.AMIForceDeregister, 169 AMIName: b.config.AMIName, 170 }, 171 &stepCreateAMI{}, 172 &stepCreateEncryptedAMICopy{}, 173 &awscommon.StepAMIRegionCopy{ 174 AccessConfig: &b.config.AccessConfig, 175 Regions: b.config.AMIRegions, 176 Name: b.config.AMIName, 177 }, 178 &awscommon.StepModifyAMIAttributes{ 179 Description: b.config.AMIDescription, 180 Users: b.config.AMIUsers, 181 Groups: b.config.AMIGroups, 182 ProductCodes: b.config.AMIProductCodes, 183 }, 184 &awscommon.StepCreateTags{ 185 Tags: b.config.AMITags, 186 }, 187 } 188 189 // Run! 190 b.runner = common.NewRunner(steps, b.config.PackerConfig, ui) 191 b.runner.Run(state) 192 193 // If there was an error, return that 194 if rawErr, ok := state.GetOk("error"); ok { 195 return nil, rawErr.(error) 196 } 197 198 // If there are no AMIs, then just return 199 if _, ok := state.GetOk("amis"); !ok { 200 return nil, nil 201 } 202 203 // Build the artifact and return it 204 artifact := &awscommon.Artifact{ 205 Amis: state.Get("amis").(map[string]string), 206 BuilderIdValue: BuilderId, 207 Conn: ec2conn, 208 } 209 210 return artifact, nil 211 } 212 213 func (b *Builder) Cancel() { 214 if b.runner != nil { 215 log.Println("Cancelling the step runner...") 216 b.runner.Cancel() 217 } 218 }