-
Notifications
You must be signed in to change notification settings - Fork 76
Expand file tree
/
Copy pathcustom-resource-provider-helper.ts
More file actions
222 lines (199 loc) · 6.67 KB
/
Copy pathcustom-resource-provider-helper.ts
File metadata and controls
222 lines (199 loc) · 6.67 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
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
/**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance
* with the License. A copy of the License is located at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* or in the 'license' file accompanying this file. This file is distributed on an 'AS IS' BASIS, WITHOUT WARRANTIES
* OR CONDITIONS OF ANY KIND, express or implied. See the License for the specific language governing permissions
* and limitations under the License.
*/
import * as child_process from 'child_process';
import * as cdk from 'aws-cdk-lib';
import * as ec2 from 'aws-cdk-lib/aws-ec2';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as lambda from 'aws-cdk-lib/aws-lambda';
import * as logs from 'aws-cdk-lib/aws-logs';
import * as cr from 'aws-cdk-lib/custom-resources';
import { NagSuppressions } from 'cdk-nag';
import { Construct } from 'constructs';
export interface CRProviderProps {
/**
* A globally unique name for the Custom Resource provider.
*
* @default - None.
*/
readonly providerName: string;
/**
* Path to custom resource provider Lambda code. The package will be bundled locally if
* pip/poetry are available, otherwise falls back to Docker.
*
* @default - None.
*/
readonly codePath: string;
/**
* The name of the Lambda handler function.
*
* @default - None.
*/
readonly handler: string;
/**
* The runtime of the Lambda function.
*
* @default - None.
*/
readonly runtime: lambda.Runtime;
/**
* The list of layers to attach to the Lambda function.
*
* @default - None.
*/
readonly layers?: lambda.ILayerVersion[];
/**
* The VPC to deploy Lambda function into.
*
* @default - None.
*/
readonly vpc?: ec2.IVpc;
/**
* The security group for Lambda function.
*
* @default - None.
*/
readonly securityGroup?: ec2.SecurityGroup;
}
/**
* The ICR provider
*/
export interface ICRProvider {
role: iam.Role;
provider: cr.Provider;
serviceToken: string;
}
/**
* Get the ICRProvider
*/
export interface ICRProviderClass {
getProvider(scope: Construct): ICRProvider;
}
export function buildCustomResourceProvider(props: CRProviderProps): ICRProviderClass {
const { providerName, codePath, handler, runtime, layers, vpc, securityGroup } = props;
class CRProvider extends Construct {
static getProvider(scope: Construct): CRProvider {
const stack = cdk.Stack.of(scope);
const existing = stack.node.tryFindChild(providerName);
if (existing) {
return existing as CRProvider;
}
return new CRProvider(cdk.Stack.of(scope), providerName);
}
public readonly role: iam.Role;
public readonly provider: cr.Provider;
public readonly serviceToken: string;
constructor(scope: cdk.Stack, id: string) {
super(scope, id);
this.role = new iam.Role(this, 'CRRole', {
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
managedPolicies: [
iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AWSLambdaBasicExecutionRole'),
],
});
const customResourceFunction = new lambda.Function(this, 'CustomResourcesFunction', {
code: lambda.Code.fromAsset(codePath, {
bundling: {
image: runtime.bundlingImage,
user: 'root',
command: [
'bash', '-c',
'pip install poetry -q && poetry install -q && poetry build -q && poetry run pip install --upgrade -t /asset-output dist/*.whl -q',
],
local: {
tryBundle(outputDir: string): boolean {
try {
const opts = { cwd: codePath, stdio: 'pipe' as const, shell: true };
const steps = [
() => child_process.spawnSync('pip', ['install', 'poetry', '-q'], opts),
() => child_process.spawnSync('poetry', ['install', '-q'], opts),
() => child_process.spawnSync('poetry', ['build', '-q'], opts),
() => child_process.spawnSync('poetry', ['run', 'pip', 'install', '--upgrade', '-t', outputDir, 'dist/*.whl', '-q'], opts),
];
return steps.every(step => step().status === 0);
} catch {
return false;
}
},
},
},
}),
handler,
runtime,
layers,
role: this.role,
timeout: cdk.Duration.minutes(15),
memorySize: 128,
vpc,
vpcSubnets: vpc ? { subnetType: ec2.SubnetType.PRIVATE_ISOLATED } : undefined,
securityGroups: vpc && securityGroup ? [securityGroup] : undefined,
logRetention: logs.RetentionDays.ONE_WEEK,
description: 'Custom Resource Provider',
});
const providerRole = new iam.Role(this, 'ProviderRole', {
assumedBy: new iam.ServicePrincipal('lambda.amazonaws.com'),
managedPolicies: [
iam.ManagedPolicy.fromAwsManagedPolicyName('service-role/AWSLambdaBasicExecutionRole'),
],
});
this.provider = new cr.Provider(this, 'Provider', {
onEventHandler: customResourceFunction,
logRetention: logs.RetentionDays.ONE_WEEK,
role: providerRole,
});
this.serviceToken = this.provider.serviceToken;
NagSuppressions.addResourceSuppressions(
customResourceFunction,
[
{
id: 'AwsSolutions-L1',
reason: 'Lambda runtime version is managed upstream by CDK.',
},
],
true,
);
NagSuppressions.addResourceSuppressionsByPath(
cdk.Stack.of(this),
`${this.provider.node.path}/framework-onEvent/Resource`,
[
{
id: 'AwsSolutions-L1',
reason: 'Lambda runtime version is managed upstream by CDK.',
},
],
);
for (let role of [this.role, providerRole]) {
NagSuppressions.addResourceSuppressions(
role,
[
{
id: 'AwsSolutions-IAM4',
reason: 'CDK CustomResource Lambda uses the AWSLambdaBasicExecutionRole AWS Managed Policy.',
},
],
);
}
NagSuppressions.addResourceSuppressions(
providerRole,
[
{
id: 'AwsSolutions-IAM5',
reason: 'CDK CustomResource Provider has a wildcard to invoke any version of the specific Custom Resource function.',
appliesTo: [{ regex: `/^Resource::<${id}${customResourceFunction.node.id}[A-Z0-9]+\\.Arn>:\\*$/g` }],
},
],
true,
);
}
}
return CRProvider;
}