Skip to content

Commit

Permalink
Move code to filter unprotected ec2 instances to separate function
Browse files Browse the repository at this point in the history
  • Loading branch information
tonerdo committed Jan 25, 2018
1 parent b4341c7 commit 1aa2611
Showing 1 changed file with 28 additions and 29 deletions.
57 changes: 28 additions & 29 deletions aws/ec2.go
Original file line number Diff line number Diff line change
@@ -1,22 +1,38 @@
package aws

import (
"fmt"

awsgo "github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/gruntwork-io/aws-nuke/logging"
"github.com/gruntwork-io/gruntwork-cli/errors"
)

// Build string that'll be shown in resources list
func buildEntryName(instance ec2.Instance) string {
return fmt.Sprintf(
"ec2-%s-%s",
awsgo.StringValue(instance.InstanceId),
awsgo.StringValue(instance.InstanceType),
)
// returns only instance Ids of unprotected ec2 instances
func filterOutProtectedInstances(svc *ec2.EC2, output *ec2.DescribeInstancesOutput) ([]*string, error) {
var filteredIds []*string
for _, reservation := range output.Reservations {
for _, instance := range reservation.Instances {
instanceID := *instance.InstanceId

attr, err := svc.DescribeInstanceAttribute(&ec2.DescribeInstanceAttributeInput{
Attribute: awsgo.String("disableApiTermination"),
InstanceId: awsgo.String(instanceID),
})

if err != nil {
return nil, errors.WithStackTrace(err)
}

protected := *attr.DisableApiTermination.Value
// Exclude protected EC2 instances
if !protected {
filteredIds = append(filteredIds, &instanceID)
}
}
}

return filteredIds, nil
}

// Returns a formatted string of EC2 instance ids
Expand All @@ -40,26 +56,9 @@ func getAllEc2Instances(session *session.Session, region string) ([]*string, err
return nil, errors.WithStackTrace(err)
}

var instanceIds []*string
for _, reservation := range output.Reservations {
for _, instance := range reservation.Instances {
instanceID := *instance.InstanceId

attr, err := svc.DescribeInstanceAttribute(&ec2.DescribeInstanceAttributeInput{
Attribute: awsgo.String("disableApiTermination"),
InstanceId: awsgo.String(instanceID),
})

if err != nil {
return nil, errors.WithStackTrace(err)
}

protected := *attr.DisableApiTermination.Value
// Exclude protected EC2 instances
if !protected {
instanceIds = append(instanceIds, &instanceID)
}
}
instanceIds, err := filterOutProtectedInstances(svc, output)
if err != nil {
return nil, errors.WithStackTrace(err)
}

return instanceIds, nil
Expand Down

0 comments on commit 1aa2611

Please sign in to comment.