github.com/jerryclinesmith/packer@v0.3.7/builder/amazon/common/step_ami_region_copy.go (about)

     1  package common
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/mitchellh/goamz/aws"
     6  	"github.com/mitchellh/goamz/ec2"
     7  	"github.com/mitchellh/multistep"
     8  	"github.com/mitchellh/packer/packer"
     9  )
    10  
    11  type StepAMIRegionCopy struct {
    12  	Regions []string
    13  }
    14  
    15  func (s *StepAMIRegionCopy) Run(state multistep.StateBag) multistep.StepAction {
    16  	ec2conn := state.Get("ec2").(*ec2.EC2)
    17  	ui := state.Get("ui").(packer.Ui)
    18  	amis := state.Get("amis").(map[string]string)
    19  	ami := amis[ec2conn.Region.Name]
    20  
    21  	if len(s.Regions) == 0 {
    22  		return multistep.ActionContinue
    23  	}
    24  
    25  	ui.Say(fmt.Sprintf("Copying AMI (%s) to other regions...", ami))
    26  	for _, region := range s.Regions {
    27  		ui.Message(fmt.Sprintf("Copying to: %s", region))
    28  
    29  		// Connect to the region where the AMI will be copied to
    30  		regionconn := ec2.New(ec2conn.Auth, aws.Regions[region])
    31  		resp, err := regionconn.CopyImage(&ec2.CopyImage{
    32  			SourceRegion:  ec2conn.Region.Name,
    33  			SourceImageId: ami,
    34  		})
    35  
    36  		if err != nil {
    37  			err := fmt.Errorf("Error Copying AMI (%s) to region (%s): %s", ami, region, err)
    38  			state.Put("error", err)
    39  			ui.Error(err.Error())
    40  			return multistep.ActionHalt
    41  		}
    42  
    43  		ui.Say(fmt.Sprintf("Waiting for AMI (%s) in region (%s) to become ready...", resp.ImageId, region))
    44  		if err := WaitForAMI(regionconn, resp.ImageId); err != nil {
    45  			err := fmt.Errorf("Error waiting for AMI (%s) in region (%s): %s", resp.ImageId, region, err)
    46  			state.Put("error", err)
    47  			ui.Error(err.Error())
    48  			return multistep.ActionHalt
    49  		}
    50  
    51  		amis[region] = resp.ImageId
    52  	}
    53  
    54  	state.Put("amis", amis)
    55  	return multistep.ActionContinue
    56  }
    57  
    58  func (s *StepAMIRegionCopy) Cleanup(state multistep.StateBag) {
    59  	// No cleanup...
    60  }