github.com/StackPointCloud/packer@v0.10.2-0.20180716202532-b28098e0f79b/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  	ui.Say("Deleting image snapshots.")
    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  		for _, image := range images {
    35  			if image.ImageOwnerAlias != string(ecs.ImageOwnerSelf) {
    36  				log.Printf("You can only delete instances based on customized images %s ", image.ImageId)
    37  				continue
    38  			}
    39  			err = client.DeleteImage(common.Region(config.AlicloudRegion), image.ImageId)
    40  			if err != nil {
    41  				err := fmt.Errorf("Failed to delete image: %s", err)
    42  				state.Put("error", err)
    43  				ui.Error(err.Error())
    44  				return multistep.ActionHalt
    45  			}
    46  			if s.AlicloudImageForceDeleteSnapshots {
    47  				for _, diskDevice := range image.DiskDeviceMappings.DiskDeviceMapping {
    48  					if err := client.DeleteSnapshot(diskDevice.SnapshotId); err != nil {
    49  						err := fmt.Errorf("Deleting ECS snapshot failed: %s", err)
    50  						state.Put("error", err)
    51  						ui.Error(err.Error())
    52  						return multistep.ActionHalt
    53  					}
    54  				}
    55  			}
    56  		}
    57  
    58  	}
    59  
    60  	return multistep.ActionContinue
    61  }
    62  
    63  func (s *stepDeleteAlicloudImageSnapshots) Cleanup(state multistep.StateBag) {
    64  }