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

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