github.phpd.cn/hashicorp/packer@v1.3.2/builder/alicloud/ecs/step_share_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 stepShareAlicloudImage struct {
    14  	AlicloudImageShareAccounts   []string
    15  	AlicloudImageUNShareAccounts []string
    16  	RegionId                     string
    17  }
    18  
    19  func (s *stepShareAlicloudImage) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
    20  	client := state.Get("client").(*ecs.Client)
    21  	ui := state.Get("ui").(packer.Ui)
    22  	alicloudImages := state.Get("alicloudimages").(map[string]string)
    23  	for copiedRegion, copiedImageId := range alicloudImages {
    24  		err := client.ModifyImageSharePermission(
    25  			&ecs.ModifyImageSharePermissionArgs{
    26  				RegionId:      common.Region(copiedRegion),
    27  				ImageId:       copiedImageId,
    28  				AddAccount:    s.AlicloudImageShareAccounts,
    29  				RemoveAccount: s.AlicloudImageUNShareAccounts,
    30  			})
    31  		if err != nil {
    32  			state.Put("error", err)
    33  			ui.Say(fmt.Sprintf("Failed modifying image share permissions: %s", err))
    34  			return multistep.ActionHalt
    35  		}
    36  	}
    37  	return multistep.ActionContinue
    38  }
    39  
    40  func (s *stepShareAlicloudImage) Cleanup(state multistep.StateBag) {
    41  	_, cancelled := state.GetOk(multistep.StateCancelled)
    42  	_, halted := state.GetOk(multistep.StateHalted)
    43  	if cancelled || halted {
    44  		ui := state.Get("ui").(packer.Ui)
    45  		client := state.Get("client").(*ecs.Client)
    46  		alicloudImages := state.Get("alicloudimages").(map[string]string)
    47  		ui.Say("Restoring image share permission because cancellations or error...")
    48  		for copiedRegion, copiedImageId := range alicloudImages {
    49  			err := client.ModifyImageSharePermission(
    50  				&ecs.ModifyImageSharePermissionArgs{
    51  					RegionId:      common.Region(copiedRegion),
    52  					ImageId:       copiedImageId,
    53  					AddAccount:    s.AlicloudImageUNShareAccounts,
    54  					RemoveAccount: s.AlicloudImageShareAccounts,
    55  				})
    56  			if err != nil {
    57  				ui.Say(fmt.Sprintf("Restoring image share permission failed: %s", err))
    58  			}
    59  		}
    60  	}
    61  }