github.com/askholme/packer@v0.7.2-0.20140924152349-70d9566a6852/builder/amazon/common/artifact.go (about)

     1  package common
     2  
     3  import (
     4  	"fmt"
     5  	"github.com/mitchellh/goamz/aws"
     6  	"github.com/mitchellh/goamz/ec2"
     7  	"github.com/mitchellh/packer/packer"
     8  	"log"
     9  	"sort"
    10  	"strings"
    11  )
    12  
    13  // Artifact is an artifact implementation that contains built AMIs.
    14  type Artifact struct {
    15  	// A map of regions to AMI IDs.
    16  	Amis map[string]string
    17  
    18  	// BuilderId is the unique ID for the builder that created this AMI
    19  	BuilderIdValue string
    20  
    21  	// EC2 connection for performing API stuff.
    22  	Conn *ec2.EC2
    23  }
    24  
    25  func (a *Artifact) BuilderId() string {
    26  	return a.BuilderIdValue
    27  }
    28  
    29  func (*Artifact) Files() []string {
    30  	// We have no files
    31  	return nil
    32  }
    33  
    34  func (a *Artifact) Id() string {
    35  	parts := make([]string, 0, len(a.Amis))
    36  	for region, amiId := range a.Amis {
    37  		parts = append(parts, fmt.Sprintf("%s:%s", region, amiId))
    38  	}
    39  
    40  	sort.Strings(parts)
    41  	return strings.Join(parts, ",")
    42  }
    43  
    44  func (a *Artifact) String() string {
    45  	amiStrings := make([]string, 0, len(a.Amis))
    46  	for region, id := range a.Amis {
    47  		single := fmt.Sprintf("%s: %s", region, id)
    48  		amiStrings = append(amiStrings, single)
    49  	}
    50  
    51  	sort.Strings(amiStrings)
    52  	return fmt.Sprintf("AMIs were created:\n\n%s", strings.Join(amiStrings, "\n"))
    53  }
    54  
    55  func (a *Artifact) Destroy() error {
    56  	errors := make([]error, 0)
    57  
    58  	for region, imageId := range a.Amis {
    59  		log.Printf("Deregistering image ID (%s) from region (%s)", imageId, region)
    60  		regionconn := ec2.New(a.Conn.Auth, aws.Regions[region])
    61  		if _, err := regionconn.DeregisterImage(imageId); err != nil {
    62  			errors = append(errors, err)
    63  		}
    64  
    65  		// TODO(mitchellh): Delete the snapshots associated with an AMI too
    66  	}
    67  
    68  	if len(errors) > 0 {
    69  		if len(errors) == 1 {
    70  			return errors[0]
    71  		} else {
    72  			return &packer.MultiError{errors}
    73  		}
    74  	}
    75  
    76  	return nil
    77  }