-
Notifications
You must be signed in to change notification settings - Fork 48
/
cmd_provision.go
322 lines (290 loc) · 11 KB
/
cmd_provision.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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
package sparta
import (
"bytes"
"fmt"
"reflect"
"text/template"
cwCustomProvider "github.com/mweagle/Sparta/v3/aws/cloudformation/provider"
gof "github.com/awslabs/goformation/v5/cloudformation"
gofiam "github.com/awslabs/goformation/v5/cloudformation/iam"
goflambda "github.com/awslabs/goformation/v5/cloudformation/lambda"
spartaCF "github.com/mweagle/Sparta/v3/aws/cloudformation"
cfCustomResources "github.com/mweagle/Sparta/v3/aws/cloudformation/resources"
spartaIAM "github.com/mweagle/Sparta/v3/aws/iam"
"github.com/pkg/errors"
"github.com/rs/zerolog"
)
const (
// ScratchDirectory is the cwd relative path component
// where intermediate build artifacts are created
ScratchDirectory = ".sparta"
// EnvVarCustomResourceTypeName is the environment variable
// name that stores the CustomResource TypeName that should be
// instantiated
EnvVarCustomResourceTypeName = "SPARTA_CUSTOM_RESOURCE_TYPE"
)
// This is a literal version of the DiscoveryInfo struct.
var discoveryData = `
{
"ResourceID": "<< .TagLogicalResourceID >>",
"Region": "{"Ref" : "AWS::Region"}",
"StackID": "{"Ref" : "AWS::StackId"}",
"StackName": "{"Ref" : "AWS::StackName"}",
"Resources":{<<range $eachDepResource, $eachOutputString := .Resources>>
"<< $eachDepResource >>" : << $eachOutputString >><< trailingComma >><<end>>
}
}`
//
type discoveryDataTemplateData struct {
TagLogicalResourceID string
Resources map[string]string
}
func lambdaFunctionEnvironment(userEnvMap map[string]string,
resourceID string,
deps map[string]string,
logger *zerolog.Logger) (*goflambda.Function_Environment, error) {
// Merge everything, add the deps
envMap := make(map[string]string)
for eachKey, eachValue := range userEnvMap {
envMap[eachKey] = eachValue
}
discoveryInfo, discoveryInfoErr := discoveryInfoForResource(resourceID, deps)
if discoveryInfoErr != nil {
return nil, errors.Wrapf(discoveryInfoErr, "Failed to calculate dependency info")
}
envMap[envVarLogLevel] = logger.GetLevel().String()
envMap[envVarDiscoveryInformation] = fmt.Sprintf("%q", discoveryInfo)
return &goflambda.Function_Environment{
Variables: envMap,
}, nil
}
func discoveryInfoForResource(resID string, deps map[string]string) (string, error) {
discoveryDataTemplateData := &discoveryDataTemplateData{
TagLogicalResourceID: resID,
Resources: deps,
}
totalDeps := len(deps)
var templateFuncMap = template.FuncMap{
// The name "trailingComma" is what the function will be called in the template text.
"trailingComma": func() string {
totalDeps--
if totalDeps > 0 {
return ","
}
return ""
},
}
discoveryTemplate, discoveryTemplateErr := template.New("discoveryData").
Delims("<<", ">>").
Funcs(templateFuncMap).
Parse(discoveryData)
if nil != discoveryTemplateErr {
return "", discoveryTemplateErr
}
var templateResults bytes.Buffer
evalResultErr := discoveryTemplate.Execute(&templateResults, discoveryDataTemplateData)
if nil != evalResultErr {
return "", evalResultErr
}
templateReader := bytes.NewReader(templateResults.Bytes())
templateExpr, templateExprErr := spartaCF.ConvertToTemplateExpression(templateReader, nil)
if templateExprErr != nil {
return "", templateExprErr
}
return gof.Base64(templateExpr), nil
}
// EnsureCustomResourceHandler handles ensuring that the custom resource responsible
// for supporting the operation is actually part of this stack. The returned
// string value is the CloudFormation resource name that implements this
// resource. The customResourceCloudFormationTypeName must have already
// been registered with gocf and implement the resources.CustomResourceCommand
// interface
func EnsureCustomResourceHandler(serviceName string,
customResourceCloudFormationTypeName string,
sourceArn string,
dependsOn []string,
template *gof.Template,
lambdaFunctionCode *goflambda.Function_Code,
logger *zerolog.Logger) (string, error) {
// Ok, we need a way to round trip this type as the AWS lambda function name.
// The problem with this is that the full CustomResource::Type value isn't an
// AWS Lambda friendly name. We want to do this so that in the AWS lambda handler
// we can attempt to instantiate a new CustomAction resource, typecast it to a
// CustomResourceCommand type and then apply the workflow. Doing this means
// we can decouple the lookup logic for custom resource...
resource, resourceErr := cwCustomProvider.NewCloudFormationCustomResource(customResourceCloudFormationTypeName, logger)
if resourceErr != nil {
return "", resourceErr
}
if resource == nil {
return "", errors.Errorf("Unable to create custom resource handler of type: %v", customResourceCloudFormationTypeName)
}
command, commandOk := resource.(cfCustomResources.CustomResourceCommand)
if !commandOk {
return "", errors.Errorf("Cannot type assert resource type %s to CustomResourceCommand", customResourceCloudFormationTypeName)
}
// Prefix
commandType := reflect.TypeOf(command)
customResourceTypeName := fmt.Sprintf("%T", command)
prefixName := fmt.Sprintf("%s-CFRes", serviceName)
subscriberHandlerName := CloudFormationResourceName(prefixName, customResourceTypeName)
//////////////////////////////////////////////////////////////////////////////
// IAM Role definition
iamResourceName, err := ensureIAMRoleForCustomResource(command,
sourceArn,
template,
logger)
if nil != err {
return "", errors.Wrapf(err,
"Failed to ensure IAM Role for custom resource: %T",
command)
}
iamRoleRef := gof.GetAtt(iamResourceName, "Arn")
_, exists := template.Resources[subscriberHandlerName]
if exists {
return subscriberHandlerName, nil
}
// Encode the resourceType...
configuratorDescription := customResourceDescription(serviceName, customResourceTypeName)
//////////////////////////////////////////////////////////////////////////////
// Custom Resource Lambda Handler
// Insert it into the template resources...
logger.Info().
Str("CloudFormationResourceType", customResourceCloudFormationTypeName).
Str("Resource", customResourceTypeName).
Str("TypeOf", commandType.String()).
Msg("Including Lambda CustomResource")
// Don't forget the discovery info...
userDispatchMap := map[string]string{
EnvVarCustomResourceTypeName: customResourceCloudFormationTypeName,
}
lambdaEnv, lambdaEnvErr := lambdaFunctionEnvironment(userDispatchMap,
customResourceTypeName,
nil,
logger)
if lambdaEnvErr != nil {
return "", errors.Wrapf(lambdaEnvErr, "Failed to create environment for required custom resource")
}
// Add the special key that's the custom resource type name
customResourceHandlerDef := &goflambda.Function{
Code: lambdaFunctionCode,
Runtime: string(Go1LambdaRuntime),
Description: configuratorDescription,
Handler: SpartaBinaryName,
Role: iamRoleRef,
Timeout: 30,
// Let AWS assign a name here...
// FunctionName: lambdaFunctionName.String(),
// DISPATCH INFORMATION
Environment: lambdaEnv,
}
if lambdaFunctionCode.ImageUri != "" {
customResourceHandlerDef.PackageType = "Image"
} else {
customResourceHandlerDef.Runtime = string(Go1LambdaRuntime)
customResourceHandlerDef.Handler = SpartaBinaryName
}
if nil != dependsOn && (len(dependsOn) > 0) {
customResourceHandlerDef.AWSCloudFormationDependsOn = dependsOn
}
template.Resources[subscriberHandlerName] = customResourceHandlerDef
return subscriberHandlerName, nil
}
// ensureIAMRoleForCustomResource ensures that the single IAM::Role for a single
// AWS principal (eg, s3.*.*) exists, and includes statements for the given
// sourceArn. Sparta uses a single IAM::Role for the CustomResource configuration
// lambda, which is the union of all Arns in the application.
func ensureIAMRoleForCustomResource(command cfCustomResources.CustomResourceCommand,
sourceArn string,
template *gof.Template,
logger *zerolog.Logger) (string, error) {
// What's the stable IAMRoleName?
commandName := fmt.Sprintf("%T", command)
resourceBaseName := fmt.Sprintf("CFResIAMRole%s", commandName)
stableRoleName := CloudFormationResourceName(resourceBaseName, resourceBaseName)
// Is it a privileged command?
var privileges []string
privilegedCommand, privilegedCommandOk := command.(cfCustomResources.CustomResourcePrivilegedCommand)
if privilegedCommandOk {
privileges = privilegedCommand.IAMPrivileges()
}
// Ensure it exists, then check to see if this Source ARN is already specified...
// Checking equality with Stringable?
// Create a new Role
var existingIAMRole *gofiam.Role
existingResource, exists := template.Resources[stableRoleName]
logger.Debug().
Interface("PrincipalActions", privileges).
Interface("SourceArn", sourceArn).
Msg("Ensuring IAM Role results")
if !exists {
// Insert the IAM role here. We'll walk the policies data in the next section
// to make sure that the sourceARN we have is in the list
statements := CommonIAMStatements.Core
iamPolicyList := []gofiam.Role_Policy{
{
PolicyDocument: ArbitraryJSONObject{
"Version": "2012-10-17",
"Statement": statements,
},
PolicyName: fmt.Sprintf("%sPolicy", stableRoleName),
},
}
existingIAMRole = &gofiam.Role{
AssumeRolePolicyDocument: AssumePolicyDocument,
Policies: iamPolicyList,
}
template.Resources[stableRoleName] = existingIAMRole
// Create a new IAM Role resource
logger.Debug().
Str("RoleName", stableRoleName).
Msg("Inserting IAM Role")
} else {
existingIAMRole = existingResource.(*gofiam.Role)
}
// ARNs are only required if there are non-empty privileges associated
// with the command
if sourceArn == "" {
if len(privileges) != 0 {
return "", errors.Errorf("CustomResource %s requires a SourceARN to apply it's %d principle actions",
commandName,
len(privileges))
}
return stableRoleName, nil
}
// Walk the existing statements
if nil != existingIAMRole.Policies {
for _, eachPolicy := range existingIAMRole.Policies {
policyDoc := eachPolicy.PolicyDocument.(ArbitraryJSONObject)
statements := policyDoc["Statement"]
for _, eachStatement := range statements.([]spartaIAM.PolicyStatement) {
if sourceArn == eachStatement.Resource {
logger.Debug().
Str("RoleName", stableRoleName).
Interface("SourceArn", sourceArn).
Msg("SourceArn already exists for IAM Policy")
return stableRoleName, nil
}
}
}
logger.Debug().
Str("RoleName", stableRoleName).
Interface("Action", privileges).
Interface("Resource", sourceArn).
Msg("Inserting Actions for configuration ARN")
// Add this statement to the first policy, iff the actions are non-empty
if len(privileges) > 0 {
rootPolicy := (existingIAMRole.Policies)[0]
rootPolicyDoc := rootPolicy.PolicyDocument.(ArbitraryJSONObject)
rootPolicyStatements := rootPolicyDoc["Statement"].([]spartaIAM.PolicyStatement)
rootPolicyDoc["Statement"] = append(rootPolicyStatements,
spartaIAM.PolicyStatement{
Effect: "Allow",
Action: privileges,
Resource: sourceArn,
})
}
return stableRoleName, nil
}
return "", errors.Errorf("Unable to find Policies entry for IAM role: %s", stableRoleName)
}