This repository has been archived by the owner on Jan 3, 2022. It is now read-only.
/
deploycfn.go
237 lines (212 loc) · 6.27 KB
/
deploycfn.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
package deploycfn
import (
"archive/zip"
"bytes"
"crypto/sha1"
"encoding/json"
"fmt"
"strings"
log "github.com/Sirupsen/logrus"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/cloudformation"
"github.com/aws/aws-sdk-go/service/s3"
"github.com/crewjam/awsregion"
cfn "github.com/crewjam/go-cloudformation"
)
type DeployInput struct {
Session client.ConfigProvider
StackName string
Template *cfn.Template
Parameters map[string]string
TemplateBucket string
}
// Deploy creates or updates the specified CloudFormation template to AWS.
//
// If you secify nil for awsConfigProvider, a default one will be used.
//
// This is a handy function to call from your main, i.e.:
//
// func main() {
// dnsName := flag.String("name", "example.com", "the DNS name")
// flag.Parse()
//
// template := makeTemplate(*dnsName)
// if err := deploycfn.Deploy(nil, "Example", template); err != nil {
// log.Fatalf("deploy: %s", err)
// }
// }
//
func Deploy(input DeployInput) error {
if input.Session == nil {
awsSession := session.New()
awsregion.GuessRegion(awsSession.Config)
input.Session = awsSession
}
cfnSvc := cloudformation.New(input.Session)
describeStacksResponse, err := cfnSvc.DescribeStacks(&cloudformation.DescribeStacksInput{
StackName: aws.String(input.StackName),
})
doCreate := err != nil || len(describeStacksResponse.Stacks) == 0
watcher := &StackEventWatcher{
Service: cfnSvc,
StackName: input.StackName,
}
if !doCreate {
watcher, err = NewStackEventWatcher(input.Session, input.StackName)
if err != nil {
return err
}
}
needCapabilityIam := false
for _, resource := range input.Template.Resources {
switch resource.Properties.CfnResourceType() {
case "AWS::IAM::AccessKey":
needCapabilityIam = true
case "AWS::IAM::Group":
needCapabilityIam = true
case "AWS::IAM::InstanceProfile":
needCapabilityIam = true
case "AWS::IAM::Policy":
needCapabilityIam = true
case "AWS::IAM::Role":
needCapabilityIam = true
case "AWS::IAM::User":
needCapabilityIam = true
case "AWS::IAM::UserToGroupAddition":
needCapabilityIam = true
}
}
capabilities := []*string{}
if needCapabilityIam {
capabilities = append(capabilities, aws.String(cloudformation.CapabilityCapabilityIam))
}
// if inline lambda function code is too big, upload it to S3
if input.TemplateBucket != "" {
for resourceName, resource := range input.Template.Resources {
if resource.Properties.CfnResourceType() == "AWS::Lambda::Function" {
if f, ok := resource.Properties.(cfn.LambdaFunction); ok {
if f.Code != nil && f.Code.ZipFile != nil {
if f.Code.ZipFile.Func == nil {
code := []byte(f.Code.ZipFile.Literal)
if len(code) > 4096 {
// the zip file is too long, store it in S3
s3svc := s3.New(input.Session)
sha1sum := sha1.Sum(code)
key := fmt.Sprintf("cfn/%x/%s/%s/lambda-code.zip", sha1sum[:],
input.StackName, resourceName)
fileName := strings.Split(f.Handler.Literal, ".")[0] + ".js"
zipBuf := new(bytes.Buffer)
w := zip.NewWriter(zipBuf)
zipFileWriter, err := w.Create(fileName)
if err != nil {
return err
}
if _, err := zipFileWriter.Write(code); err != nil {
return err
}
if err := w.Close(); err != nil {
return err
}
l := log.WithField("Resource", resourceName)
l = l.WithField("Path", "s3://"+input.TemplateBucket+"/"+key)
l.Info("uploaded inline lambda function code")
_, err = s3svc.PutObject(&s3.PutObjectInput{
Bucket: &input.TemplateBucket,
Key: &key,
Body: bytes.NewReader(zipBuf.Bytes()),
})
if err != nil {
return err
}
// Update the template
f.Code = &cfn.LambdaFunctionCode{
S3Bucket: cfn.String(input.TemplateBucket),
S3Key: cfn.String(key),
}
input.Template.Resources[resourceName].Properties = f
}
}
}
}
}
}
}
parameters := []*cloudformation.Parameter{}
for key, value := range input.Parameters {
parameters = append(parameters, &cloudformation.Parameter{
ParameterKey: aws.String(key),
ParameterValue: aws.String(value),
})
}
if !doCreate {
for key := range input.Template.Parameters {
if _, ok := input.Parameters[key]; ok {
continue
}
parameterExistsInCurrentStack := false
for _, p := range describeStacksResponse.Stacks[0].Parameters {
if *p.ParameterKey == key {
parameterExistsInCurrentStack = true
}
}
if parameterExistsInCurrentStack {
parameters = append(parameters, &cloudformation.Parameter{
ParameterKey: aws.String(key),
UsePreviousValue: aws.Bool(true),
})
}
}
}
templateBody, err := json.Marshal(input.Template)
if err != nil {
return err
}
var templateBodyStr = aws.String(string(templateBody))
var templateURL *string
const maxTemplateSize = 51200
if input.TemplateBucket != "" && len(templateBody) > maxTemplateSize {
s3svc := s3.New(input.Session)
sha1sum := sha1.Sum(templateBody)
key := fmt.Sprintf("cfn/%x/%s.template", sha1sum[:], input.StackName)
log.WithField("Path", "s3://"+input.TemplateBucket+"/"+key).Info("uploaded template")
_, err := s3svc.PutObject(&s3.PutObjectInput{
Bucket: &input.TemplateBucket,
Key: &key,
Body: bytes.NewReader(templateBody),
})
if err != nil {
return err
}
templateBodyStr = nil
templateURL = aws.String(fmt.Sprintf("https://%s.s3.amazonaws.com/%s", input.TemplateBucket, key))
}
if doCreate {
_, err = cfnSvc.CreateStack(&cloudformation.CreateStackInput{
StackName: aws.String(input.StackName),
TemplateBody: templateBodyStr,
TemplateURL: templateURL,
Capabilities: capabilities,
Parameters: parameters,
})
if err != nil {
return err
}
} else {
_, err = cfnSvc.UpdateStack(&cloudformation.UpdateStackInput{
StackName: aws.String(input.StackName),
TemplateBody: templateBodyStr,
TemplateURL: templateURL,
Capabilities: capabilities,
Parameters: parameters,
})
if err != nil {
return err
}
}
if err := watcher.Watch(); err != nil {
return err
}
return nil
}