2020-03-13 12:10:51 -04:00
|
|
|
package testshelper
|
2020-03-13 11:17:40 -04:00
|
|
|
|
|
|
|
import (
|
2020-04-03 12:17:09 -04:00
|
|
|
"fmt"
|
2020-03-13 11:17:40 -04:00
|
|
|
"github.com/aws/aws-sdk-go/aws"
|
|
|
|
"github.com/aws/aws-sdk-go/service/ec2"
|
|
|
|
awscommon "github.com/hashicorp/packer/builder/amazon/common"
|
|
|
|
)
|
|
|
|
|
|
|
|
type AWSHelper struct {
|
2020-03-13 11:36:30 -04:00
|
|
|
Region string
|
2020-03-13 11:17:40 -04:00
|
|
|
AMIName string
|
|
|
|
}
|
|
|
|
|
2020-04-03 12:17:09 -04:00
|
|
|
func (a *AWSHelper) CleanUpAmi() error {
|
2020-03-13 11:17:40 -04:00
|
|
|
accessConfig := &awscommon.AccessConfig{}
|
|
|
|
session, err := accessConfig.Session()
|
|
|
|
if err != nil {
|
2020-04-03 12:17:09 -04:00
|
|
|
return fmt.Errorf("AWSAMICleanUp: Unable to create aws session %s", err.Error())
|
2020-03-13 11:17:40 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
regionconn := ec2.New(session.Copy(&aws.Config{
|
|
|
|
Region: aws.String(a.Region),
|
|
|
|
}))
|
|
|
|
|
|
|
|
resp, err := regionconn.DescribeImages(&ec2.DescribeImagesInput{
|
|
|
|
Owners: aws.StringSlice([]string{"self"}),
|
|
|
|
Filters: []*ec2.Filter{{
|
|
|
|
Name: aws.String("name"),
|
|
|
|
Values: aws.StringSlice([]string{a.AMIName}),
|
|
|
|
}}})
|
|
|
|
if err != nil {
|
2020-04-03 12:17:09 -04:00
|
|
|
return fmt.Errorf("AWSAMICleanUp: Unable to find Image %s: %s", a.AMIName, err.Error())
|
2020-03-13 11:17:40 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
_, err = regionconn.DeregisterImage(&ec2.DeregisterImageInput{
|
|
|
|
ImageId: resp.Images[0].ImageId,
|
|
|
|
})
|
|
|
|
if err != nil {
|
2020-04-03 12:17:09 -04:00
|
|
|
return fmt.Errorf("AWSAMICleanUp: Unable to Deregister Image %s", err.Error())
|
2020-03-13 11:17:40 -04:00
|
|
|
}
|
2020-04-03 12:17:09 -04:00
|
|
|
return nil
|
2020-03-13 11:36:30 -04:00
|
|
|
}
|