token-injectable-docker-builder 0.1.1 → 0.1.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.
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/lib/index.ts ADDED
@@ -0,0 +1,171 @@
1
+ import * as path from 'path';
2
+ import { Duration, CustomResource, Stack } from 'aws-cdk-lib';
3
+ import { Project, Source, LinuxBuildImage, BuildSpec } from 'aws-cdk-lib/aws-codebuild';
4
+ import { Repository } from 'aws-cdk-lib/aws-ecr';
5
+ import { PolicyStatement } from 'aws-cdk-lib/aws-iam';
6
+ import { Code, DockerImageCode, Runtime } from 'aws-cdk-lib/aws-lambda';
7
+ import { Asset } from 'aws-cdk-lib/aws-s3-assets';
8
+ import { Provider } from 'aws-cdk-lib/custom-resources';
9
+ import { Construct } from 'constructs';
10
+ import { ContainerImage } from 'aws-cdk-lib/aws-ecs';
11
+ import * as crypto from 'crypto';
12
+ import { Function } from 'aws-cdk-lib/aws-lambda';
13
+
14
+ export interface TokenInjectableDockerBuilderProps {
15
+ path: string;
16
+ buildArgs?: { [key: string]: string };
17
+ }
18
+
19
+ export class TokenInjectableDockerBuilder extends Construct {
20
+ private readonly ecrRepository: Repository;
21
+ private readonly buildTriggerResource: CustomResource;
22
+
23
+ constructor(scope: Construct, id: string, props: TokenInjectableDockerBuilderProps) {
24
+ super(scope, id);
25
+
26
+ const { path: sourcePath, buildArgs } = props; // Default to linux/amd64
27
+
28
+ // Define absolute paths for Lambda handlers
29
+ const onEventHandlerPath = path.resolve(__dirname, '../src/onEventHandler');
30
+ const isCompleteHandlerPath = path.resolve(__dirname, '../src/isCompleteHandler');
31
+
32
+ // Create an ECR repository
33
+ this.ecrRepository = new Repository(this, 'ECRRepository');
34
+
35
+ // Package the source code as an asset
36
+ const sourceAsset = new Asset(this, 'SourceAsset', {
37
+ path: sourcePath, // Path to the Dockerfile or source code
38
+ });
39
+
40
+ // Transform buildArgs into a string of --build-arg KEY=VALUE
41
+ const buildArgsString = buildArgs
42
+ ? Object.entries(buildArgs)
43
+ .map(([key, value]) => `--build-arg ${key}=${value}`)
44
+ .join(' ')
45
+ : '';
46
+
47
+ // Pass the buildArgsString and platform as environment variables
48
+ const environmentVariables: { [name: string]: { value: string } } = {
49
+ ECR_REPO_URI: { value: this.ecrRepository.repositoryUri },
50
+ BUILD_ARGS: { value: buildArgsString },
51
+ };
52
+
53
+ // Create a CodeBuild project
54
+ const codeBuildProject = new Project(this, 'UICodeBuildProject', {
55
+ source: Source.s3({
56
+ bucket: sourceAsset.bucket,
57
+ path: sourceAsset.s3ObjectKey,
58
+ }),
59
+ environment: {
60
+ buildImage: LinuxBuildImage.STANDARD_7_0,
61
+ privileged: true, // Required for Docker builds
62
+ },
63
+ environmentVariables: environmentVariables,
64
+ buildSpec: BuildSpec.fromObject({
65
+ version: '0.2',
66
+ phases: {
67
+ pre_build: {
68
+ commands: [
69
+ 'echo "Retrieving AWS Account ID..."',
70
+ 'export ACCOUNT_ID=$(aws sts get-caller-identity --query Account --output text)',
71
+ 'echo "Logging in to Amazon ECR..."',
72
+ 'aws ecr get-login-password --region $AWS_DEFAULT_REGION | docker login --username AWS --password-stdin $ACCOUNT_ID.dkr.ecr.$AWS_DEFAULT_REGION.amazonaws.com',
73
+ ],
74
+ },
75
+ build: {
76
+ commands: [
77
+ 'echo Build phase: Building the Docker image...',
78
+ 'docker build $BUILD_ARGS -t $ECR_REPO_URI:latest $CODEBUILD_SRC_DIR',
79
+ ],
80
+ },
81
+ post_build: {
82
+ commands: [
83
+ 'echo Post-build phase: Pushing the Docker image...',
84
+ 'docker push $ECR_REPO_URI:latest',
85
+ ],
86
+ },
87
+ },
88
+ }),
89
+ });
90
+
91
+ // Grant permissions to interact with ECR
92
+ this.ecrRepository.grantPullPush(codeBuildProject);
93
+
94
+ codeBuildProject.role!.addToPrincipalPolicy(
95
+ new PolicyStatement({
96
+ actions: ['ecr:GetAuthorizationToken'],
97
+ resources: ['*'],
98
+ })
99
+ );
100
+
101
+ // Grant permissions to CodeBuild for CloudWatch Logs
102
+ codeBuildProject.role!.addToPrincipalPolicy(
103
+ new PolicyStatement({
104
+ actions: ['logs:PutLogEvents', 'logs:CreateLogGroup', 'logs:CreateLogStream'],
105
+ resources: [`arn:aws:logs:${Stack.of(this).region}:${Stack.of(this).account}:*`],
106
+ })
107
+ );
108
+
109
+ // Create Node.js Lambda function for onEvent
110
+ const onEventHandlerFunction = new Function(this, 'OnEventHandlerFunction', {
111
+ runtime: Runtime.NODEJS_18_X, // Use Node.js runtime
112
+ code: Code.fromAsset(onEventHandlerPath), // Path to handler code
113
+ handler: 'index.handler', // Entry point (adjust as needed)
114
+ timeout: Duration.minutes(15),
115
+ });
116
+
117
+ onEventHandlerFunction.addToRolePolicy(
118
+ new PolicyStatement({
119
+ actions: ['codebuild:StartBuild'],
120
+ resources: [codeBuildProject.projectArn], // Restrict to specific project
121
+ })
122
+ );
123
+
124
+ // Create Node.js Lambda function for isComplete
125
+ const isCompleteHandlerFunction = new Function(this, 'IsCompleteHandlerFunction', {
126
+ runtime: Runtime.NODEJS_18_X,
127
+ code: Code.fromAsset(isCompleteHandlerPath),
128
+ handler: 'index.handler',
129
+ timeout: Duration.minutes(15),
130
+ });
131
+
132
+ isCompleteHandlerFunction.addToRolePolicy(
133
+ new PolicyStatement({
134
+ actions: [
135
+ 'codebuild:BatchGetBuilds',
136
+ 'codebuild:ListBuildsForProject',
137
+ 'logs:GetLogEvents',
138
+ 'logs:DescribeLogStreams',
139
+ 'logs:DescribeLogGroups'
140
+ ],
141
+ resources: ['*'],
142
+ })
143
+ );
144
+
145
+ // Create a custom resource provider
146
+ const provider = new Provider(this, 'CustomResourceProvider', {
147
+ onEventHandler: onEventHandlerFunction,
148
+ isCompleteHandler: isCompleteHandlerFunction,
149
+ queryInterval: Duration.minutes(1),
150
+ });
151
+
152
+ // Define the custom resource
153
+ this.buildTriggerResource = new CustomResource(this, 'BuildTriggerResource', {
154
+ serviceToken: provider.serviceToken,
155
+ properties: {
156
+ ProjectName: codeBuildProject.projectName,
157
+ Trigger: crypto.randomUUID(),
158
+ },
159
+ });
160
+
161
+ this.buildTriggerResource.node.addDependency(codeBuildProject);
162
+ }
163
+
164
+ public getContainerImage(): ContainerImage {
165
+ return ContainerImage.fromEcrRepository(this.ecrRepository, 'latest');
166
+ }
167
+
168
+ public getDockerImageCode(): DockerImageCode {
169
+ return DockerImageCode.fromEcr(this.ecrRepository);
170
+ }
171
+ }
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.3",
4
4
  "main": "lib/index.js",
5
5
  "types": "lib/index.d.ts",
6
6
  "scripts": {
@@ -21,5 +21,30 @@
21
21
  "peerDependencies": {
22
22
  "aws-cdk-lib": "2.166.0",
23
23
  "constructs": "^10.0.0"
24
- }
24
+ },
25
+ "keywords": [
26
+ "aws",
27
+ "cdk",
28
+ "aws-cdk",
29
+ "docker",
30
+ "ecr",
31
+ "lambda",
32
+ "custom-resource",
33
+ "docker-build",
34
+ "codebuild",
35
+ "token-injection",
36
+ "docker-image",
37
+ "aws-codebuild",
38
+ "aws-ecr",
39
+ "docker-builder",
40
+ "cdk-construct",
41
+ "lambda-custom-resource",
42
+ "container-image",
43
+ "aws-lambda",
44
+ "aws-cdk-lib",
45
+ "cloud-development-kit",
46
+ "ci-cd",
47
+ "aws-ci-cd",
48
+ "infrastructure-as-code"
49
+ ]
25
50
  }
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
- };
@@ -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,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZG9ja2VyX2ltYWdlX2Fzc2V0LnRlc3QuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyJkb2NrZXJfaW1hZ2VfYXNzZXQudGVzdC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLG1DQUFtQztBQUNuQyx1REFBa0Q7QUFDbEQsd0NBQTREO0FBRTVELElBQUksQ0FBQyw2Q0FBNkMsRUFBRSxHQUFHLEVBQUU7SUFDdkQsTUFBTSxHQUFHLEdBQUcsSUFBSSxHQUFHLENBQUMsR0FBRyxFQUFFLENBQUM7SUFDMUIsTUFBTSxLQUFLLEdBQUcsSUFBSSxHQUFHLENBQUMsS0FBSyxDQUFDLEdBQUcsRUFBRSxXQUFXLENBQUMsQ0FBQztJQUU5QyxJQUFJLG9DQUE0QixDQUFDLEtBQUssRUFBRSxzQkFBc0IsRUFBRTtRQUM5RCxJQUFJLEVBQUUsc0JBQXNCLEVBQUUseUJBQXlCO1FBQ3ZELFNBQVMsRUFBRSxFQUFFLEdBQUcsRUFBRSxNQUFNLEVBQUU7S0FDM0IsQ0FBQyxDQUFDO0lBRUgsTUFBTSxRQUFRLEdBQUcscUJBQVEsQ0FBQyxTQUFTLENBQUMsS0FBSyxDQUFDLENBQUM7SUFFM0MsMkNBQTJDO0lBQzNDLFFBQVEsQ0FBQyxlQUFlLENBQUMsc0JBQXNCLEVBQUUsQ0FBQyxDQUFDLENBQUM7SUFFcEQsc0VBQXNFO0lBQ3RFLFFBQVEsQ0FBQyxxQkFBcUIsQ0FBQyx5QkFBeUIsRUFBRTtRQUN4RCxXQUFXLEVBQUU7WUFDWCxXQUFXL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