In AWS CDK, I would like to define a CodeBuild project that will run every time a pull request is opened or updated in CodeCommit. I am doing this to be able to have my tests and build validated prior to merging to the main branch.
How do I have this CodeBuild project run for the branch that is associated with the pull request?
Below is my code:
import { Repository } from 'aws-cdk-lib/aws-codecommit';
import { BuildSpec, Project, Source } from 'aws-cdk-lib/aws-codebuild';
import { CodeBuildProject } from 'aws-cdk-lib/aws-events-targets';
const repo = Repository.fromRepositoryName(this, 'MyRepo', 'my-repo');
const project = new Project(this, 'MyCodeBuildProject', {
source: Source.codeCommit({ repository: repo }),
buildSpec: BuildSpec.fromObject({
version: '0.2',
phases: {
build: {
commands: [ 'npm run build' ],
},
},
}),
});
const myRule = repo.onPullRequestStateChange('MyRule', {
target: new targets.CodeBuildProject(project),
});
I have tried providing it to the project source this way:
import { ReferenceEvent } from 'aws-cdk-lib/aws-codecommit';
...
source: Source.codeCommit({ repository: repo, branchOrRef: ReferenceEvent.name }),
But I receive this error:
reference not found for primary source and source version $.detail.referenceName
CodeCommit -> Open pull request -> CloudWatch event (EventBridge) -> CodeBuild
AWS CDK v2.5.0
TypeScript