token-injectable-docker-builder 0.1.0

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.
package/README.md ADDED
@@ -0,0 +1,12 @@
1
+ # Welcome to your CDK TypeScript Construct Library project
2
+
3
+ You should explore the contents of this project. It demonstrates a CDK Construct Library that includes a construct (`DockerImageAsset`)
4
+ which contains an Amazon SQS queue that is subscribed to an Amazon SNS topic.
5
+
6
+ The construct defines an interface (`DockerImageAssetProps`) to configure the visibility timeout of the queue.
7
+
8
+ ## Useful commands
9
+
10
+ * `npm run build` compile typescript to js
11
+ * `npm run watch` watch for changes and compile
12
+ * `npm run test` perform the jest unit tests
package/jest.config.js ADDED
@@ -0,0 +1,8 @@
1
+ module.exports = {
2
+ testEnvironment: 'node',
3
+ roots: ['<rootDir>/test'],
4
+ testMatch: ['**/*.test.ts'],
5
+ transform: {
6
+ '^.+\\.tsx?$': 'ts-jest'
7
+ }
8
+ };
package/package.json ADDED
@@ -0,0 +1,25 @@
1
+ {
2
+ "name": "token-injectable-docker-builder",
3
+ "version": "0.1.0",
4
+ "main": "lib/index.js",
5
+ "types": "lib/index.d.ts",
6
+ "scripts": {
7
+ "build": "tsc",
8
+ "watch": "tsc -w",
9
+ "test": "jest"
10
+ },
11
+ "devDependencies": {
12
+ "@aws-cdk/assertions": "^1.204.0",
13
+ "@types/jest": "^29.5.14",
14
+ "@types/node": "22.7.9",
15
+ "aws-cdk-lib": "2.166.0",
16
+ "constructs": "^10.0.0",
17
+ "jest": "^29.7.0",
18
+ "ts-jest": "^29.2.5",
19
+ "typescript": "~5.6.3"
20
+ },
21
+ "peerDependencies": {
22
+ "aws-cdk-lib": "2.166.0",
23
+ "constructs": "^10.0.0"
24
+ }
25
+ }
@@ -0,0 +1,97 @@
1
+ const { CodeBuildClient, ListBuildsForProjectCommand, BatchGetBuildsCommand } = require('@aws-sdk/client-codebuild');
2
+ const { CloudWatchLogsClient, GetLogEventsCommand } = require('@aws-sdk/client-cloudwatch-logs');
3
+
4
+ exports.handler = async (event, context) => {
5
+ console.log('isCompleteHandler Event:', JSON.stringify(event, null, 2));
6
+
7
+ // Initialize AWS SDK v3 clients
8
+ const codebuildClient = new CodeBuildClient({ region: process.env.AWS_REGION });
9
+ const cloudwatchlogsClient = new CloudWatchLogsClient({ region: process.env.AWS_REGION });
10
+
11
+ try {
12
+ const projectName = event.ResourceProperties.ProjectName;
13
+
14
+ if (!projectName) {
15
+ throw new Error('ProjectName is required in ResourceProperties');
16
+ }
17
+
18
+ console.log(`Checking status for CodeBuild project: ${projectName}`);
19
+
20
+ // Retrieve the latest build for the given project
21
+ const listBuildsCommand = new ListBuildsForProjectCommand({
22
+ projectName: projectName,
23
+ sortOrder: 'DESCENDING',
24
+ maxResults: 1,
25
+ });
26
+
27
+ const listBuildsResp = await codebuildClient.send(listBuildsCommand);
28
+ const buildIds = listBuildsResp.ids;
29
+
30
+ if (!buildIds || buildIds.length === 0) {
31
+ throw new Error(`No builds found for project: ${projectName}`);
32
+ }
33
+
34
+ const buildId = buildIds[0];
35
+ console.log(`Latest Build ID: ${buildId}`);
36
+
37
+ // Get build details
38
+ const batchGetBuildsCommand = new BatchGetBuildsCommand({
39
+ ids: [buildId],
40
+ });
41
+
42
+ const buildDetailsResp = await codebuildClient.send(batchGetBuildsCommand);
43
+ const build = buildDetailsResp.builds[0];
44
+
45
+ if (!build) {
46
+ throw new Error(`Build details not found for Build ID: ${buildId}`);
47
+ }
48
+
49
+ const buildStatus = build.buildStatus;
50
+ console.log(`Build Status: ${buildStatus}`);
51
+
52
+ if (buildStatus === 'IN_PROGRESS') {
53
+ // Build is still in progress
54
+ console.log('Build is still in progress.');
55
+ return { IsComplete: false };
56
+ } else if (buildStatus === 'SUCCEEDED') {
57
+ // Build succeeded
58
+ console.log('Build succeeded.');
59
+ return { IsComplete: true };
60
+ } else if (['FAILED', 'FAULT', 'STOPPED', 'TIMED_OUT'].includes(buildStatus)) {
61
+ // Build failed; retrieve last 5 log lines
62
+ const logsInfo = build.logs;
63
+ if (logsInfo && logsInfo.groupName && logsInfo.streamName) {
64
+ console.log(`Retrieving logs from CloudWatch Logs Group: ${logsInfo.groupName}, Stream: ${logsInfo.streamName}`);
65
+
66
+ const getLogEventsCommand = new GetLogEventsCommand({
67
+ logGroupName: logsInfo.groupName,
68
+ logStreamName: logsInfo.streamName,
69
+ startFromHead: false, // Start from the end to get latest logs
70
+ limit: 5,
71
+ });
72
+
73
+ const logEventsResp = await cloudwatchlogsClient.send(getLogEventsCommand);
74
+ const logEvents = logEventsResp.events;
75
+ const lastFiveMessages = logEvents.map((event) => event.message).reverse().join('\n');
76
+
77
+ const errorMessage = `Build failed with status: ${buildStatus}\nLast 5 build logs:\n${lastFiveMessages}`;
78
+ console.error(errorMessage);
79
+
80
+ // Throw an error to indicate failure to the CDK provider
81
+ throw new Error(errorMessage);
82
+ } else {
83
+ const errorMessage = `Build failed with status: ${buildStatus}, but logs are not available.`;
84
+ console.error(errorMessage);
85
+ throw new Error(errorMessage);
86
+ }
87
+ } else {
88
+ const errorMessage = `Unknown build status: ${buildStatus}`;
89
+ console.error(errorMessage);
90
+ throw new Error(errorMessage);
91
+ }
92
+ } catch (error) {
93
+ console.error('Error in isCompleteHandler:', error);
94
+ // Rethrow the error to inform the CDK provider of the failure
95
+ throw error;
96
+ }
97
+ };
@@ -0,0 +1,39 @@
1
+ const { CodeBuildClient, StartBuildCommand } = require('@aws-sdk/client-codebuild');
2
+
3
+ exports.handler = async (event, context) => {
4
+ console.log('Event:', JSON.stringify(event, null, 2));
5
+
6
+ // Initialize the AWS SDK v3 CodeBuild client
7
+ const codebuildClient = new CodeBuildClient({ region: process.env.AWS_REGION });
8
+
9
+ // Set the PhysicalResourceId
10
+ let physicalResourceId = event.PhysicalResourceId || event.LogicalResourceId;
11
+
12
+ if (event.RequestType === 'Create' || event.RequestType === 'Update') {
13
+ const params = {
14
+ projectName: event.ResourceProperties.ProjectName,
15
+ };
16
+
17
+ try {
18
+ const command = new StartBuildCommand(params); // Create the command
19
+ const build = await codebuildClient.send(command); // Send the command
20
+ console.log('Started build:', JSON.stringify(build, null, 2));
21
+ } catch (error) {
22
+ console.error('Error starting build:', error);
23
+
24
+ return {
25
+ PhysicalResourceId: physicalResourceId,
26
+ Data: {},
27
+ Reason: error.message,
28
+ };
29
+ }
30
+ } else if (event.RequestType === 'Delete') {
31
+ // No action needed for delete, but ensure PhysicalResourceId remains the same
32
+ console.log('Delete request received. No action required.');
33
+ }
34
+
35
+ return {
36
+ PhysicalResourceId: physicalResourceId,
37
+ Data: {},
38
+ };
39
+ };
package/tsconfig.json ADDED
@@ -0,0 +1,31 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2020",
4
+ "module": "commonjs",
5
+ "lib": [
6
+ "es2020",
7
+ "dom"
8
+ ],
9
+ "declaration": true,
10
+ "strict": true,
11
+ "noImplicitAny": true,
12
+ "strictNullChecks": true,
13
+ "noImplicitThis": true,
14
+ "alwaysStrict": true,
15
+ "noUnusedLocals": false,
16
+ "noUnusedParameters": false,
17
+ "noImplicitReturns": true,
18
+ "noFallthroughCasesInSwitch": false,
19
+ "inlineSourceMap": true,
20
+ "inlineSources": true,
21
+ "experimentalDecorators": true,
22
+ "strictPropertyInitialization": false,
23
+ "typeRoots": [
24
+ "./node_modules/@types"
25
+ ]
26
+ },
27
+ "exclude": [
28
+ "node_modules",
29
+ "cdk.out"
30
+ ]
31
+ }