Search code examples
typescriptaws-cdkaws-codepipelineaws-codecommit

How to Specify directory to trigger code pipeline cdk?


I am using a cdk code pipeline and i would like to specify for it to only trigger if a directory within the repo has changed.

const pipeline = new CodePipeline(this, 'Pipeline', {
    pipelineName: 'BackEndPipeline',
    synth: new CodeBuildStep('SynthStep', {
        input: CodePipelineSource.codeCommit(repo, 'master'),
        installCommands: [
            'npm install -g aws-cdk'
        ],
        commands: [
            'cd mydir',
            'ls',
            'npm install',
            'ls',
            'npm run build',
            'ls',
            'npx cdk synth'
        ],
        primaryOutputDirectory: 'mydir/cdk.out'
    })
});

Solution

  • It's a DIY job. A CodePipeline is designed to run from start to finish, unconditionally. The trick is to trigger the pipeline only when there has been a relevant change. You must replace the default trigger-on-every-change setup with manual triggering logic. For a CodeCommit repo:

    (1) Turn off the pipeline's automatic trigger. Set the trigger: codepipeline_actions.CodeCommitTrigger.NONE prop in the CodePipelineSource.

    (2) Create an EventBridge Rule to listen to your repo's commit events:

    const rule = new events.Rule(this, 'MyRule', {
      eventPattern: {
        source: ['aws.codecommit'],
        resources: ['arn:aws:codecommit:us-east-1:123456789012:my-repo'],
        detailType: ['CodeCommit Repository State Change'],
      },
    });
    

    (3) Add a Lambda as the rule's target. The Lambda will receive the referenceUpdated payload on a push to your repo. The event payload contains the commitId, but not the changed files. To get the file-level changes, your Lambda should call the GetDifferences API. Your Lambda should then determine whether a relevant change has taken place.

    (4) Manually trigger a pipeline excecution if required. Your Lambda should call the StartPipelineExecution API or set the pipeline as a custom Event target.