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

     1  package ecs
     2  
     3  import (
     4  	"context"
     5  	"fmt"
     6  	"log"
     7  
     8  	"github.com/denverdino/aliyungo/common"
     9  	"github.com/denverdino/aliyungo/ecs"
    10  	"github.com/hashicorp/packer/helper/multistep"
    11  	"github.com/hashicorp/packer/packer"
    12  )
    13  
    14  type stepDeleteAlicloudImageSnapshots struct {
    15  	AlicloudImageForceDelete          bool
    16  	AlicloudImageForceDeleteSnapshots bool
    17  	AlicloudImageName                 string
    18  }
    19  
    20  func (s *stepDeleteAlicloudImageSnapshots) Run(_ context.Context, state multistep.StateBag) multistep.StepAction {
    21  	client := state.Get("client").(*ecs.Client)
    22  	ui := state.Get("ui").(packer.Ui)
    23  	config := state.Get("config").(*Config)
    24  
    25  	// Check for force delete
    26  	if s.AlicloudImageForceDelete {
    27  		images, _, err := client.DescribeImages(&ecs.DescribeImagesArgs{
    28  			RegionId:  common.Region(config.AlicloudRegion),
    29  			ImageName: s.AlicloudImageName,
    30  		})
    31  		if len(images) < 1 {
    32  			return multistep.ActionContinue
    33  		}
    34  
    35  		ui.Say(fmt.Sprintf("Deleting duplicated image and snapshot: %s", s.AlicloudImageName))
    36  
    37  		for _, image := range images {
    38  			if image.ImageOwnerAlias != string(ecs.ImageOwnerSelf) {
    39  				log.Printf("You can only delete instances based on customized images %s ", image.ImageId)
    40  				continue
    41  			}
    42  			err = client.DeleteImage(common.Region(config.AlicloudRegion), image.ImageId)
    43  			if err != nil {
    44  				err := fmt.Errorf("Failed to delete image: %s", err)
    45  				state.Put("error", err)
    46  				ui.Error(err.Error())
    47  				return multistep.ActionHalt
    48  			}
    49  			if s.AlicloudImageForceDeleteSnapshots {
    50  				for _, diskDevice := range image.DiskDeviceMappings.DiskDeviceMapping {
    51  					if err := client.DeleteSnapshot(diskDevice.SnapshotId); err != nil {
    52  						err := fmt.Errorf("Deleting ECS snapshot failed: %s", err)
    53  						state.Put("error", err)
    54  						ui.Error(err.Error())
    55  						return multistep.ActionHalt
    56  					}
    57  				}
    58  			}
    59  		}
    60  
    61  	}
    62  
    63  	return multistep.ActionContinue
    64  }
    65  
    66  func (s *stepDeleteAlicloudImageSnapshots) Cleanup(state multistep.StateBag) {
    67  }