@cdklabs/deploy-time-build 0.0.1 → 0.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,279 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ handler: () => handler
34
+ });
35
+ module.exports = __toCommonJS(index_exports);
36
+ var import_client_codebuild = require("@aws-sdk/client-codebuild");
37
+ var import_crypto = __toESM(require("crypto"));
38
+ var import_promises = require("timers/promises");
39
+ var cb = new import_client_codebuild.CodeBuildClient({});
40
+ var handler = async (event, context) => {
41
+ try {
42
+ if (event.RequestType == "Create" || event.RequestType == "Update") {
43
+ const props = event.ResourceProperties;
44
+ const commonEnvironments = [
45
+ {
46
+ name: "responseURL",
47
+ value: event.ResponseURL
48
+ },
49
+ {
50
+ name: "stackId",
51
+ value: event.StackId
52
+ },
53
+ {
54
+ name: "requestId",
55
+ value: event.RequestId
56
+ },
57
+ {
58
+ name: "logicalResourceId",
59
+ value: event.LogicalResourceId
60
+ }
61
+ ];
62
+ const newPhysicalId = import_crypto.default.randomBytes(16).toString("hex");
63
+ let command;
64
+ switch (props.type) {
65
+ case "NodejsBuild":
66
+ command = new import_client_codebuild.StartBuildCommand({
67
+ projectName: props.codeBuildProjectName,
68
+ environmentVariablesOverride: [
69
+ ...commonEnvironments,
70
+ {
71
+ name: "input",
72
+ value: JSON.stringify(
73
+ props.sources.map((source) => ({
74
+ assetUrl: `s3://${source.sourceBucketName}/${source.sourceObjectKey}`,
75
+ extractPath: source.extractPath,
76
+ commands: (source.commands ?? []).join(" && ")
77
+ }))
78
+ )
79
+ },
80
+ {
81
+ name: "buildCommands",
82
+ value: props.buildCommands.join(" && ")
83
+ },
84
+ {
85
+ name: "destinationBucketName",
86
+ value: props.destinationBucketName
87
+ },
88
+ {
89
+ name: "destinationKeyPrefix",
90
+ // remove the beginning / if any
91
+ value: props.destinationKeyPrefix.startsWith("/") ? props.destinationKeyPrefix.slice(1) : props.destinationKeyPrefix
92
+ },
93
+ {
94
+ name: "distributionId",
95
+ value: props.distributionId ?? ""
96
+ },
97
+ {
98
+ name: "distributionPath",
99
+ value: (() => {
100
+ let path = props.destinationKeyPrefix;
101
+ if (!path.startsWith("/")) {
102
+ path = "/" + path;
103
+ }
104
+ if (!path.endsWith("/")) {
105
+ path += "/";
106
+ }
107
+ return path + "*";
108
+ })()
109
+ },
110
+ {
111
+ name: "assetBucketName",
112
+ value: props.assetBucketName
113
+ },
114
+ {
115
+ name: "workingDirectory",
116
+ value: props.workingDirectory
117
+ },
118
+ {
119
+ name: "outputSourceDirectory",
120
+ value: props.outputSourceDirectory
121
+ },
122
+ {
123
+ name: "projectName",
124
+ value: props.codeBuildProjectName
125
+ },
126
+ {
127
+ name: "outputEnvFile",
128
+ value: props.outputEnvFile.toString()
129
+ },
130
+ {
131
+ name: "envFileKey",
132
+ value: `deploy-time-build/${event.StackId.split("/")[1]}/${event.LogicalResourceId}/${newPhysicalId}.env`
133
+ },
134
+ {
135
+ name: "envNames",
136
+ value: Object.keys(props.environment ?? {}).join(",")
137
+ },
138
+ ...Object.entries(props.environment ?? {}).map(([name, value]) => ({
139
+ name,
140
+ value
141
+ }))
142
+ ]
143
+ });
144
+ break;
145
+ case "SociIndexBuild":
146
+ command = new import_client_codebuild.StartBuildCommand({
147
+ projectName: props.codeBuildProjectName,
148
+ environmentVariablesOverride: [
149
+ ...commonEnvironments,
150
+ {
151
+ name: "repositoryName",
152
+ value: props.repositoryName
153
+ },
154
+ {
155
+ name: "imageTag",
156
+ value: props.imageTag
157
+ },
158
+ {
159
+ name: "projectName",
160
+ value: props.codeBuildProjectName
161
+ }
162
+ ]
163
+ });
164
+ break;
165
+ case "SociIndexV2Build":
166
+ command = new import_client_codebuild.StartBuildCommand({
167
+ projectName: props.codeBuildProjectName,
168
+ environmentVariablesOverride: [
169
+ ...commonEnvironments,
170
+ {
171
+ name: "repositoryName",
172
+ value: props.repositoryName
173
+ },
174
+ {
175
+ name: "inputImageTag",
176
+ value: props.inputImageTag
177
+ },
178
+ {
179
+ name: "outputImageTag",
180
+ value: props.outputImageTag
181
+ },
182
+ {
183
+ name: "projectName",
184
+ value: props.codeBuildProjectName
185
+ }
186
+ ]
187
+ });
188
+ break;
189
+ case "ContainerImageBuild": {
190
+ const imageTag = props.imageTag ?? `${props.tagPrefix ?? ""}${newPhysicalId}`;
191
+ command = new import_client_codebuild.StartBuildCommand({
192
+ projectName: props.codeBuildProjectName,
193
+ environmentVariablesOverride: [
194
+ ...commonEnvironments,
195
+ {
196
+ name: "repositoryUri",
197
+ value: props.repositoryUri
198
+ },
199
+ {
200
+ name: "repositoryAuthUri",
201
+ value: props.repositoryUri.split("/")[0]
202
+ },
203
+ {
204
+ name: "repositoryRegion",
205
+ value: props.repositoryUri.split(".")[3]
206
+ },
207
+ {
208
+ name: "buildCommand",
209
+ value: props.buildCommand
210
+ },
211
+ {
212
+ name: "imageTag",
213
+ value: imageTag
214
+ },
215
+ {
216
+ name: "projectName",
217
+ value: props.codeBuildProjectName
218
+ },
219
+ {
220
+ name: "sourceS3Url",
221
+ value: props.sourceS3Url
222
+ }
223
+ ]
224
+ });
225
+ break;
226
+ }
227
+ default:
228
+ throw new Error(`invalid event type ${props}}`);
229
+ }
230
+ let retries = 0;
231
+ while (retries < 10) {
232
+ try {
233
+ await cb.send(command);
234
+ break;
235
+ } catch (error) {
236
+ if (error.name === "AccessDeniedException") {
237
+ retries++;
238
+ console.log(`AccessDeniedException encountered, retrying (${retries})...`);
239
+ await (0, import_promises.setTimeout)(5e3);
240
+ } else {
241
+ throw error;
242
+ }
243
+ }
244
+ }
245
+ } else {
246
+ await sendStatus("SUCCESS", event, context);
247
+ }
248
+ } catch (e) {
249
+ console.log(e);
250
+ const err = e;
251
+ await sendStatus("FAILED", event, context, err.message);
252
+ }
253
+ };
254
+ var sendStatus = async (status, event, context, reason) => {
255
+ const responseBody = {
256
+ Status: status,
257
+ Reason: reason ?? "See the details in CloudWatch Log Stream: " + context.logStreamName,
258
+ PhysicalResourceId: context.logStreamName,
259
+ StackId: event.StackId,
260
+ RequestId: event.RequestId,
261
+ LogicalResourceId: event.LogicalResourceId,
262
+ NoEcho: false,
263
+ Data: {}
264
+ //responseData
265
+ };
266
+ const responseBodyString = JSON.stringify(responseBody);
267
+ await fetch(event.ResponseURL, {
268
+ method: "PUT",
269
+ body: responseBodyString,
270
+ headers: {
271
+ "Content-Type": "",
272
+ "Content-Length": responseBodyString.length.toString()
273
+ }
274
+ });
275
+ };
276
+ // Annotate the CommonJS export names for ESM import in node:
277
+ 0 && (module.exports = {
278
+ handler
279
+ });
@@ -0,0 +1,269 @@
1
+ import { CodeBuildClient, StartBuildCommand } from '@aws-sdk/client-codebuild';
2
+ import { CloudFormationCustomResourceEvent, CloudFormationCustomResourceResponse, Context } from 'aws-lambda';
3
+ import Crypto from 'crypto';
4
+ import { setTimeout } from 'timers/promises';
5
+ import type { ResourceProperties } from '../../src/types';
6
+
7
+ const cb = new CodeBuildClient({});
8
+
9
+ type Event = CloudFormationCustomResourceEvent & {
10
+ ResourceProperties: ResourceProperties;
11
+ };
12
+
13
+ export const handler = async (event: Event, context: Context) => {
14
+ try {
15
+ if (event.RequestType == 'Create' || event.RequestType == 'Update') {
16
+ const props = event.ResourceProperties;
17
+ const commonEnvironments = [
18
+ {
19
+ name: 'responseURL',
20
+ value: event.ResponseURL,
21
+ },
22
+ {
23
+ name: 'stackId',
24
+ value: event.StackId,
25
+ },
26
+ {
27
+ name: 'requestId',
28
+ value: event.RequestId,
29
+ },
30
+ {
31
+ name: 'logicalResourceId',
32
+ value: event.LogicalResourceId,
33
+ },
34
+ ];
35
+ const newPhysicalId = Crypto.randomBytes(16).toString('hex');
36
+
37
+ let command: StartBuildCommand;
38
+ switch (props.type) {
39
+ case 'NodejsBuild':
40
+ command = new StartBuildCommand({
41
+ projectName: props.codeBuildProjectName,
42
+ environmentVariablesOverride: [
43
+ ...commonEnvironments,
44
+ {
45
+ name: 'input',
46
+ value: JSON.stringify(
47
+ props.sources.map((source) => ({
48
+ assetUrl: `s3://${source.sourceBucketName}/${source.sourceObjectKey}`,
49
+ extractPath: source.extractPath,
50
+ commands: (source.commands ?? []).join(' && '),
51
+ }))
52
+ ),
53
+ },
54
+ {
55
+ name: 'buildCommands',
56
+ value: props.buildCommands.join(' && '),
57
+ },
58
+ {
59
+ name: 'destinationBucketName',
60
+ value: props.destinationBucketName,
61
+ },
62
+ {
63
+ name: 'destinationKeyPrefix',
64
+ // remove the beginning / if any
65
+ value: props.destinationKeyPrefix.startsWith('/') ? props.destinationKeyPrefix.slice(1) : props.destinationKeyPrefix,
66
+ },
67
+ {
68
+ name: 'distributionId',
69
+ value: props.distributionId ?? '',
70
+ },
71
+ {
72
+ name: 'distributionPath',
73
+ value: (() => {
74
+ let path = props.destinationKeyPrefix;
75
+ if (!path.startsWith('/')) {
76
+ path = '/' + path;
77
+ }
78
+ if (!path.endsWith('/')) {
79
+ path += '/';
80
+ }
81
+ return path + '*';
82
+ })(),
83
+ },
84
+ {
85
+ name: 'assetBucketName',
86
+ value: props.assetBucketName,
87
+ },
88
+ {
89
+ name: 'workingDirectory',
90
+ value: props.workingDirectory,
91
+ },
92
+ {
93
+ name: 'outputSourceDirectory',
94
+ value: props.outputSourceDirectory,
95
+ },
96
+ {
97
+ name: 'projectName',
98
+ value: props.codeBuildProjectName,
99
+ },
100
+ {
101
+ name: 'outputEnvFile',
102
+ value: props.outputEnvFile.toString(),
103
+ },
104
+ {
105
+ name: 'envFileKey',
106
+ value: `deploy-time-build/${event.StackId.split('/')[1]}/${event.LogicalResourceId}/${newPhysicalId}.env`,
107
+ },
108
+ {
109
+ name: 'envNames',
110
+ value: Object.keys(props.environment ?? {}).join(','),
111
+ },
112
+ ...Object.entries(props.environment ?? {}).map(([name, value]) => ({
113
+ name,
114
+ value,
115
+ })),
116
+ ],
117
+ });
118
+ break;
119
+ case 'SociIndexBuild':
120
+ command = new StartBuildCommand({
121
+ projectName: props.codeBuildProjectName,
122
+ environmentVariablesOverride: [
123
+ ...commonEnvironments,
124
+ {
125
+ name: 'repositoryName',
126
+ value: props.repositoryName,
127
+ },
128
+ {
129
+ name: 'imageTag',
130
+ value: props.imageTag,
131
+ },
132
+ {
133
+ name: 'projectName',
134
+ value: props.codeBuildProjectName,
135
+ },
136
+ ],
137
+ });
138
+ break;
139
+ case 'SociIndexV2Build':
140
+ command = new StartBuildCommand({
141
+ projectName: props.codeBuildProjectName,
142
+ environmentVariablesOverride: [
143
+ ...commonEnvironments,
144
+ {
145
+ name: 'repositoryName',
146
+ value: props.repositoryName,
147
+ },
148
+ {
149
+ name: 'inputImageTag',
150
+ value: props.inputImageTag,
151
+ },
152
+ {
153
+ name: 'outputImageTag',
154
+ value: props.outputImageTag,
155
+ },
156
+ {
157
+ name: 'projectName',
158
+ value: props.codeBuildProjectName,
159
+ },
160
+ ],
161
+ });
162
+ break;
163
+ case 'ContainerImageBuild': {
164
+ const imageTag = props.imageTag ?? `${props.tagPrefix ?? ''}${newPhysicalId}`;
165
+ command = new StartBuildCommand({
166
+ projectName: props.codeBuildProjectName,
167
+ environmentVariablesOverride: [
168
+ ...commonEnvironments,
169
+ {
170
+ name: 'repositoryUri',
171
+ value: props.repositoryUri,
172
+ },
173
+ {
174
+ name: 'repositoryAuthUri',
175
+ value: props.repositoryUri.split('/')[0],
176
+ },
177
+ {
178
+ name: 'repositoryRegion',
179
+ value: props.repositoryUri.split('.')[3],
180
+ },
181
+ {
182
+ name: 'buildCommand',
183
+ value: props.buildCommand,
184
+ },
185
+ {
186
+ name: 'imageTag',
187
+ value: imageTag,
188
+ },
189
+ {
190
+ name: 'projectName',
191
+ value: props.codeBuildProjectName,
192
+ },
193
+ {
194
+ name: 'sourceS3Url',
195
+ value: props.sourceS3Url,
196
+ },
197
+ ],
198
+ });
199
+ break;
200
+ }
201
+ default:
202
+ throw new Error(`invalid event type ${props}}`);
203
+ }
204
+ // start code build project
205
+ let retries = 0;
206
+ while (retries < 10) {
207
+ try {
208
+ await cb.send(command);
209
+ break;
210
+ } catch (error: any) {
211
+ // Sometimes AccessDeniedException is thrown due to IAM propagation delay. It should be resolved with retry.
212
+ if (error.name === 'AccessDeniedException') {
213
+ retries++;
214
+ console.log(`AccessDeniedException encountered, retrying (${retries})...`);
215
+ await setTimeout(5000);
216
+ } else {
217
+ throw error;
218
+ }
219
+ }
220
+ }
221
+
222
+ // Sometimes CodeBuild build fails before running buildspec, without calling the CFn callback.
223
+ // We can poll the status of a build for a few minutes and sendStatus if such errors are detected.
224
+ // if (build.build?.id == null) {
225
+ // throw new Error('build id is null');
226
+ // }
227
+
228
+ // for (let i=0; i< 20; i++) {
229
+ // const res = await cb.send(new BatchGetBuildsCommand({ ids: [build.build.id] }));
230
+ // const status = res.builds?.[0].buildStatus;
231
+ // if (status == null) {
232
+ // throw new Error('build status is null');
233
+ // }
234
+
235
+ // await new Promise((resolve) => setTimeout(resolve, 5000));
236
+ // }
237
+ } else {
238
+ // Do nothing on a DELETE event.
239
+ await sendStatus('SUCCESS', event, context);
240
+ }
241
+ } catch (e) {
242
+ console.log(e);
243
+ const err = e as Error;
244
+ await sendStatus('FAILED', event, context, err.message);
245
+ }
246
+ };
247
+
248
+ const sendStatus = async (status: 'SUCCESS' | 'FAILED', event: Event, context: Context, reason?: string) => {
249
+ const responseBody: CloudFormationCustomResourceResponse = {
250
+ Status: status,
251
+ Reason: reason ?? 'See the details in CloudWatch Log Stream: ' + context.logStreamName,
252
+ PhysicalResourceId: context.logStreamName,
253
+ StackId: event.StackId,
254
+ RequestId: event.RequestId,
255
+ LogicalResourceId: event.LogicalResourceId,
256
+ NoEcho: false,
257
+ Data: {}, //responseData
258
+ };
259
+ const responseBodyString = JSON.stringify(responseBody);
260
+
261
+ await fetch(event.ResponseURL, {
262
+ method: 'PUT',
263
+ body: responseBodyString,
264
+ headers: {
265
+ 'Content-Type': '',
266
+ 'Content-Length': responseBodyString.length.toString(),
267
+ },
268
+ });
269
+ };
@@ -0,0 +1,17 @@
1
+ {
2
+ "name": "lambda",
3
+ "version": "1.0.0",
4
+ "description": "",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "build": "esbuild index.ts --bundle --outdir=./dist --platform=node --external:@aws-sdk/*"
8
+ },
9
+ "dependencies": {
10
+ "@aws-sdk/client-codebuild": "^3.321.1"
11
+ },
12
+ "devDependencies": {
13
+ "@types/aws-lambda": "^8.10.95",
14
+ "@types/node": "^18.16.3",
15
+ "esbuild": "^0.25.8"
16
+ }
17
+ }
@@ -0,0 +1,84 @@
1
+ import { IVpc } from 'aws-cdk-lib/aws-ec2';
2
+ import { IRepository } from 'aws-cdk-lib/aws-ecr';
3
+ import { DockerImageAssetProps } from 'aws-cdk-lib/aws-ecr-assets';
4
+ import { IGrantable, IPrincipal } from 'aws-cdk-lib/aws-iam';
5
+ import { DockerImageCode } from 'aws-cdk-lib/aws-lambda';
6
+ import { Construct } from 'constructs';
7
+ export interface ContainerImageBuildProps extends DockerImageAssetProps {
8
+ /**
9
+ * The tag when to push the image
10
+ * @default use assetHash as tag
11
+ */
12
+ readonly tag?: string;
13
+ /**
14
+ * Prefix to add to the image tag
15
+ * @default no prefix
16
+ */
17
+ readonly tagPrefix?: string;
18
+ /**
19
+ * The ECR repository to push the image.
20
+ * @default create a new ECR repository
21
+ */
22
+ readonly repository?: IRepository;
23
+ /**
24
+ * Use zstd for compressing a container image.
25
+ * @default false
26
+ */
27
+ readonly zstdCompression?: boolean;
28
+ /**
29
+ * The VPC where your build job will be deployed.
30
+ * This VPC must have private subnets with NAT Gateways.
31
+ *
32
+ * Use this property when you want to control the outbound IP addresses that base images are pulled from.
33
+ * @default No VPC used.
34
+ */
35
+ readonly vpc?: IVpc;
36
+ }
37
+ /**
38
+ * Options for configuring Lambda Docker image code.
39
+ */
40
+ export interface LambdaDockerImageOptions {
41
+ /**
42
+ * Specify or override the CMD on the specified Docker image or Dockerfile.
43
+ * This needs to be in the 'exec form', viz., `[ 'executable', 'param1', 'param2' ]`.
44
+ * @see <https://docs.docker.com/engine/reference/builder/#cmd>
45
+ * @default - use the CMD specified in the docker image or Dockerfile.
46
+ */
47
+ readonly cmd?: string[];
48
+ /**
49
+ * Specify or override the ENTRYPOINT on the specified Docker image or Dockerfile.
50
+ * An ENTRYPOINT allows you to configure a container that will run as an executable.
51
+ * This needs to be in the 'exec form', viz., `[ 'executable', 'param1', 'param2' ]`.
52
+ * @see <https://docs.docker.com/engine/reference/builder/#entrypoint>
53
+ * @default - use the ENTRYPOINT in the docker image or Dockerfile.
54
+ */
55
+ readonly entrypoint?: string[];
56
+ /**
57
+ * Specify or override the WORKDIR on the specified Docker image or Dockerfile.
58
+ * A WORKDIR allows you to configure the working directory the container will use.
59
+ * @see <https://docs.docker.com/engine/reference/builder/#workdir>
60
+ * @default - use the WORKDIR in the docker image or Dockerfile.
61
+ */
62
+ readonly workingDirectory?: string;
63
+ }
64
+ /**
65
+ * Build a container image and push it to an ECR repository on deploy-time.
66
+ */
67
+ export declare class ContainerImageBuild extends Construct implements IGrantable {
68
+ private readonly props;
69
+ readonly grantPrincipal: IPrincipal;
70
+ readonly repository: IRepository;
71
+ readonly imageTag: string;
72
+ readonly imageUri: string;
73
+ constructor(scope: Construct, id: string, props: ContainerImageBuildProps);
74
+ /**
75
+ * Get the instance of {@link DockerImageCode} for a Lambda function image.
76
+ * @param options Optional configuration for Docker image code.
77
+ */
78
+ toLambdaDockerImageCode(options?: LambdaDockerImageOptions): DockerImageCode;
79
+ /**
80
+ * Get the instance of {@link ContainerImage} for an ECS task definition.
81
+ */
82
+ toEcsDockerImageCode(): import("aws-cdk-lib/aws-ecs").EcrImage;
83
+ private getDockerBuildCommand;
84
+ }