Search code examples
amazon-web-servicesaws-cdkaws-codepipelineaws-codebuildcicd

How can I reference an existing codebuild project in codepipeline via CDK?


I am using AWS CDK to deploy codepipeline and codebuild. What I am current doing is to create codebuild in one cloudformation stack and reference the codebuild in the codepipeline in a different cf stack.

Below is my code, I create a codebuild action like:

    const action = new actions.CodeBuildAction({
          actionName: "MockEventBridge",
          type: actions.CodeBuildActionType.BUILD,
          input: input,
          project: new codebuild.PipelineProject(this, name, {
            projectName: mockName,
            environment: {
              computeType: codebuild.ComputeType.SMALL,
              buildImage
              privileged: true,
            },
            role,
            buildSpec: codebuild.BuildSpec.fromSourceFilename(
              "cicd/buildspec/mockEventbridge.yaml"
            ),
          }),
          runOrder: 1,
        })
    ...
    const stages = {
      stageName, actions: [action]
    }

once build the action, I use below code to build codepipeline.

new codepipeline.Pipeline(this, name, {
      pipelineName: this.projectName,
      role,
      stages,
      artifactBucket
    });

The problem is that both the codebuild project and codepipeline are built into one stack. If I build the codebuild project in a separate cf stack, how can I reference this stack in codepipeline?

when look at the api reference https://docs.aws.amazon.com/cdk/api/v1/docs/@aws-cdk_aws-codepipeline.Pipeline.html, I can't find a way to reference the codebuild arn in codepipeline instance.


Solution

  • Use the codebuild.Project.fromProjectArn static method to import an external Project resource using its ARN. It returns an IProject, which is what your pipeline's actions.CodeBuildAction props expect.