如何在 AWS CodeBuild 中设置 AWS CDK 应用程序执行?

How to setup AWS CDK app execution in AWS CodeBuild?

我想 运行 使用 AWS CodeBuild 从 Git 存储库合成 AWS CDK - 即,如果我更新存储库中的 CDK 应用程序代码,我希望 CloudFormation 堆栈自动更新。设置构建角色权限的最佳做法是什么?

对于 GitHub 存储库,您的 CodeBuild 角色不需要额外的权限,但它应该有权访问 oauthToken 以访问 GitHub.

对于 CodeCommit 存储库,创建或 import 一个 codecommit.Repository 对象并为您的 source 参数使用一个 CodeCommitSource 对象,构建角色权限将被设置自动向上(特别是,将添加的权限将从指定的存储库添加到 codecommit:GitPull)。

here

您可能还对 CDK 的 app-delivery 包感兴趣。它不只是创建一个 CodeBuild 项目,它还使用 CodePipeline 来获取、构建和部署 CDK 应用程序,因此它可能比您正在寻找的更多。

AWS 一个月前发布了一个名为 pipelines that includes several utilities to ease the job of setting up self modifying pipelines. In addition, there's codepipeline-actions 的 CDK 套件的新 class,其中包括将您的管道挂接到 CodeCommit、GitHub、BitBucket 等的结构...

这是一个完整的 example(来自链接博客 post 的逐字记录),使用 github 作为源,通过 CodePipeline 部署 lambda:

用你的堆栈创建一个舞台

import { CfnOutput, Construct, Stage, StageProps } from '@aws-cdk/core';
import { CdkpipelinesDemoStack } from './cdkpipelines-demo-stack';

/**
 * Deployable unit of web service app
 */
export class CdkpipelinesDemoStage extends Stage {
  public readonly urlOutput: CfnOutput;
  
  constructor(scope: Construct, id: string, props?: StageProps) {
    super(scope, id, props);

    const service = new CdkpipelinesDemoStack(this, 'WebService');
    
    // Expose CdkpipelinesDemoStack's output one level higher
    this.urlOutput = service.urlOutput;
  }
}

使用您的管道创建堆栈

import * as codepipeline from '@aws-cdk/aws-codepipeline';
import * as codepipeline_actions from '@aws-cdk/aws-codepipeline-actions';
import { Construct, SecretValue, Stack, StackProps } from '@aws-cdk/core';
import { CdkPipeline, SimpleSynthAction } from "@aws-cdk/pipelines";

/**
 * The stack that defines the application pipeline
 */
export class CdkpipelinesDemoPipelineStack extends Stack {
  constructor(scope: Construct, id: string, props?: StackProps) {
    super(scope, id, props);

    const sourceArtifact = new codepipeline.Artifact();
    const cloudAssemblyArtifact = new codepipeline.Artifact();
 
    const pipeline = new CdkPipeline(this, 'Pipeline', {
      // The pipeline name
      pipelineName: 'MyServicePipeline',
      cloudAssemblyArtifact,

      // Where the source can be found
      sourceAction: new codepipeline_actions.GitHubSourceAction({
        actionName: 'GitHub',
        output: sourceArtifact,
        oauthToken: SecretValue.secretsManager('github-token'),
        owner: 'OWNER',
        repo: 'REPO',
      }),

       // How it will be built and synthesized
       synthAction: SimpleSynthAction.standardNpmSynth({
         sourceArtifact,
         cloudAssemblyArtifact,
         
         // We need a build step to compile the TypeScript Lambda
         buildCommand: 'npm run build'
       }),
    });

    // This is where we add the application stages
    // ...
  }
}