github.phpd.cn/hashicorp/packer@v1.3.2/builder/amazon/ebsvolume/artifact.go (about)

     1  package ebsvolume
     2  
     3  import (
     4  	"fmt"
     5  	"log"
     6  	"sort"
     7  	"strings"
     8  
     9  	"github.com/aws/aws-sdk-go/service/ec2"
    10  	"github.com/hashicorp/packer/packer"
    11  )
    12  
    13  // map of region to list of volume IDs
    14  type EbsVolumes map[string][]string
    15  
    16  // Artifact is an artifact implementation that contains built AMIs.
    17  type Artifact struct {
    18  	// A map of regions to EBS Volume IDs.
    19  	Volumes EbsVolumes
    20  
    21  	// BuilderId is the unique ID for the builder that created this AMI
    22  	BuilderIdValue string
    23  
    24  	// EC2 connection for performing API stuff.
    25  	Conn *ec2.EC2
    26  }
    27  
    28  func (a *Artifact) BuilderId() string {
    29  	return a.BuilderIdValue
    30  }
    31  
    32  func (*Artifact) Files() []string {
    33  	// We have no files
    34  	return nil
    35  }
    36  
    37  // returns a sorted list of region:ID pairs
    38  func (a *Artifact) idList() []string {
    39  	parts := make([]string, 0, len(a.Volumes))
    40  	for region, volumeIDs := range a.Volumes {
    41  		for _, volumeID := range volumeIDs {
    42  			parts = append(parts, fmt.Sprintf("%s:%s", region, volumeID))
    43  		}
    44  	}
    45  
    46  	sort.Strings(parts)
    47  	return parts
    48  }
    49  
    50  func (a *Artifact) Id() string {
    51  	return strings.Join(a.idList(), ",")
    52  }
    53  
    54  func (a *Artifact) String() string {
    55  	return fmt.Sprintf("EBS Volumes were created:\n\n%s", strings.Join(a.idList(), "\n"))
    56  }
    57  
    58  func (a *Artifact) State(name string) interface{} {
    59  	return nil
    60  }
    61  
    62  func (a *Artifact) Destroy() error {
    63  	errors := make([]error, 0)
    64  
    65  	for region, volumeIDs := range a.Volumes {
    66  		for _, volumeID := range volumeIDs {
    67  			log.Printf("Deregistering Volume ID (%s) from region (%s)", volumeID, region)
    68  
    69  			input := &ec2.DeleteVolumeInput{
    70  				VolumeId: &volumeID,
    71  			}
    72  			if _, err := a.Conn.DeleteVolume(input); err != nil {
    73  				errors = append(errors, err)
    74  			}
    75  		}
    76  	}
    77  
    78  	if len(errors) > 0 {
    79  		if len(errors) == 1 {
    80  			return errors[0]
    81  		} else {
    82  			return &packer.MultiError{Errors: errors}
    83  		}
    84  	}
    85  
    86  	return nil
    87  }