Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add loginConfig to source/dest, handle in caller #5

Open
wants to merge 1 commit into
base: scanlonp-add-sources
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 29 additions & 15 deletions src/destination.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as ecr from 'aws-cdk-lib/aws-ecr';
import * as iam from 'aws-cdk-lib/aws-iam';
import { LoginType, LoginConfig } from './source';

/**
* Destination information
Expand All @@ -10,6 +11,11 @@ export interface DestinationConfig {
*/
readonly destinationUri: string;

/**
* The login info.
*/
readonly loginConfig: LoginConfig;

/**
* The tag of the deployed image.
* @default - the tag of the source
Expand All @@ -22,7 +28,7 @@ export interface DestinationConfig {
*/
export interface EcrSourceOptions {
/**
* Tag of deployed image
* Tag of deployed image.
* @default - tag of source
*/
readonly tag?: string;
Expand All @@ -43,14 +49,12 @@ export interface EcrSourceOptions {
*/
export abstract class Destination {
/**
* Uses an ECR repository as the destination for the image
* Uses an ECR repository in the same account as the stack as the destination for the image.
*/
public static ecr(repository: ecr.IRepository, options?: EcrSourceOptions): Destination {
return new EcrDestination(repository, options);
}

public abstract readonly config: DestinationConfig;

protected validateTag(tag: string): void {
if (tag.length > 128) {
throw new Error (`Invalid tag: tags may contain a maximum of 128 characters; your tag ${tag} has ${tag.length} characters`);
Expand All @@ -61,18 +65,19 @@ export abstract class Destination {
}

/**
* bind grants the CodeBuild role permissions to pull and push to a repository if necessary
* bind should be invoked by the caller to get the DesitinationConfig
* Bind grants the CodeBuild role permissions to pull and push to a repository if necessary.
* Bind should be invoked by the caller to get the DesitinationConfig.
*/
public abstract bind(role: iam.IGrantable): void;
public abstract bind(role: iam.IGrantable): DestinationConfig;
}

/**
* Class used when the destination of docker image deployment is an ECR repository
* Class used when the destination of docker image deployment is an ECR repository in the same account as the stack
*/
class EcrDestination extends Destination {
private repository: ecr.IRepository;
public readonly config: DestinationConfig;
private options?: EcrSourceOptions;
//public readonly config: DestinationConfig;

constructor(repository: ecr.IRepository, options?: EcrSourceOptions) {
super();
Expand All @@ -81,15 +86,24 @@ class EcrDestination extends Destination {

if (options?.tag !== undefined) {
super.validateTag(options.tag);
this.options = options;
}

this.config = {
destinationUri: repository.repositoryUri,
destinationTag: options?.tag,
};
}

public bind(role: iam.IGrantable): void {
public bind(role: iam.IGrantable): DestinationConfig {
const accountId = this.repository.env.account;
const region = this.repository.env.region;

this.repository.grantPullPush(role);

return {
destinationUri: this.repository.repositoryUri,
loginConfig: {
loginCommand: `aws ecr get-login-password --region ${region} | docker login --username AWS --password-stdin ${accountId}.dkr.ecr.${region}.amazonaws.com`,
loginType: LoginType.ECR,
region: region,
},
destinationTag: this.options?.tag,
};
}
}
33 changes: 16 additions & 17 deletions src/docker-image-deployment.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Stack, CustomResource, Duration } from 'aws-cdk-lib';
import { CustomResource, Duration } from 'aws-cdk-lib';
import * as codebuild from 'aws-cdk-lib/aws-codebuild';
import * as iam from 'aws-cdk-lib/aws-iam';
import { Runtime } from 'aws-cdk-lib/aws-lambda';
Expand Down Expand Up @@ -34,35 +34,34 @@ export class DockerImageDeployment extends Construct {
});

const sourceConfig = props.source.bind(this, { handlerRole });
props.destination.bind(handlerRole);
const destinationConfig = props.destination.bind(handlerRole);

const sourceUri = sourceConfig.imageUri;

const destTag = props.destination.config.destinationTag ?? sourceConfig.imageTag;
const destUri = `${props.destination.config.destinationUri}:${destTag}`;
const destTag = destinationConfig.destinationTag ?? sourceConfig.imageTag;
const destUri = `${destinationConfig.destinationUri}:${destTag}`;

const accountId = Stack.of(this).account;
const region = Stack.of(this).region;

const sourceLoginCommands = [
`aws ecr get-login-password --region ${region} | docker login --username AWS --password-stdin ${accountId}.dkr.ecr.${region}.amazonaws.com`,
];

const buildCommands = [
const commands = [
sourceConfig.loginConfig.loginCommand,
`docker pull ${sourceUri}`,
`docker tag ${sourceUri} ${destUri}`,
`docker push ${destUri}`,
];

if (sourceConfig.loginConfig.loginType !== destinationConfig.loginConfig.loginType
|| sourceConfig.loginConfig.region !== destinationConfig.loginConfig.region) {
commands.push('docker logout');
commands.push(destinationConfig.loginConfig.loginCommand);
}

commands.push(`docker push ${destUri}`);
commands.push('docker logout');

this.cb = new codebuild.Project(this, 'DockerImageDeployProject', {
buildSpec: codebuild.BuildSpec.fromObject({
version: '0.2',
phases: {
pre_build: {
commands: sourceLoginCommands,
},
build: {
commands: buildCommands,
commands: commands,
},
},
}),
Expand Down
75 changes: 68 additions & 7 deletions src/source.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,21 @@
//import * as fs from 'fs';
//import * as path from 'path';
import { Fn } from 'aws-cdk-lib';
import { Stack, Fn } from 'aws-cdk-lib';
import * as ecr from 'aws-cdk-lib/aws-ecr';
import * as ecr_assets from 'aws-cdk-lib/aws-ecr-assets';
import * as iam from 'aws-cdk-lib/aws-iam';
import { Construct } from 'constructs';

/**
* Denotes what type of registry is provided.
* ECR is an ECR repository in the same account as the stack.
* EXTERNALECR is any other ECR respoitory.
*/
export enum LoginType {
ECR,
EXTERNALECR,
}

/**
* Source information
*/
Expand All @@ -19,14 +29,41 @@ export interface SourceConfig {
* The source tag.
*/
readonly imageTag: string;

/**
* The login info.
*/
readonly loginConfig: LoginConfig;
}

/**
* Login commands for specified registry
*/
export interface LoginConfig {
/**
* Command to run in codebuild to login.
* Formatted `docker login ...`.
*/
readonly loginCommand: string;

/**
* Type of registry logged in to
*/
readonly loginType: LoginType;

/**
* region of ECR repository
* @default - undefined if not an ECR repository
*/
readonly region?: string;
}

/**
* Bind context for Source
*/
export interface SourceContext {
/**
* The role for the handler
* The role for the handler.
*/
readonly handlerRole: iam.IRole;
}
Expand All @@ -45,7 +82,7 @@ export interface SourceContext {
*/
export abstract class Source {
/**
* Uses a local image built from a Dockerfile in a local directory as the source
* Uses a local image built from a Dockerfile in a local directory as the source.
*
* @param path - path to the directory containing your Dockerfile (not a path to a file)
*/
Expand All @@ -60,10 +97,10 @@ export abstract class Source {
public static asset(asset: ecr_assets.DockerImageAsset): Source { // | ecr_assets.TarballImageAsset): Source {
return new AssetSource(asset);
}

/**
* bind grants the CodeBuild role permissions to pull from a repository if necessary
* bind should be invoked by the caller to get the SourceConfig
* Bind grants the CodeBuild role permissions to pull from a repository if necessary.
* Bind should be invoked by the caller to get the SourceConfig.
*/
public abstract bind(scope: Construct, context: SourceContext): SourceConfig;
}
Expand All @@ -80,6 +117,8 @@ class DirectorySource extends Source {
}

public bind(scope: Construct, context: SourceContext): SourceConfig {
const accountId = Stack.of(scope).account;
const region = Stack.of(scope).region;

const asset = new ecr_assets.DockerImageAsset(scope, 'asset', {
directory: this.path,
Expand All @@ -91,10 +130,18 @@ class DirectorySource extends Source {
imageUri: asset.imageUri,
imageTag: Fn.select(1, Fn.split(':', asset.imageUri)), // uri will be something like 'directory/of/image:tag' so this picks out the tag from the token
//imageTag: asset.imageTag - will be available in cdk 2.38.1
loginConfig: {
loginCommand: `aws ecr get-login-password --region ${region} | docker login --username AWS --password-stdin ${accountId}.dkr.ecr.${region}.amazonaws.com`,
loginType: LoginType.ECR,
region: region,
},
};
}
}

/**
* Source of docker image deployment is a an image in an ECR repository in the same account as the stack
*/
class EcrSource extends Source {
private repository: ecr.IRepository;
private tag: string;
Expand All @@ -106,12 +153,19 @@ class EcrSource extends Source {
}

public bind(_scope: Construct, context: SourceContext): SourceConfig {
const accountId = this.repository.env.account;
const region = this.repository.env.region;

this.repository.grantPull(context.handlerRole);

return {
imageUri: this.repository.repositoryUriForTag(this.tag),
imageTag: this.tag,
loginConfig: {
loginCommand: `aws ecr get-login-password --region ${region} | docker login --username AWS --password-stdin ${accountId}.dkr.ecr.${region}.amazonaws.com`,
loginType: LoginType.ECR,
region: region,
},
};
}
}
Expand All @@ -126,13 +180,20 @@ class AssetSource extends Source {
this.tag = Fn.select(1, Fn.split(':', asset.imageUri));
}

public bind(_scope: Construct, context: SourceContext): SourceConfig {
public bind(scope: Construct, context: SourceContext): SourceConfig {
const accountId = Stack.of(scope).account;
const region = Stack.of(scope).region;

this.repository.grantPull(context.handlerRole);

return {
imageUri: this.repository.repositoryUriForTag(this.tag),
imageTag: this.tag,
loginConfig: {
loginCommand: `aws ecr get-login-password --region ${region} | docker login --username AWS --password-stdin ${accountId}.dkr.ecr.${region}.amazonaws.com`,
loginType: LoginType.ECR,
region: region,
},
};
}
}
17 changes: 14 additions & 3 deletions test/docker-image-deploy.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as path from 'path';
import { Match, Template } from 'aws-cdk-lib/assertions';
import * as ecr from 'aws-cdk-lib/aws-ecr';
import * as ecr_assets from 'aws-cdk-lib/aws-ecr-assets';
import * as iam from 'aws-cdk-lib/aws-iam';
import * as cdk from 'aws-cdk-lib/core';
import * as imagedeploy from '../src';

Expand Down Expand Up @@ -287,6 +288,7 @@ describe('DockerImageDeploy', () => {

});

/*
test('ECR login and pull commands are well formatted', () => {
Template.fromStack(stack).hasResourceProperties('AWS::CodeBuild::Project', {
Source: {
Expand All @@ -307,6 +309,7 @@ describe('DockerImageDeploy', () => {
},
});
});
*/
});

describe('Source: ecr', () => {
Expand Down Expand Up @@ -402,16 +405,24 @@ describe('Destination', () => {
const stack = new cdk.Stack();
const repo = new ecr.Repository(stack, 'TestRepository');

// dummy role
const testRole = new iam.Role(stack, 'DockerImageDeployRole', {
assumedBy: new iam.ServicePrincipal('ecr.amazonaws.com'),
});

test('valid tag', () => {
expect(imagedeploy.Destination.ecr(repo, { tag: '_test_TEST-1234.tag-' }).config.destinationTag).toEqual('_test_TEST-1234.tag-');
const destination = imagedeploy.Destination.ecr(repo, { tag: '_test_TEST-1234.tag-' });
expect(destination.bind(testRole).destinationTag).toEqual('_test_TEST-1234.tag-');
});

test('options not provided does not throw', () => {
expect(imagedeploy.Destination.ecr(repo).config.destinationTag).toEqual(undefined);
const destination = imagedeploy.Destination.ecr(repo);
expect(destination.bind(testRole).destinationTag).toEqual(undefined);
});

test('tag not provided does not throw', () => {
expect(imagedeploy.Destination.ecr(repo, {}).config.destinationTag).toEqual(undefined);
const destination = imagedeploy.Destination.ecr(repo, {});
expect(destination.bind(testRole).destinationTag).toEqual(undefined);
});

test('empyty tag', () => {
Expand Down