github.com/emc-advanced-dev/unik@v0.0.0-20190717152701-a58d3e8e33b7/pkg/providers/aws/delete_image.go (about)

     1  package aws
     2  
     3  import (
     4  	"github.com/aws/aws-sdk-go/aws"
     5  	"github.com/aws/aws-sdk-go/service/ec2"
     6  	"github.com/emc-advanced-dev/pkg/errors"
     7  )
     8  
     9  func (p *AwsProvider) DeleteImage(id string, force bool) error {
    10  	image, err := p.GetImage(id)
    11  	if err != nil {
    12  		return errors.New("retrieving image", err)
    13  	}
    14  	instances, err := p.ListInstances()
    15  	if err != nil {
    16  		return errors.New("retrieving list of instances", err)
    17  	}
    18  	for _, instance := range instances {
    19  		if instance.ImageId == image.Id {
    20  			if !force {
    21  				return errors.New("instance "+instance.Id+" found which uses image "+image.Id+"; try again with force=true", nil)
    22  			} else {
    23  				err = p.DeleteInstance(instance.Id, true)
    24  				if err != nil {
    25  					return errors.New("failed to delete instance "+instance.Id+" which is using image "+image.Id, err)
    26  				}
    27  			}
    28  		}
    29  	}
    30  
    31  	ec2svc := p.newEC2()
    32  	deleteAmiParam := &ec2.DeregisterImageInput{
    33  		ImageId: aws.String(image.Id),
    34  	}
    35  	_, err = ec2svc.DeregisterImage(deleteAmiParam)
    36  	if err != nil {
    37  		return errors.New("failed deleting image "+image.Id, err)
    38  	}
    39  
    40  	snap, err := getSnapshotForImage(ec2svc, image.Id)
    41  	if err != nil {
    42  		return err
    43  	}
    44  	deleteSnapshotParam := &ec2.DeleteSnapshotInput{
    45  		SnapshotId: aws.String(*snap.SnapshotId),
    46  	}
    47  	if _, err := ec2svc.DeleteSnapshot(deleteSnapshotParam); err != nil {
    48  		return errors.New("failed deleting snapshot "+*snap.SnapshotId, err)
    49  	}
    50  	deleteVolumeParam := &ec2.DeleteVolumeInput{
    51  		VolumeId: aws.String(*snap.VolumeId),
    52  	}
    53  	if _, err := ec2svc.DeleteVolume(deleteVolumeParam); err != nil {
    54  		return errors.New("failed deleting volumme "+*snap.VolumeId, err)
    55  	}
    56  	return p.state.RemoveImage(image)
    57  }
    58  
    59  func getSnapshotForImage(ec2svc *ec2.EC2, imageId string) (*ec2.Snapshot, error) {
    60  	describeSnapshotsOutput, err := ec2svc.DescribeSnapshots(&ec2.DescribeSnapshotsInput{})
    61  	if err != nil {
    62  		return nil, errors.New("getting ec2 snapshot list", err)
    63  	}
    64  
    65  	for _, snapshot := range describeSnapshotsOutput.Snapshots {
    66  		for _, tag := range snapshot.Tags {
    67  			if *tag.Key == UNIK_IMAGE_ID && *tag.Value == imageId {
    68  				return snapshot, nil
    69  			}
    70  		}
    71  	}
    72  	return nil, errors.New("snapshot for image "+imageId+" not found", nil)
    73  }