/
cloudformation-stack.go
103 lines (85 loc) · 2.31 KB
/
cloudformation-stack.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
package resources
import (
"errors"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/rebuy-de/aws-nuke/pkg/types"
)
func init() {
register("CloudFormationStack", ListCloudFormationStacks)
}
func ListCloudFormationStacks(sess *session.Session) ([]Resource, error) {
svc := cloudformation.New(sess)
params := &cloudformation.DescribeStacksInput{}
resources := make([]Resource, 0)
for {
resp, err := svc.DescribeStacks(params)
if err != nil {
return nil, err
}
for _, stack := range resp.Stacks {
resources = append(resources, &CloudFormationStack{
svc: svc,
stack: stack,
})
}
if resp.NextToken == nil {
break
}
params.NextToken = resp.NextToken
}
return resources, nil
}
type CloudFormationStack struct {
svc *cloudformation.CloudFormation
stack *cloudformation.Stack
}
func (cfs *CloudFormationStack) Remove() error {
o, err := cfs.svc.DescribeStacks(&cloudformation.DescribeStacksInput{
StackName: cfs.stack.StackName,
})
if err != nil {
return err
}
stack := o.Stacks[0]
if *stack.StackStatus != cloudformation.StackStatusDeleteFailed {
cfs.svc.DeleteStack(&cloudformation.DeleteStackInput{
StackName: stack.StackName,
})
return errors.New("CFS might not be deleted after this run.")
} else {
// This means the CFS has undeleteable resources.
// In order to move on with nuking, we retain them in the deletion.
retainableResources, err := cfs.svc.ListStackResources(&cloudformation.ListStackResourcesInput{
StackName: stack.StackName,
})
if err != nil {
return err
}
retain := make([]*string, 0)
for _, r := range retainableResources.StackResourceSummaries {
if *r.ResourceStatus != "DELETE_COMPLETE" {
retain = append(retain, r.LogicalResourceId)
}
}
_, err = cfs.svc.DeleteStack(&cloudformation.DeleteStackInput{
StackName: stack.StackName,
RetainResources: retain,
})
if err != nil {
return err
}
return nil
}
}
func (cfs *CloudFormationStack) Properties() types.Properties {
properties := types.NewProperties()
properties.Set("Name", cfs.stack.StackName)
for _, tagValue := range cfs.stack.Tags {
properties.SetTag(tagValue.Key, tagValue.Value)
}
return properties
}
func (cfs *CloudFormationStack) String() string {
return *cfs.stack.StackName
}