Skip to content
This repository has been archived by the owner on Oct 15, 2024. It is now read-only.

Commit

Permalink
Merge pull request #417 from jbmchuck/ec2termpro
Browse files Browse the repository at this point in the history
Terminate protected EC2 instances
  • Loading branch information
svenwltr authored Oct 28, 2019
2 parents 498111e + 7c882c3 commit d38e638
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
1 change: 1 addition & 0 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ type Nuke struct {
type FeatureFlags struct {
DisableDeletionProtection struct {
RDSInstance bool `yaml:"RDSInstance"`
EC2Instance bool `yaml:"EC2Instance"`
} `yaml:"disable-deletion-protection"`
}

Expand Down
38 changes: 38 additions & 0 deletions resources/ec2-instances.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,19 @@ package resources
import (
"fmt"

"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/rebuy-de/aws-nuke/pkg/config"
"github.com/rebuy-de/aws-nuke/pkg/types"
)

type EC2Instance struct {
svc *ec2.EC2
instance *ec2.Instance

featureFlags config.FeatureFlags
}

func init() {
Expand Down Expand Up @@ -48,6 +53,10 @@ func ListEC2Instances(sess *session.Session) ([]Resource, error) {
return resources, nil
}

func (i *EC2Instance) FeatureFlags(ff config.FeatureFlags) {
i.featureFlags = ff
}

func (i *EC2Instance) Filter() error {
if *i.instance.State.Name == "terminated" {
return fmt.Errorf("already terminated")
Expand All @@ -62,9 +71,38 @@ func (i *EC2Instance) Remove() error {

_, err := i.svc.TerminateInstances(params)
if err != nil {
if i.featureFlags.DisableDeletionProtection.EC2Instance {
awsErr, ok := err.(awserr.Error)
if ok && awsErr.Code() == "OperationNotPermitted" &&
awsErr.Message() == "The instance '"+*i.instance.InstanceId+"' may not be terminated. "+
"Modify its 'disableApiTermination' instance attribute and try again." {
err = i.DisableProtection()
if err != nil {
return err
}
_, err := i.svc.TerminateInstances(params)
if err != nil {
return err
}
return nil
}
}
return err
}
return nil
}

func (i *EC2Instance) DisableProtection() error {
params := &ec2.ModifyInstanceAttributeInput{
InstanceId: i.instance.InstanceId,
DisableApiTermination: &ec2.AttributeBooleanValue{
Value: aws.Bool(false),
},
}
_, err := i.svc.ModifyInstanceAttribute(params)
if err != nil {
return err
}
return nil
}

Expand Down

0 comments on commit d38e638

Please sign in to comment.