github.com/mmcquillan/packer@v1.1.1-0.20171009221028-c85cf0483a5d/builder/alicloud/ecs/step_region_copy_image.go (about)

     1  package ecs
     2  
     3  import (
     4  	"fmt"
     5  
     6  	"github.com/denverdino/aliyungo/common"
     7  	"github.com/denverdino/aliyungo/ecs"
     8  	"github.com/hashicorp/packer/packer"
     9  	"github.com/mitchellh/multistep"
    10  )
    11  
    12  type setpRegionCopyAlicloudImage struct {
    13  	AlicloudImageDestinationRegions []string
    14  	AlicloudImageDestinationNames   []string
    15  	RegionId                        string
    16  }
    17  
    18  func (s *setpRegionCopyAlicloudImage) Run(state multistep.StateBag) multistep.StepAction {
    19  	if len(s.AlicloudImageDestinationRegions) == 0 {
    20  		return multistep.ActionContinue
    21  	}
    22  	client := state.Get("client").(*ecs.Client)
    23  	ui := state.Get("ui").(packer.Ui)
    24  	imageId := state.Get("alicloudimage").(string)
    25  	alicloudImages := state.Get("alicloudimages").(map[string]string)
    26  	region := common.Region(s.RegionId)
    27  
    28  	numberOfName := len(s.AlicloudImageDestinationNames)
    29  	for index, destinationRegion := range s.AlicloudImageDestinationRegions {
    30  		if destinationRegion == s.RegionId {
    31  			continue
    32  		}
    33  		ecsImageName := ""
    34  		if numberOfName > 0 && index < numberOfName {
    35  			ecsImageName = s.AlicloudImageDestinationNames[index]
    36  		}
    37  		imageId, err := client.CopyImage(
    38  			&ecs.CopyImageArgs{
    39  				RegionId:             region,
    40  				ImageId:              imageId,
    41  				DestinationRegionId:  common.Region(destinationRegion),
    42  				DestinationImageName: ecsImageName,
    43  			})
    44  		if err != nil {
    45  			state.Put("error", err)
    46  			ui.Say(fmt.Sprintf("Error copying images: %s", err))
    47  			return multistep.ActionHalt
    48  		}
    49  		alicloudImages[destinationRegion] = imageId
    50  	}
    51  	return multistep.ActionContinue
    52  }
    53  
    54  func (s *setpRegionCopyAlicloudImage) Cleanup(state multistep.StateBag) {
    55  	_, cancelled := state.GetOk(multistep.StateCancelled)
    56  	_, halted := state.GetOk(multistep.StateHalted)
    57  	if cancelled || halted {
    58  		ui := state.Get("ui").(packer.Ui)
    59  		client := state.Get("client").(*ecs.Client)
    60  		alicloudImages := state.Get("alicloudimages").(map[string]string)
    61  		ui.Say(fmt.Sprintf("Stopping copy image because cancellation or error..."))
    62  		for copyedRegionId, copyedImageId := range alicloudImages {
    63  			if copyedRegionId == s.RegionId {
    64  				continue
    65  			}
    66  			if err := client.CancelCopyImage(common.Region(copyedRegionId), copyedImageId); err != nil {
    67  				ui.Say(fmt.Sprintf("Error cancelling copy image: %v", err))
    68  			}
    69  		}
    70  	}
    71  }