-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcloudformation.go
249 lines (197 loc) · 7.01 KB
/
cloudformation.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
// Package godeploycfn allows deployment of a Cloudformation template to be a bit easier
package godeploycfn
import (
"context"
"fmt"
"strings"
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/aws/aws-sdk-go/service/cloudformation/cloudformationiface"
"github.com/cenkalti/backoff/v4"
"github.com/google/uuid"
"github.com/sirupsen/logrus"
)
const (
maxRetryTimeForStack = time.Minute * 10
initialRetryPeriod = 12 * time.Second
maxRetryInterval = time.Minute
)
// Cloudformation is a utility wrapper around the original aws api to make
// common operations more intuitive.
type Cloudformation struct {
CFClient cloudformationiface.CloudFormationAPI
StackName string
LogrusEntry *logrus.Entry
}
// CloudformationAPI provides an API which can be used instead of a concrete client for testing/mocking purposes.
type CloudformationAPI interface {
CloudFormationDeploy(templateBody string, namedIAM bool) error
}
func (c *Cloudformation) logger() *logrus.Entry {
stackFields := logrus.Fields{
"stack_name": c.StackName,
}
if c.LogrusEntry == nil {
return logrus.WithFields(stackFields)
}
return c.LogrusEntry.WithFields(stackFields)
}
func changeSetIsEmpty(o *cloudformation.DescribeChangeSetOutput) bool {
// Seems absurd but looks like this is the best way to find out if the ChangeSet is empty.
return *o.Status == "FAILED" && strings.Contains(*o.StatusReason, "submitted information didn't contain changes")
}
func (c *Cloudformation) getCreateType() (string, error) {
changeSetType := "UPDATE"
//nolint
dsi := &cloudformation.DescribeStacksInput{
StackName: aws.String(c.StackName),
}
_, err := c.CFClient.DescribeStacks(dsi)
if err != nil && !strings.Contains(err.Error(), "does not exist") {
return "", fmt.Errorf("unexpected error while describing stack: %w", err)
}
if err != nil {
changeSetType = "CREATE"
}
return changeSetType, nil
}
func trimStackName(stackName string, max int) string {
var sn string
switch {
case len(stackName) <= max:
sn = stackName
case len(stackName) > max:
sn = stackName[0:max]
}
return sn
}
func (c *Cloudformation) executeChangeSet(changeSetName string) error {
//nolint
ecsi := &cloudformation.ExecuteChangeSetInput{
ChangeSetName: aws.String(changeSetName),
StackName: aws.String(c.StackName),
}
_, err := c.CFClient.ExecuteChangeSet(ecsi)
if err != nil {
return fmt.Errorf("error executing the ChangeSet: %w", err)
}
endRetryTimestamp := time.Now().Add(maxRetryTimeForStack)
back := &backoff.ExponentialBackOff{
InitialInterval: initialRetryPeriod,
RandomizationFactor: backoff.DefaultRandomizationFactor,
Multiplier: backoff.DefaultMultiplier,
MaxInterval: maxRetryInterval,
MaxElapsedTime: maxRetryTimeForStack,
Stop: backoff.Stop,
Clock: backoff.SystemClock,
}
var errToReturn error
err = backoff.Retry(func() error {
var dso *cloudformation.DescribeStacksOutput
dso, err = c.CFClient.DescribeStacks(&cloudformation.DescribeStacksInput{
NextToken: nil,
StackName: aws.String(c.StackName),
})
if err != nil {
return fmt.Errorf("encountered an error when describing the stack: %w", err)
}
if len(dso.Stacks) != 1 {
errToReturn = fmt.Errorf("unexpected (!=1) number of stacks in result: %v", len(dso.Stacks))
return nil
}
stackStatus := *dso.Stacks[0].StackStatus
switch stackStatus {
case cloudformation.StackStatusUpdateComplete, cloudformation.StackStatusCreateComplete, cloudformation.StackStatusUpdateCompleteCleanupInProgress:
c.logger().Infof("ChangeSet '%s' has been successfully executed.", changeSetName)
return nil
case cloudformation.StackStatusCreateInProgress, cloudformation.StackStatusUpdateInProgress:
c.logger().Infof("Stack update still in progress. Will check again. Will stop making more attempts to deploy after %s.",
endRetryTimestamp.Format(time.RFC3339))
return fmt.Errorf("stack creation not complete yet, status: %s", stackStatus)
}
errToReturn = fmt.Errorf("unexpected stack status for stack %s: %s", *dso.Stacks[0].StackName, stackStatus)
return nil
}, back)
if err != nil {
return fmt.Errorf("retryable state occurred but maximum retry period of %s has passed, so we'll stop trying: %w",
maxRetryTimeForStack, err)
}
return errToReturn
}
// CloudFormationDeploy deploys the given Cloudformation Template to the given Cloudformation Stack.
func (c *Cloudformation) CloudFormationDeploy(templateBody string, namedIAM bool) error {
changeSetType, err := c.getCreateType()
if err != nil {
return err
}
id, err := uuid.NewUUID()
if err != nil {
return fmt.Errorf("error while generating UUID %w", err)
}
// max stack name is 128, then we add a UUID (36 byte/char string) so the max the stackName can be is 92
// we also add a `-' here, so adjust for that accordingly
csn := fmt.Sprintf("%s-%s", trimStackName(c.StackName, 91), id)
// normally, the max we can have is 128
sn := trimStackName(c.StackName, 128)
//nolint
ccsi := &cloudformation.CreateChangeSetInput{
ChangeSetName: aws.String(csn),
ChangeSetType: aws.String(changeSetType),
StackName: aws.String(sn),
TemplateBody: aws.String(templateBody),
}
if namedIAM {
ccsi.Capabilities = []*string{aws.String(cloudformation.CapabilityCapabilityNamedIam)}
}
ccso, err := c.CFClient.CreateChangeSet(ccsi)
if err != nil {
return fmt.Errorf("the ChangeSetType was %s error in creating ChangeSet: %w", changeSetType, err)
}
//nolint
dcsi := &cloudformation.DescribeChangeSetInput{
ChangeSetName: ccso.Id,
StackName: aws.String(sn),
}
maxAttempts := 12
delay := time.Duration(5) * time.Second
err = c.CFClient.WaitUntilChangeSetCreateCompleteWithContext(context.Background(),
dcsi,
request.WithWaiterDelay(request.ConstantWaiterDelay(delay)),
request.WithWaiterMaxAttempts(maxAttempts))
if err != nil {
dcso, err2 := c.CFClient.DescribeChangeSet(dcsi)
if err2 != nil {
return fmt.Errorf("error describing the ChangeSet: %w", err2)
}
if changeSetIsEmpty(dcso) {
c.logger().Infof("ChangeSet '%v' is empty. Deleting again.", *ccso.Id)
_, err3 := c.CFClient.DeleteChangeSet(&cloudformation.DeleteChangeSetInput{
ChangeSetName: aws.String(csn),
StackName: aws.String(sn),
})
if err3 != nil {
return fmt.Errorf("couldn't delete empty change set: %w", err3)
}
return nil
}
return fmt.Errorf("changeset is not empty but waiting for changeset completion still timed out. Error was: %w", err)
}
return c.executeChangeSet(csn)
}
// CreateStackName creates a valid stack name from the given alarm name.
func CreateStackName(s string) string {
s = strings.ToLower(s)
for _, char := range [...]string{"/", "."} {
s = strings.ReplaceAll(s, char, "-")
}
return s
}
// CreateLogicalName creates a logical name used in the CloudFormation template.
func CreateLogicalName(s string) string {
for _, char := range [...]string{"-", "/", "_", ".", " "} {
s = strings.ReplaceAll(s, char, "")
}
return s
}