github.phpd.cn/hashicorp/packer@v1.3.2/builder/alicloud/ecs/step_region_copy_image.go (about)

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