token-injectable-docker-builder 0.1.1 → 0.1.2

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 CHANGED
@@ -1,12 +1,152 @@
1
- # Welcome to your CDK TypeScript Construct Library project
1
+ # TokenInjectableDockerBuilder
2
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.
3
+ The `TokenInjectableDockerBuilder` is a powerful AWS CDK construct that automates the building, pushing, and deployment of Docker images to Amazon Elastic Container Registry (ECR) using AWS CodeBuild and Lambda custom resources. This construct simplifies workflows by enabling token-based Docker image customization.
5
4
 
6
- The construct defines an interface (`DockerImageAssetProps`) to configure the visibility timeout of the queue.
5
+ ## Features
7
6
 
8
- ## Useful commands
7
+ - Automatically builds and pushes Docker images to ECR.
8
+ - Supports custom build arguments for Docker builds.
9
+ - Provides Lambda functions to handle `onEvent` and `isComplete` lifecycle events for custom resources.
10
+ - Retrieves the latest Docker image from ECR for use in ECS or Lambda.
9
11
 
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
12
+ ---
13
+
14
+ ## Installation
15
+
16
+ First, install the construct using NPM:
17
+
18
+ ```bash
19
+ npm install token-injectable-docker-builder
20
+ ```
21
+
22
+ ---
23
+
24
+ ## Constructor
25
+
26
+ ### `TokenInjectableDockerBuilder`
27
+
28
+ #### Parameters
29
+
30
+ - **`scope`**: The construct's parent scope.
31
+ - **`id`**: The construct ID.
32
+ - **`props`**: Configuration properties.
33
+
34
+ #### Properties in `TokenInjectableDockerBuilderProps`
35
+
36
+ | Property | Type | Required | Description |
37
+ |----------------|-----------------------------------|----------|------------------------------------------------------------|
38
+ | `path` | `string` | Yes | The file path to the Dockerfile or source code directory. |
39
+ | `buildArgs` | `{ [key: string]: string }` | No | Build arguments to pass to the Docker build process. |
40
+
41
+ ---
42
+
43
+ ## Usage Example
44
+
45
+ Here is an example of how to use the `TokenInjectableDockerBuilder` in your AWS CDK application:
46
+
47
+ ```typescript
48
+ import * as cdk from 'aws-cdk-lib';
49
+ import { TokenInjectableDockerBuilder } from 'token-injectable-docker-builder';
50
+
51
+ export class MyStack extends cdk.Stack {
52
+ constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
53
+ super(scope, id, props);
54
+
55
+ // Create a TokenInjectableDockerBuilder construct
56
+ const dockerBuilder = new TokenInjectableDockerBuilder(this, 'MyDockerBuilder', {
57
+ path: './docker', // Path to the directory containing your Dockerfile
58
+ buildArgs: {
59
+ TOKEN: 'my-secret-token', // Example of a build argument
60
+ ENV: 'production',
61
+ },
62
+ });
63
+
64
+ // Retrieve the container image for ECS
65
+ const containerImage = dockerBuilder.getContainerImage();
66
+
67
+ // Retrieve the Docker image code for Lambda
68
+ const dockerImageCode = dockerBuilder.getDockerImageCode();
69
+
70
+ // Example: Use the container image in an ECS service
71
+ new ecs.FargateTaskDefinition(this, 'TaskDefinition', {
72
+ containerImage,
73
+ });
74
+
75
+ // Example: Use the Docker image code in a Lambda function
76
+ new lambda.Function(this, 'DockerLambdaFunction', {
77
+ runtime: lambda.Runtime.FROM_IMAGE,
78
+ code: dockerImageCode,
79
+ handler: lambda.Handler.FROM_IMAGE,
80
+ });
81
+ }
82
+ }
83
+ ```
84
+
85
+ ---
86
+
87
+ ## How It Works
88
+
89
+ 1. **Docker Source**: The construct packages the source code or Dockerfile specified in the `path` property as an S3 asset.
90
+ 2. **CodeBuild Project**:
91
+ - Uses the packaged asset and build arguments to build the Docker image.
92
+ - Pushes the image to an ECR repository.
93
+ 3. **Custom Resource**:
94
+ - Triggers the build process using a Lambda function (`onEvent`).
95
+ - Monitors the build status using another Lambda function (`isComplete`).
96
+ 4. **Outputs**:
97
+ - Provides the Docker image via `getContainerImage()` for ECS use.
98
+ - Provides the Docker image code via `getDockerImageCode()` for Lambda.
99
+
100
+ ---
101
+
102
+ ## Methods
103
+
104
+ ### `getContainerImage()`
105
+
106
+ Returns a `ContainerImage` object that can be used in ECS services.
107
+
108
+ ```typescript
109
+ const containerImage = dockerBuilder.getContainerImage();
110
+ ```
111
+
112
+ ### `getDockerImageCode()`
113
+
114
+ Returns a `DockerImageCode` object that can be used in Lambda functions.
115
+
116
+ ```typescript
117
+ const dockerImageCode = dockerBuilder.getDockerImageCode();
118
+ ```
119
+
120
+ ---
121
+
122
+ ## IAM Permissions
123
+
124
+ This construct automatically grants the required IAM permissions for:
125
+ - CodeBuild to pull and push images to ECR.
126
+ - CodeBuild to write logs to CloudWatch.
127
+ - Lambda functions to monitor the build status and retrieve logs.
128
+
129
+ ---
130
+
131
+ ## Notes
132
+
133
+ - **Build Arguments**: Use the `buildArgs` property to pass custom arguments to the Docker build process. These are transformed into `--build-arg` flags.
134
+ - **ECR Repository**: A new ECR repository is created automatically.
135
+ - **Custom Resources**: Custom resources are used to handle lifecycle events and ensure the build is completed successfully.
136
+
137
+ ---
138
+
139
+ ## Prerequisites
140
+
141
+ Ensure you have the following:
142
+ 1. Docker installed locally if you're testing builds.
143
+ 2. AWS CDK CLI installed (`npm install -g aws-cdk`).
144
+ 3. An AWS account and configured credentials.
145
+
146
+ ---
147
+
148
+ ## Troubleshooting
149
+
150
+ 1. **Build Errors**: Check the AWS CodeBuild logs in CloudWatch.
151
+ 2. **Lambda Function Errors**: Check the `onEvent` and `isComplete` Lambda logs in CloudWatch.
152
+ 3. **Permissions**: Ensure the IAM role for CodeBuild has the required permissions to interact with ECR and CloudWatch.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "token-injectable-docker-builder",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "main": "lib/index.js",
5
5
  "types": "lib/index.d.ts",
6
6
  "scripts": {
package/jest.config.js DELETED
@@ -1,8 +0,0 @@
1
- module.exports = {
2
- testEnvironment: 'node',
3
- roots: ['<rootDir>/test'],
4
- testMatch: ['**/*.test.ts'],
5
- transform: {
6
- '^.+\\.tsx?$': 'ts-jest'
7
- }
8
- };
package/lib/index.d.ts DELETED
@@ -1,16 +0,0 @@
1
- import { DockerImageCode } from 'aws-cdk-lib/aws-lambda';
2
- import { Construct } from 'constructs';
3
- import { ContainerImage } from 'aws-cdk-lib/aws-ecs';
4
- export interface TokenInjectableDockerBuilderProps {
5
- path: string;
6
- buildArgs?: {
7
- [key: string]: string;
8
- };
9
- }
10
- export declare class TokenInjectableDockerBuilder extends Construct {
11
- private readonly ecrRepository;
12
- private readonly buildTriggerResource;
13
- constructor(scope: Construct, id: string, props: TokenInjectableDockerBuilderProps);
14
- getContainerImage(): ContainerImage;
15
- getDockerImageCode(): DockerImageCode;
16
- }
@@ -1,97 +0,0 @@
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
- };
@@ -1,39 +0,0 @@
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
- };
@@ -1 +0,0 @@
1
- export {};
@@ -1,30 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const cdk = require("aws-cdk-lib");
4
- const assertions_1 = require("aws-cdk-lib/assertions");
5
- const index_1 = require("../lib/index");
6
- test('DockerImageAsset creates required resources', () => {
7
- const app = new cdk.App();
8
- const stack = new cdk.Stack(app, 'TestStack');
9
- new index_1.TokenInjectableDockerBuilder(stack, 'TestDockerImageAsset', {
10
- path: './src/onEventHandler', // Path to Docker context
11
- buildArgs: { ENV: 'test' },
12
- });
13
- const template = assertions_1.Template.fromStack(stack);
14
- // Verify that an ECR repository is created
15
- template.resourceCountIs('AWS::ECR::Repository', 1);
16
- // Verify that a CodeBuild project is created with expected properties
17
- template.hasResourceProperties('AWS::CodeBuild::Project', {
18
- Environment: {
19
- ComputeType: 'BUILD_GENERAL1_SMALL',
20
- PrivilegedMode: true,
21
- Image: 'aws/codebuild/standard:7.0',
22
- },
23
- Source: {
24
- Type: 'S3',
25
- },
26
- });
27
- // Verify the Custom Resource is created with the expected service token
28
- template.resourceCountIs('AWS::CloudFormation::CustomResource', 1);
29
- });
30
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZG9ja2VyX2ltYWdlX2Fzc2V0LnRlc3QuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJkb2NrZXJfaW1hZ2VfYXNzZXQudGVzdC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLG1DQUFtQztBQUNuQyx1REFBa0Q7QUFDbEQsd0NBQTREO0FBRTVELElBQUksQ0FBQyw2Q0FBNkMsRUFBRSxHQUFHLEVBQUU7SUFDdkQsTUFBTSxHQUFHLEdBQUcsSUFBSSxHQUFHLENBQUMsR0FBRyxFQUFFLENBQUM7SUFDMUIsTUFBTSxLQUFLLEdBQUcsSUFBSSxHQUFHLENBQUMsS0FBSyxDQUFDLEdBQUcsRUFBRSxXQUFXLENBQUMsQ0FBQztJQUU5QyxJQUFJLG9DQUE0QixDQUFDLEtBQUssRUFBRSxzQkFBc0IsRUFBRTtRQUM5RCxJQUFJLEVBQUUsc0JBQXNCLEVBQUUseUJBQXlCO1FBQ3ZELFNBQVMsRUFBRSxFQUFFLEdBQUcsRUFBRSxNQUFNLEVBQUU7S0FDM0IsQ0FBQyxDQUFDO0lBRUgsTUFBTSxRQUFRLEdBQUcscUJBQVEsQ0FBQyxTQUFTLENBQUMsS0FBSyxDQUFDLENBQUM7SUFFM0MsMkNBQTJDO0lBQzNDLFFBQVEsQ0FBQyxlQUFlLENBQUMsc0JBQXNCLEVBQUUsQ0FBQ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