-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
76 lines (68 loc) · 2.27 KB
/
index.js
File metadata and controls
76 lines (68 loc) · 2.27 KB
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
"use strict";
/**
* Check if a policy statement item meets the criteria to be simplified
*
* @param {*} s Policy Statement entry
* @returns {boolean} true when the statement should be simplified
*/
const shouldSimplify = (s) => {
/**
* The resources for polices that define these permissions will be 'simplified'
*/
const LOG_ACTIONS_TO_SIMPLIFY = [
"logs:CreateLogStream",
"logs:CreateLogGroup",
"logs:PutLogEvents",
];
return (
s.Effect === "Allow" &&
s.Action.every((action) => LOG_ACTIONS_TO_SIMPLIFY.includes(action))
);
};
class SimplifyDefaultExecRole {
constructor(serverless) {
this.hooks = {
"before:package:finalize": function () {
simplifyBaseIAMLogGroups(serverless);
},
};
}
}
/**
* By default serverless specifies each CloudWatch log group ARN individually in a Stack's Lambda IAM role. For every large stacks, this can cause the role
* to exceed the maximum allowed size of 10240 bytes. This code reduces the size of the generated lambda role by replacing the resource list with a single
* ARN to grants write access to _all_ log groups that are part of the same region and account.
*
* arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:*
*
* @param {*} serverless
*/
function simplifyBaseIAMLogGroups(serverless) {
const resourceSection =
serverless.service.provider.compiledCloudFormationTemplate.Resources;
if (
resourceSection.IamRoleLambdaExecution &&
resourceSection.IamRoleLambdaExecution.Properties &&
Array.isArray(resourceSection.IamRoleLambdaExecution.Properties.Policies)
) {
// parse all existing policies from the lambda role
resourceSection.IamRoleLambdaExecution.Properties.Policies.forEach((p) => {
if (p.PolicyDocument && Array.isArray(p.PolicyDocument.Statement)) {
const nStatement = [];
for (const s of p.PolicyDocument.Statement) {
if (shouldSimplify(s)) {
s.Resource = [
{
"Fn::Sub":
"arn:${AWS::Partition}:logs:${AWS::Region}:${AWS::AccountId}:log-group:*",
},
];
}
nStatement.push(s);
}
p.PolicyDocument.Statement = nStatement;
}
});
}
}
module.exports = SimplifyDefaultExecRole;