Skip to content

Commit

Permalink
feat(codebuild): add support for test reports
Browse files Browse the repository at this point in the history
This adds support for CodeBuild's test reports feature.
It includes a new Layer 2 class, ReportGroup.

The default project's IAM role has been augmented with permissions
to create and use test result groups whose names begin with the project's name
(as that is what the default report group created when putting a simple name in the
'reports' buildspec section is called).
There is a new boolean property when creating the project,
addCreateReportGroupPermissions,
that can be used to turn off this behavor.

Fixes #7367
  • Loading branch information
skinny85 committed May 6, 2020
1 parent c6d1a21 commit 4befefc
Show file tree
Hide file tree
Showing 27 changed files with 712 additions and 6 deletions.
62 changes: 62 additions & 0 deletions packages/@aws-cdk/aws-codebuild/README.md
Expand Up @@ -269,6 +269,68 @@ any attempt to save more than one will result in an error.
You can use the [`list-source-credentials` AWS CLI operation](https://docs.aws.amazon.com/cli/latest/reference/codebuild/list-source-credentials.html)
to inspect what credentials are stored in your account.

## Test reports

You can specify a test report in your buildspec:

```typescript
const project = new codebuild.Project(this, 'Project', {
buildSpec: codebuild.BuildSpec.fromObject({
// ...
reports: {
myReport: {
files: '**/*',
'base-directory': 'build/test-results',
},
},
}),
});
```

This will create a new test report group,
with the name `<ProjectName>-myReport`.

The project's role in the CDK will always be granted permissions to create and use report groups
with names starting with the project's name;
if you'd rather not have those permissions added,
you can opt out of it when creating the project:

```typescript
const project = new codebuild.Project(this, 'Project', {
// ...
grantReportGroupPermissions: false,
});
```

Alternatively, you can specify an ARN of an existing resource group,
instead of a simple name, in your buildspec:

```typescript
// create a new ReportGroup
const reportGroup = new codebuild.ReportGroup(this, 'ReportGroup');

const project = new codebuild.Project(this, 'Project', {
buildSpec: codebuild.BuildSpec.fromObject({
// ...
reports: {
[reportGroup.reportGroupArn]: {
files: '**/*',
'base-directory': 'build/test-results',
},
},
}),
});
```

If you do that, you need to grant the project's role permissions to write reports to that report group:

```typescript
reportGroup.grantWrite(project);
```

For more information on the test reports feature,
see the [AWS CodeBuild documentation](https://docs.aws.amazon.com/codebuild/latest/userguide/test-reporting.html).

## Events

CodeBuild projects can be used either as a source for events or be triggered
Expand Down
1 change: 1 addition & 0 deletions packages/@aws-cdk/aws-codebuild/lib/index.ts
@@ -1,6 +1,7 @@
export * from './events';
export * from './pipeline-project';
export * from './project';
export * from './report-group';
export * from './source';
export * from './source-credentials';
export * from './artifacts';
Expand Down
30 changes: 30 additions & 0 deletions packages/@aws-cdk/aws-codebuild/lib/project.ts
Expand Up @@ -16,6 +16,7 @@ import { CodePipelineArtifacts } from './codepipeline-artifacts';
import { IFileSystemLocation } from './file-location';
import { NoArtifacts } from './no-artifacts';
import { NoSource } from './no-source';
import { renderReportGroupArn } from './report-group-utils';
import { ISource } from './source';
import { CODEPIPELINE_SOURCE_ARTIFACTS_TYPE, NO_SOURCE_TYPE } from './source-types';

Expand Down Expand Up @@ -519,6 +520,21 @@ export interface CommonProjectProps {
* @default - no file system locations
*/
readonly fileSystemLocations?: IFileSystemLocation[];

/**
* Add permissions to this project's role to create and use test report groups with name starting with the name of this project.
*
* That is the standard report group that gets created when a simple name
* (in contrast to an ARN)
* is used in the 'reports' section of the buildspec of this project.
* This is usually harmless, but you can turn these off if you don't plan on using test
* reports in this project.
*
* @default true
*
* @see https://docs.aws.amazon.com/codebuild/latest/userguide/test-report-group-naming.html
*/
readonly grantReportGroupPermissions?: boolean;
}

export interface ProjectProps extends CommonProjectProps {
Expand Down Expand Up @@ -762,6 +778,20 @@ export class Project extends ProjectBase {
this.projectName = this.getResourceNameAttribute(resource.ref);

this.addToRolePolicy(this.createLoggingPermission());
// add permissions to create and use test report groups
// with names starting with the project's name,
// unless the customer explicitly opts out of it
if (props.grantReportGroupPermissions !== false) {
this.addToRolePolicy(new iam.PolicyStatement({
actions: [
'codebuild:CreateReportGroup',
'codebuild:CreateReport',
'codebuild:UpdateReport',
'codebuild:BatchPutTestCases',
],
resources: [renderReportGroupArn(this, `${this.projectName}-*`)],
}));
}

if (props.encryptionKey) {
this.encryptionKey = props.encryptionKey;
Expand Down
17 changes: 17 additions & 0 deletions packages/@aws-cdk/aws-codebuild/lib/report-group-utils.ts
@@ -0,0 +1,17 @@
import * as cdk from '@aws-cdk/core';

// this file contains a bunch of functions shared
// between Project and ResourceGroup,
// which we don't want to make part of the public API of this module

export function renderReportGroupArn(scope: cdk.Construct, reportGroupName: string): string {
return cdk.Stack.of(scope).formatArn(reportGroupArnComponents(reportGroupName));
}

export function reportGroupArnComponents(reportGroupName: string): cdk.ArnComponents {
return {
service: 'codebuild',
resource: 'report-group',
resourceName: reportGroupName,
};
}
152 changes: 152 additions & 0 deletions packages/@aws-cdk/aws-codebuild/lib/report-group.ts
@@ -0,0 +1,152 @@
import * as iam from '@aws-cdk/aws-iam';
import * as s3 from '@aws-cdk/aws-s3';
import * as cdk from '@aws-cdk/core';
import { CfnReportGroup } from './codebuild.generated';
import { renderReportGroupArn, reportGroupArnComponents } from './report-group-utils';

/**
* The interface representing the ReportGroup resource -
* either an existing one, imported using the
* {@link ReportGroup.fromReportGroupName} method,
* or a new one, created with the {@link ReportGroup} class.
*/
export interface IReportGroup extends cdk.IResource {
/**
* The ARN of the ReportGroup.
*
* @attribute
*/
readonly reportGroupArn: string;

/**
* The name of the ReportGroup.
*
* @attribute
*/
readonly reportGroupName: string;

/**
* Grants the given entity permissions to write
* (that is, upload reports to)
* this report group.
*/
grantWrite(identity: iam.IGrantable): iam.Grant;
}

abstract class ReportGroupBase extends cdk.Resource implements IReportGroup {
public abstract readonly reportGroupArn: string;
public abstract readonly reportGroupName: string;
protected abstract readonly exportBucket?: s3.IBucket;

public grantWrite(identity: iam.IGrantable): iam.Grant {
const ret = iam.Grant.addToPrincipal({
grantee: identity,
actions: [
'codebuild:CreateReport',
'codebuild:UpdateReport',
'codebuild:BatchPutTestCases',
],
resourceArns: [this.reportGroupArn],
});

if (this.exportBucket) {
this.exportBucket.grantWrite(identity);
}

return ret;
}
}

/**
* Construction properties for {@link ReportGroup}.
*/
export interface ReportGroupProps {
/**
* The physical name of the report group.
*
* @default - CloudFormation-generated name
*/
readonly reportGroupName?: string;

/**
* An optional S3 bucket to export the reports to.
*
* @default - the reports will not be exported
*/
readonly exportBucket?: s3.IBucket;

/**
* Whether to output the report files into the export bucket as-is,
* or create a ZIP from them before doing the export.
* Ignored if {@link exportBucket} has not been provided.
*
* @default - false (the files will not be ZIPped)
*/
readonly zipExport?: boolean;

/**
* What to do when this resource is deleted from a stack.
* As CodeBuild does not allow deleting a ResourceGroup that has reports inside of it,
* this is set to retain the resource by default.
*
* @default RemovalPolicy.RETAIN
*/
readonly removalPolicy?: cdk.RemovalPolicy;
}

/**
* The ReportGroup resource class.
*/
export class ReportGroup extends ReportGroupBase {

/**
* Reference an existing ReportGroup,
* defined outside of the CDK code,
* by name.
*/
public static fromReportGroupName(scope: cdk.Construct, id: string, reportGroupName: string): IReportGroup {
class Import extends ReportGroupBase {
public readonly reportGroupName = reportGroupName;
public readonly reportGroupArn = renderReportGroupArn(scope, reportGroupName);
protected readonly exportBucket = undefined;
}

return new Import(scope, id);
}

public readonly reportGroupArn: string;
public readonly reportGroupName: string;
protected readonly exportBucket?: s3.IBucket;

constructor(scope: cdk.Construct, id: string, props: ReportGroupProps = {}) {
super(scope, id, {
physicalName: props.reportGroupName,
});

const resource = new CfnReportGroup(this, 'Resource', {
type: 'TEST',
exportConfig: {
exportConfigType: props.exportBucket ? 'S3' : 'NO_EXPORT',
s3Destination: props.exportBucket
? {
bucket: props.exportBucket.bucketName,
encryptionDisabled: props.exportBucket.encryptionKey ? false : undefined,
encryptionKey: props.exportBucket.encryptionKey?.keyArn,
packaging: props.zipExport ? 'ZIP' : undefined,
}
: undefined,
},
});
resource.applyRemovalPolicy(props.removalPolicy, {
default: cdk.RemovalPolicy.RETAIN,
});
this.reportGroupArn = this.getResourceArnAttribute(resource.attrArn,
reportGroupArnComponents(this.physicalName));
this.reportGroupName = this.getResourceNameAttribute(
// there is no separate name attribute,
// so use Fn::Select + Fn::Split to make one
cdk.Fn.select(1, cdk.Fn.split('/', resource.ref)),
);
this.exportBucket = props.exportBucket;
}
}
1 change: 1 addition & 0 deletions packages/@aws-cdk/aws-codebuild/test/integ.caching.ts
Expand Up @@ -22,6 +22,7 @@ new codebuild.Project(stack, 'MyProject', {
paths: ['/root/.cache/pip/**/*'],
},
}),
grantReportGroupPermissions: false,
});

app.synth();
Expand Up @@ -78,6 +78,39 @@
]
}
]
},
{
"Action": [
"codebuild:CreateReportGroup",
"codebuild:CreateReport",
"codebuild:UpdateReport",
"codebuild:BatchPutTestCases"
],
"Effect": "Allow",
"Resource": {
"Fn::Join": [
"",
[
"arn:",
{
"Ref": "AWS::Partition"
},
":codebuild:",
{
"Ref": "AWS::Region"
},
":",
{
"Ref": "AWS::AccountId"
},
":report-group/",
{
"Ref": "MyProject39F7B0AE"
},
"-*"
]
]
}
}
],
"Version": "2012-10-17"
Expand Down Expand Up @@ -115,4 +148,4 @@
}
}
}
}
}
Expand Up @@ -15,6 +15,7 @@ class TestStack extends cdk.Stack {
},
},
}),
grantReportGroupPermissions: false,
/// !show
environment: {
buildImage: codebuild.LinuxBuildImage.fromAsset(this, 'MyImage', {
Expand Down
Expand Up @@ -18,6 +18,7 @@ class TestStack extends cdk.Stack {
},
},
}),
grantReportGroupPermissions: false,
/// !show
environment: {
buildImage: codebuild.LinuxBuildImage.fromDockerRegistry('my-registry/my-repo', {
Expand Down
1 change: 1 addition & 0 deletions packages/@aws-cdk/aws-codebuild/test/integ.ecr.lit.ts
Expand Up @@ -17,6 +17,7 @@ class TestStack extends cdk.Stack {
},
},
}),
grantReportGroupPermissions: false,
/// !show
environment: {
buildImage: codebuild.LinuxBuildImage.fromEcrRepository(ecrRepository, 'v1.0'),
Expand Down
1 change: 1 addition & 0 deletions packages/@aws-cdk/aws-codebuild/test/integ.github.ts
Expand Up @@ -12,6 +12,7 @@ class TestStack extends cdk.Stack {
});
new codebuild.Project(this, 'MyProject', {
source,
grantReportGroupPermissions: false,
});
}
}
Expand Down
Expand Up @@ -19,6 +19,7 @@ new codebuild.Project(stack, 'MyProject', {
environment: {
computeType: codebuild.ComputeType.LARGE,
},
grantReportGroupPermissions: false,
});

app.synth();

0 comments on commit 4befefc

Please sign in to comment.