@aws-cdk/aws-codepipeline-actions

中文文档
1.204.0发布于 2023/06/20Apache-2.0TypeScriptCommonJS近 30 天下载 7.1万

AWS 代码管道的具体行动

此软件包已被标记为弃用

AWS CDK v1 has reached End-of-Support on 2023-06-01. This package is no longer being updated, and users should migrate to AWS CDK v2. For more information on how to migrate, see https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html

中文使用文档
文档目录20 节
  1. 来源
  2. AWS 代码承诺
  3. GitHub 图像
  4. 键盘
  5. AWS S3 来源
  6. AWS 电子记录
  7. 构建测试( T)
  8. AWS 代码构建
  9. 詹金斯(英语:
  10. 部署
  11. AWS 云阵
  12. AWS 代码部署
  13. 东加勒比国家
  14. AWS S3 部署
  15. 亚历克萨·斯克特
  16. AWS 服务目录
  17. 批准引用( T)
  18. 人工核准行动
  19. AWS 兰布达
  20. AWS 步函数

AWS 代码管道动作


End-of-Support

AWS CDK v1在2023-06-01上达到了支持结束. 此软件包不再更新,用户应该迁移到 AWS CDK v2.

关于如何移徙的更多信息,请参见: 移动到 AWS CDK v2 指南。 。 。 .


此套件包含可以在代码Pipeline中使用的动作.

import * as codepipeline from '@aws-cdk/aws-codepipeline';
import * as codepipeline_actions from '@aws-cdk/aws-codepipeline-actions';

来源

AWS 代码承诺

在代码平线中使用代码承诺存储器 :

const repo = new codecommit.Repository(this, 'Repo', {
  repositoryName: 'MyRepo',
});

const pipeline = new codepipeline.Pipeline(this, 'MyPipeline', {
  pipelineName: 'MyPipeline',
});
const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.CodeCommitSourceAction({
  actionName: 'CodeCommit',
  repository: repo,
  output: sourceOutput,
});
pipeline.addStage({
  stageName: 'Source',
  actions: [sourceAction],
});

如果您想要使用现有角色, 该角色可用于执行事件规则 . 您可以在事件Role属性中指定角色对象 .

const eventRole = iam.Role.fromRoleArn(this, 'Event-role', 'roleArn');
declare const repo: codecommit.Repository;
const sourceAction = new codepipeline_actions.CodeCommitSourceAction({
  actionName: 'CodeCommit',
  repository: repo,
  output: new codepipeline.Artifact(),
  eventRole,
});

如果您想要克隆整个代码承诺寄存器( 仅可用于代码构建动作) , 您可以设置 codeBuildCloneOutput 属性改为 true数字 :

declare const project: codebuild.PipelineProject;
declare const repo: codecommit.Repository;
const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.CodeCommitSourceAction({
  actionName: 'CodeCommit',
  repository: repo,
  output: sourceOutput,
  codeBuildCloneOutput: true,
});

const buildAction = new codepipeline_actions.CodeBuildAction({
  actionName: 'CodeBuild',
  project,
  input: sourceOutput, // The build action must use the CodeCommitSourceAction output as input.
  outputs: [new codepipeline.Artifact()], // optional
});

代码承诺源动作释放出变量 :

declare const project: codebuild.PipelineProject;
declare const repo: codecommit.Repository;
const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.CodeCommitSourceAction({
  actionName: 'CodeCommit',
  repository: repo,
  output: sourceOutput,
  variablesNamespace: 'MyNamespace', // optional - by default, a name will be generated for you
});

// later:

new codepipeline_actions.CodeBuildAction({
  actionName: 'CodeBuild',
  project,
  input: sourceOutput,
  environmentVariables: {
    COMMIT_ID: {
      value: sourceAction.variables.commitId,
    },
  },
});

GitHub 图像

如果您想要使用 GitHub 仓库作为源代码, 您必须创建 :

  • A 类 GitHub 访问托肯, (中文(简体) ), 有范围 还原 财务报告和审定财务报表 管理员:repo hook。 。 。 .
  • A 类 保密管理器 带有 GitHub 访问托肯。选择您想要的名称(例如) my-github-token) (中文(简体) ). 此令牌既可以作为 Plaintext 存储,也可以作为密钥/值存储. 如果你把信物作为普通文字保存, 设定 SecretValue.secretsManager('my-github-token') 作为 oauthToken。 。 。 . 如果你把它作为密钥/值存储, 您必须设置 SecretValue.secretsManager('my-github-token', { jsonField : 'my-github-token' }) 作为 oauthToken。 。 。 .

要使用 GitHub 作为代码Pipeline 的来源 :

// Read the secret from Secrets Manager
const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.GitHubSourceAction({
  actionName: 'GitHub_Source',
  owner: 'awslabs',
  repo: 'aws-cdk',
  oauthToken: SecretValue.secretsManager('my-github-token'),
  output: sourceOutput,
  branch: 'develop', // default: 'master'
});
pipeline.addStage({
  stageName: 'Source',
  actions: [sourceAction],
});

GitHub 源动作释放出变量 :

declare const sourceOutput: codepipeline.Artifact;
declare const project: codebuild.PipelineProject;

const sourceAction = new codepipeline_actions.GitHubSourceAction({
  actionName: 'Github_Source',
  output: sourceOutput,
  owner: 'my-owner',
  repo: 'my-repo',
  oauthToken: SecretValue.secretsManager('my-github-token'),
  variablesNamespace: 'MyNamespace', // optional - by default, a name will be generated for you
});

// later:

new codepipeline_actions.CodeBuildAction({
  actionName: 'CodeBuild',
  project,
  input: sourceOutput,
  environmentVariables: {
    COMMIT_URL: {
      value: sourceAction.variables.commitUrl,
    },
  },
});

键盘

CodePipeline 可以使用 BitBucket Git 寄存器作为来源 :

说明:您必须手动通过 AWS 控制台将代码Pipeline 连接到您的 BitBucket 账户 . 这是针对特定区域特定AWS账户的一次性操作. 最简单的方法是要么开始创造出一个新的代码Pipeline, 或编辑已有的,同时登录到 BitBucket. 选择 BitBucket 作为源代码, 并给予您的 BitBucket 账户代码Pipeline 权限 . 复制并粘贴您在控制台中的连接 ARN, 或使用 codestar-connections list-connections AWS CLI 操作 为了找到它. 之后,您可以安全地中止创建或编辑管道 - 连接已经创建 .

const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.CodeStarConnectionsSourceAction({
  actionName: 'BitBucket_Source',
  owner: 'aws',
  repo: 'aws-cdk',
  output: sourceOutput,
  connectionArn: 'arn:aws:codestar-connections:us-east-1:123456789012:connection/12345678-abcd-12ab-34cdef5678gh',
});

你也可以使用这个 CodeStarConnectionsSourceAction 连接到 GitHub, 方式相同 (你只需要在控制台创建连接时选择 GitHub 作为源).

与 GitHubSourceAction, (中文(简体) ), CodeStarConnectionsSourceAction 还发出变量:

declare const project: codebuild.Project;

const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.CodeStarConnectionsSourceAction({
  actionName: 'BitBucket_Source',
  owner: 'aws',
  repo: 'aws-cdk',
  output: sourceOutput,
  connectionArn: 'arn:aws:codestar-connections:us-east-1:123456789012:connection/12345678-abcd-12ab-34cdef5678gh',
  variablesNamespace: 'SomeSpace', // optional - by default, a name will be generated for you
});

// later:

new codepipeline_actions.CodeBuildAction({
  actionName: 'CodeBuild',
  project,
  input: sourceOutput,
  environmentVariables: {
    COMMIT_ID: {
      value: sourceAction.variables.commitId,
    },
  },
});

AWS S3 来源

在 CodePipeline 中使用 S3 Bucket 作为源代码 :

const sourceBucket = new s3.Bucket(this, 'MyBucket', {
  versioned: true, // a Bucket used as a source in CodePipeline must be versioned
});

const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.S3SourceAction({
  actionName: 'S3Source',
  bucket: sourceBucket,
  bucketKey: 'path/to/file.zip',
  output: sourceOutput,
});
pipeline.addStage({
  stageName: 'Source',
  actions: [sourceAction],
});

行动区域将由桶本身所在的区域决定. 当使用一个新建的桶, 该区域将被取出该桶所属的堆栈; 为进口桶, 您可以明确指定区域:

const sourceBucket = s3.Bucket.fromBucketAttributes(this, 'SourceBucket', {
  bucketName: 'my-bucket',
  region: 'ap-southeast-1',
});

默认情况下,管子会向巴克特进行投票,以检测变化. 您可以通过设置 trigger 属性改为 S3Trigger.EVENTS (这是 S3Trigger.POLL (默认情况下). 如果你这样做,确保源 Bucket 是AWS CloudTrail轨迹的一部分 - 否则,《云表》是不会发行的, 而您的管道不会对 Bucket 的变化作出反应 . 你可以通过CDK:

import * as cloudtrail from '@aws-cdk/aws-cloudtrail';

declare const sourceBucket: s3.Bucket;
const sourceOutput = new codepipeline.Artifact();
const key = 'some/key.zip';
const trail = new cloudtrail.Trail(this, 'CloudTrail');
trail.addS3EventSelector([{
  bucket: sourceBucket,
  objectPrefix: key,
}], {
  readWriteType: cloudtrail.ReadWriteType.WRITE_ONLY,
});
const sourceAction = new codepipeline_actions.S3SourceAction({
  actionName: 'S3Source',
  bucketKey: key,
  bucket: sourceBucket,
  output: sourceOutput,
  trigger: codepipeline_actions.S3Trigger.EVENTS, // default: S3Trigger.POLL
});

S3源动作释放出变量:

const key = 'some/key.zip';
declare const sourceBucket: s3.Bucket;
const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.S3SourceAction({
  actionName: 'S3Source',
  bucketKey: key,
  bucket: sourceBucket,
  output: sourceOutput,
  variablesNamespace: 'MyNamespace', // optional - by default, a name will be generated for you
});

// later:
declare const project: codebuild.PipelineProject;
new codepipeline_actions.CodeBuildAction({
  actionName: 'CodeBuild',
  project,
  input: sourceOutput,
  environmentVariables: {
    VERSION_ID: {
      value: sourceAction.variables.versionId,
    },
  },
});

AWS 电子记录

使用 ECR 存储器作为管道中的源 :

import * as ecr from '@aws-cdk/aws-ecr';

declare const ecrRepository: ecr.Repository;
const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.EcrSourceAction({
  actionName: 'ECR',
  repository: ecrRepository,
  imageTag: 'some-tag', // optional, default: 'latest'
  output: sourceOutput,
});
pipeline.addStage({
  stageName: 'Source',
  actions: [sourceAction],
});

ECR 源动作释放出变量 :

import * as ecr from '@aws-cdk/aws-ecr';

const sourceOutput = new codepipeline.Artifact();
declare const ecrRepository: ecr.Repository;
const sourceAction = new codepipeline_actions.EcrSourceAction({
  actionName: 'Source',
  output: sourceOutput,
  repository: ecrRepository,
  variablesNamespace: 'MyNamespace', // optional - by default, a name will be generated for you
});

// later:
declare const project: codebuild.PipelineProject;
new codepipeline_actions.CodeBuildAction({
  actionName: 'CodeBuild',
  project,
  input: sourceOutput,
  environmentVariables: {
    IMAGE_URI: {
      value: sourceAction.variables.imageUri,
    },
  },
});

构建测试( T)

AWS 代码构建

管道中使用的编码构建项目示例,与编码承诺:

declare const project: codebuild.PipelineProject;
const repository = new codecommit.Repository(this, 'MyRepository', {
  repositoryName: 'MyRepository',
});
const project = new codebuild.PipelineProject(this, 'MyProject');

const sourceOutput = new codepipeline.Artifact();
const sourceAction = new codepipeline_actions.CodeCommitSourceAction({
  actionName: 'CodeCommit',
  repository,
  output: sourceOutput,
});
const buildAction = new codepipeline_actions.CodeBuildAction({
  actionName: 'CodeBuild',
  project,
  input: sourceOutput,
  outputs: [new codepipeline.Artifact()], // optional
  executeBatchBuild: true, // optional, defaults to false
  combineBatchBuildArtifacts: true, // optional, defaults to false
});

new codepipeline.Pipeline(this, 'MyPipeline', {
  stages: [
    {
      stageName: 'Source',
      actions: [sourceAction],
    },
    {
      stageName: 'Build',
      actions: [buildAction],
    },
  ],
});

代码构建动作的默认类别是 Build· ; 如果你想要一个 Test 而是行动, 覆盖 type 属性 :

declare const project: codebuild.PipelineProject;
const sourceOutput = new codepipeline.Artifact();
const testAction = new codepipeline_actions.CodeBuildAction({
  actionName: 'IntegrationTest',
  project,
  input: sourceOutput,
  type: codepipeline_actions.CodeBuildActionType.TEST, // default is BUILD
});

多种投入和产出

当您想要在项目中使用多种投入和/或产出时 管道,而不是使用 secondarySources 财务报告和审定财务报表 secondaryArtifacts 属性 Project 类,需要使用 extraInputs 财务报告和审定财务报表 outputs 密码的属性 行动 示例

declare const repository1: codecommit.Repository;
const sourceOutput1 = new codepipeline.Artifact();
const sourceAction1 = new codepipeline_actions.CodeCommitSourceAction({
  actionName: 'Source1',
  repository: repository1,
  output: sourceOutput1,
});
declare const repository2: codecommit.Repository;
const sourceOutput2 = new codepipeline.Artifact('source2');
const sourceAction2 = new codepipeline_actions.CodeCommitSourceAction({
  actionName: 'Source2',
  repository: repository2,
  output: sourceOutput2,
});

declare const project: codebuild.PipelineProject;
const buildAction = new codepipeline_actions.CodeBuildAction({
  actionName: 'Build',
  project,
  input: sourceOutput1,
  extraInputs: [
    sourceOutput2, // this is where 'source2' comes from
  ],
  outputs: [
    new codepipeline.Artifact('artifact1'), // for better buildspec readability - see below
    new codepipeline.Artifact('artifact2'),
  ],
});

说明: 当管道中的代码构建动作有多个输出时, 它 仅使用 secondary-artifacts 区域 主要产出规格直接置于下 artifacts. 因为,它 像我们所做的那样 给行动的所有产出都起名 上方,以便您知道建筑图中使用的名称.

上述项目的示例构建

const project = new codebuild.PipelineProject(this, 'MyProject', {
  buildSpec: codebuild.BuildSpec.fromObject({
    version: '0.2',
    phases: {
      build: {
        commands: [
          // By default, you're in a directory with the contents of the repository from sourceAction1.
          // Use the CODEBUILD_SRC_DIR_source2 environment variable
          // to get a path to the directory with the contents of the second input repository.
        ],
      },
    },
    artifacts: {
      'secondary-artifacts': {
        'artifact1': {
          // primary Action output artifact,
          // available as buildAction.outputArtifact
        },
        'artifact2': {
          // additional output artifact,
          // available as buildAction.additionalOutputArtifact('artifact2')
        },
      },
    },
  }),
  // ...
});

变量

代码构建动作释放出变量 . 与许多其他动作不同,变量不是静止的, 但动态,定义在构建范围, 在“env”部分的“可导变量”小节中. 示例

const sourceOutput = new codepipeline.Artifact();
const buildAction = new codepipeline_actions.CodeBuildAction({
  actionName: 'Build1',
  input: sourceOutput,
  project: new codebuild.PipelineProject(this, 'Project', {
    buildSpec: codebuild.BuildSpec.fromObject({
      version: '0.2',
      env: {
        'exported-variables': [
          'MY_VAR',
        ],
      },
      phases: {
        build: {
          commands: 'export MY_VAR="some value"',
        },
      },
    }),
  }),
  variablesNamespace: 'MyNamespace', // optional - by default, a name will be generated for you
});

// later:
declare const project: codebuild.PipelineProject;
new codepipeline_actions.CodeBuildAction({
  actionName: 'CodeBuild',
  project,
  input: sourceOutput,
  environmentVariables: {
    MyVar: {
      value: buildAction.variable('MY_VAR'),
    },
  },
});

詹金斯(英语:

为了在管道中使用詹金斯动作, 您首先需要创建 JenkinsProvider数字 :

const jenkinsProvider = new codepipeline_actions.JenkinsProvider(this, 'JenkinsProvider', {
  providerName: 'MyJenkinsProvider',
  serverUrl: 'http://my-jenkins.com:8080',
  version: '2', // optional, default: '1'
});

如果你已经注册了詹金斯供应商 在不同的CDK应用程序, 或CDK之外(例如代码Pipeline AWS控制台), 您可以导入它 :

const jenkinsProvider = codepipeline_actions.JenkinsProvider.fromJenkinsProviderAttributes(this, 'JenkinsProvider', {
  providerName: 'MyJenkinsProvider',
  serverUrl: 'http://my-jenkins.com:8080',
  version: '2', // optional, default: '1'
});

请注意Jenkins供应商 (由供应商名称类别-(建设/测试)-版本tuple所识别) 必须在给定的账户中登记,在给定的AWS区域, 在代码Pipeline中使用之前.

与一个 JenkinsProvider, (中文(简体) ), 我们可以创建一个詹金斯行动:

declare const jenkinsProvider: codepipeline_actions.JenkinsProvider;
const buildAction = new codepipeline_actions.JenkinsAction({
  actionName: 'JenkinsBuild',
  jenkinsProvider: jenkinsProvider,
  projectName: 'MyProject',
  type: codepipeline_actions.JenkinsActionType.BUILD,
});

部署

AWS 云阵

此模块包含动作,允许您从 AWS 代码Pipeline 部署到 CloudFormation .

例如,以下代码片段定义了自动部署 Cloud Formation 模板的管道 直接取自 CodeCommit 寄存器, 并使用人工批准步骤在两者之间确认更改 :

用于部署 Cloud Formation 的管道示例

见 aWS 文档 更多关于使用 Cloud Formation 在代码Pipeline 中的细节.

更新单个云格式堆栈的行动

此套件包含以下 Cloud Formation 动作 :

  • 创建更新状态 - 直接从输油管里部署一个云阵模板。 显示的堆栈是创建的, 或已更新。 如果堆栈处于失败状态,部署将失败(除非 replaceOnFailure 设置为 true,在此情况下,它将被销毁并被再造.
  • 云格式删除程序 - 删除带有给定名称的堆栈.
  • 云阵生成重置变换动作 - 准备一套更改,待日后适用。 如果您愿意, 通常会使用更改集 手动核实正在进行的修改,或者如果你想将准备修改的人群(或系统)分开 由应用这些变化的人(或系统)进行更改.
  • 云阵执行变化动作 - 执行先前准备的更改.

将 CloudFormation StackSets 部署到多个账户的行动

您可以使用 CloudFormation StackSets 将相同的 CloudFormation 模板部署到多个 账户的管理方式。 如果您使用 AWS 组织, StackSets 可以部署到 某个组织单位的所有账户,甚至自动转入新账户 账户一旦添加到特定的OU。 更多信息见 页:1 使用 StackSets 工作 cloudFormation开发者指南的一节.

可用于更新StackSets的行动有:

  • 云阵部署组合行动 - 从管道直接创建或更新 Cloud Formation StackSet, 可选 立即创建并更新 Stack Events .
  • 云阵部署 使用 StackSet 的当前版本更新已过时的 Stack Instaces .

以下是使用这两种动作的例子:

declare const pipeline: codepipeline.Pipeline;
declare const sourceOutput: codepipeline.Artifact;

pipeline.addStage({
  stageName: 'DeployStackSets',
  actions: [
    // First, update the StackSet itself with the newest template
    new codepipeline_actions.CloudFormationDeployStackSetAction({
      actionName: 'UpdateStackSet',
      runOrder: 1,
      stackSetName: 'MyStackSet',
      template: codepipeline_actions.StackSetTemplate.fromArtifactPath(sourceOutput.atPath('template.yaml')),

      // Change this to 'StackSetDeploymentModel.organizations()' if you want to deploy to OUs
      deploymentModel: codepipeline_actions.StackSetDeploymentModel.selfManaged(),
      // This deploys to a set of accounts
      stackInstances: codepipeline_actions.StackInstances.inAccounts(['111111111111'], ['us-east-1', 'eu-west-1']),
    }),

    // Afterwards, update/create additional instances in other accounts
    new codepipeline_actions.CloudFormationDeployStackInstancesAction({
      actionName: 'AddMoreInstances',
      runOrder: 2,
      stackSetName: 'MyStackSet',
      stackInstances: codepipeline_actions.StackInstances.inAccounts(
        ['222222222222', '333333333333'],
        ['us-east-1', 'eu-west-1']
      ),
    }),
  ],
});

通过代号Pipeline部署的Lambda

如果你想通过CodePipeline 部署你的Lambda, 而你不使用资产(例如,因为你的CDK代码和Lambda代码是分开的), 你可以使用一个特殊的蓝巴达 Code 班级, CfnParametersCode。 。 。 . 请注意,你的蓝巴达 一定在一个不同的堆叠 比你的管道. Lambda号本身将部署,连同它所属的整个Stack, 使用 CloudFormation 代码平线动作。 示例

通过 CodePipeline 部署兰布达的例子

交叉账户行动

如果你想在另一个账户中更新堆栈, 通过 account 创建动作时的属性 :

const sourceOutput = new codepipeline.Artifact();
new codepipeline_actions.CloudFormationCreateUpdateStackAction({
  actionName: 'CloudFormationCreateUpdate',
  stackName: 'MyStackName',
  adminPermissions: true,
  templatePath: sourceOutput.atPath('template.yaml'),
  account: '123456789012',
});

这将创建一个新堆栈,叫做 <PipelineStackName>-support-123456789012,则在您的 App, (中文(简体) ), 它将包含管道在执行这一行动之前将在123456789012号帐户中发挥的作用. 此支持堆栈会自动被部署在包含管道的堆栈之前.

您也可以在创建动作时明确传递一个角色 - 在这种情况下 account 财产被忽略, 动作将在同一账户中操作,该角色属于:

import { PhysicalName } from '@aws-cdk/core';

// in stack for account 123456789012...
declare const otherAccountStack: Stack;
const actionRole = new iam.Role(otherAccountStack, 'ActionRole', {
  assumedBy: new iam.AccountPrincipal('123456789012'),
  // the role has to have a physical name set
  roleName: PhysicalName.GENERATE_IF_NEEDED,
});

// in the pipeline stack...
const sourceOutput = new codepipeline.Artifact();
new codepipeline_actions.CloudFormationCreateUpdateStackAction({
  actionName: 'CloudFormationCreateUpdate',
  stackName: 'MyStackName',
  adminPermissions: true,
  templatePath: sourceOutput.atPath('template.yaml'),
  role: actionRole, // this action will be cross-account as well
});

AWS 代码部署

服务器部署

在管道中使用代码部署 EC2/ 配置:

const pipeline = new codepipeline.Pipeline(this, 'MyPipeline', {
  pipelineName: 'MyPipeline',
});

// add the source and build Stages to the Pipeline...
const buildOutput = new codepipeline.Artifact();
declare const deploymentGroup: codedeploy.ServerDeploymentGroup;
const deployAction = new codepipeline_actions.CodeDeployServerDeployAction({
  actionName: 'CodeDeploy',
  input: buildOutput,
  deploymentGroup,
});
pipeline.addStage({
  stageName: 'Deploy',
  actions: [deployAction],
});
兰布达部署

在管道中部署蓝绿色的Lambda:

const lambdaCode = lambda.Code.fromCfnParameters();
const func = new lambda.Function(this, 'Lambda', {
  code: lambdaCode,
  handler: 'index.handler',
  runtime: lambda.Runtime.NODEJS_14_X,
});
// used to make sure each CDK synthesis produces a different Version
const version = func.currentVersion;
const alias = new lambda.Alias(this, 'LambdaAlias', {
  aliasName: 'Prod',
  version,
});

new codedeploy.LambdaDeploymentGroup(this, 'DeploymentGroup', {
  alias,
  deploymentConfig: codedeploy.LambdaDeploymentConfig.LINEAR_10PERCENT_EVERY_1MINUTE,
});

然后,你需要创建你的管道堆栈, 你将在那里定义你的管道, 部署 lambdaStack 使用 CloudFormation 代码 (完整的事例见上文).

东加勒比国家

CodePipeline可以部署ECS服务. 动作收到一个输入,其中包含 图像定义文件数字 :

import * as ecs from '@aws-cdk/aws-ecs';

declare const service: ecs.FargateService;
const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const buildOutput = new codepipeline.Artifact();
const deployStage = pipeline.addStage({
  stageName: 'Deploy',
  actions: [
    new codepipeline_actions.EcsDeployAction({
      actionName: 'DeployAction',
      service,
      // if your file is called imagedefinitions.json,
      // use the `input` property,
      // and leave out the `imageFile` property
      input: buildOutput,
      // if your file name is _not_ imagedefinitions.json,
      // use the `imageFile` property,
      // and leave out the `input` property
      imageFile: buildOutput.atPath('imageDef.json'),
      deploymentTimeout: Duration.minutes(60), // optional, default is 60 minutes
    }),
  ],
});

在现有服务中部署ECS应用程序

CodePipeline可以被部署到一个现有的ECS服务中,它使用 包含集群名称的 ECS 服务 ARN 格式。 。 。 . 如果服务处在与管道不同的账户和/或区域,这种服务也会起作用:

import * as ecs from '@aws-cdk/aws-ecs';

const service = ecs.BaseService.fromServiceArnWithCluster(this, 'EcsService',
  'arn:aws:ecs:us-east-1:123456789012:service/myClusterName/myServiceName'
);
const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const buildOutput = new codepipeline.Artifact();
// add source and build stages to the pipeline as usual...
const deployStage = pipeline.addStage({
  stageName: 'Deploy',
  actions: [
    new codepipeline_actions.EcsDeployAction({
      actionName: 'DeployAction',
      service: service,
      input: buildOutput,
    }),
  ],
});

当部署跨账户,特别是CDK管道自制管道时, 建议提供 role 属性 EcsDeployAction。 。 。 . 该角色需要获得部署ECS的许可. 见 密码平线文档 需要的许可.

部署存储在单独源代码存储库中的ECS应用程序

部署 ECS 应用程序的平庸的 CDK 方式是将您的 Docker 文件 和您的 CDK 代码放在同一源代码寄存器中, 杠杆作用 Docker 资产, (中文(简体) ), 并使用 CDK 管道模块。 。 。 .

然而,如果您想要部署一个Docker应用程序,其源代码保存在一个单独的版本控制存储器中,而不是CDK代码, 您可以使用 TagParameterContainerImage 来自ECS模块的课. 举个例子:

单独源代码存储器中应用程序的ECS 管道

AWS S3 部署

在 CodePipeline 中使用 S3 Bucket 作为部署目标 :

const sourceOutput = new codepipeline.Artifact();
const targetBucket = new s3.Bucket(this, 'MyBucket');

const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const deployAction = new codepipeline_actions.S3DeployAction({
  actionName: 'S3Deploy',
  bucket: targetBucket,
  input: sourceOutput,
});
const deployStage = pipeline.addStage({
  stageName: 'Deploy',
  actions: [deployAction],
});

向 S3 部署时将 CloudFront 缓存无效

目前CodePipeline中没有本地支持在部署后无效CloudFront缓存. 一个工作是在部署步骤之后再加一步, 并使用 AWS CLI 使缓存无效 :

// Create a Cloudfront Web Distribution
import * as cloudfront from '@aws-cdk/aws-cloudfront';
declare const distribution: cloudfront.Distribution;

// Create the build project that will invalidate the cache
const invalidateBuildProject = new codebuild.PipelineProject(this, `InvalidateProject`, {
  buildSpec: codebuild.BuildSpec.fromObject({
    version: '0.2',
    phases: {
      build: {
        commands:[
          'aws cloudfront create-invalidation --distribution-id ${CLOUDFRONT_ID} --paths "/*"',
          // Choose whatever files or paths you'd like, or all files as specified here
        ],
      },
    },
  }),
  environmentVariables: {
    CLOUDFRONT_ID: { value: distribution.distributionId },
  },
});

// Add Cloudfront invalidation permissions to the project
const distributionArn = `arn:aws:cloudfront::${this.account}:distribution/${distribution.distributionId}`;
invalidateBuildProject.addToRolePolicy(new iam.PolicyStatement({
  resources: [distributionArn],
  actions: [
    'cloudfront:CreateInvalidation',
  ],
}));

// Create the pipeline (here only the S3 deploy and Invalidate cache build)
const deployBucket = new s3.Bucket(this, 'DeployBucket');
const deployInput = new codepipeline.Artifact();
new codepipeline.Pipeline(this, 'Pipeline', {
  stages: [
    // ...
    {
      stageName: 'Deploy',
      actions: [
        new codepipeline_actions.S3DeployAction({
          actionName: 'S3Deploy',
          bucket: deployBucket,
          input: deployInput,
          runOrder: 1,
        }),
        new codepipeline_actions.CodeBuildAction({
          actionName: 'InvalidateCache',
          project: invalidateBuildProject,
          input: deployInput,
          runOrder: 2,
        }),
      ],
    },
  ],
});

亚历克萨·斯克特

您可以使用 CodePipeline 向 Alexa 部署以下动作:

// Read the secrets from ParameterStore
const clientId = SecretValue.secretsManager('AlexaClientId');
const clientSecret = SecretValue.secretsManager('AlexaClientSecret');
const refreshToken = SecretValue.secretsManager('AlexaRefreshToken');

// Add deploy action
const sourceOutput = new codepipeline.Artifact();
new codepipeline_actions.AlexaSkillDeployAction({
  actionName: 'DeploySkill',
  runOrder: 1,
  input: sourceOutput,
  clientId: clientId.toString(),
  clientSecret: clientSecret,
  refreshToken: refreshToken,
  skillId: 'amzn1.ask.skill.12345678-1234-1234-1234-123456789012',
});

如果您需要显示的覆盖, 您可以指定为 parameterOverridesArtifact 在行动中:

// Deploy some CFN change set and store output
const executeOutput = new codepipeline.Artifact('CloudFormation');
const executeChangeSetAction = new codepipeline_actions.CloudFormationExecuteChangeSetAction({
  actionName: 'ExecuteChangesTest',
  runOrder: 2,
  stackName: 'MyStack',
  changeSetName: 'MyChangeSet',
  outputFileName: 'overrides.json',
  output: executeOutput,
});

// Provide CFN output as manifest overrides
const clientId = SecretValue.secretsManager('AlexaClientId');
const clientSecret = SecretValue.secretsManager('AlexaClientSecret');
const refreshToken = SecretValue.secretsManager('AlexaRefreshToken');
const sourceOutput = new codepipeline.Artifact();
new codepipeline_actions.AlexaSkillDeployAction({
  actionName: 'DeploySkill',
  runOrder: 1,
  input: sourceOutput,
  parameterOverridesArtifact: executeOutput,
  clientId: clientId.toString(),
  clientSecret: clientSecret,
  refreshToken: refreshToken,
  skillId: 'amzn1.ask.skill.12345678-1234-1234-1234-123456789012',
});

AWS 服务目录

您可以将 CloudFormation 模板部署到现有的服务目录产品中,并附带以下动作:

const cdkBuildOutput = new codepipeline.Artifact();
const serviceCatalogDeployAction = new codepipeline_actions.ServiceCatalogDeployActionBeta1({
  actionName: 'ServiceCatalogDeploy',
  templatePath: cdkBuildOutput.atPath("Sample.template.json"),
  productVersionName: "Version - " + Date.now.toString,
  productVersionDescription: "This is a version from the pipeline with a new description.",
  productId: "prod-XXXXXXXX",
});

批准引用( T)

人工核准行动

此套件包含一个动作, 在有人手动点击批准按钮前停止管道:

import * as sns from '@aws-cdk/aws-sns';

const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const approveStage = pipeline.addStage({ stageName: 'Approve' });
const manualApprovalAction = new codepipeline_actions.ManualApprovalAction({
  actionName: 'Approve',
  notificationTopic: new sns.Topic(this, 'Topic'), // optional
  notifyEmails: [
    '[email protected]',
  ], // optional
  additionalInformation: 'additional info', // optional
});
approveStage.addAction(manualApprovalAction);
// `manualApprovalAction.notificationTopic` can be used to access the Topic
// after the Action has been added to a Pipeline

如果 notificationTopic 未提供, 不过 notifyEmails 当时, 将创建一个新的 SNS 专题 (并且可通过 notificationTopic 页:1.

如果您想获得批准修改的主要许可, 您可以引用该方法 grantManualApproval 传过来 IGrantable数字 :

const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const approveStage = pipeline.addStage({ stageName: 'Approve' });
const manualApprovalAction = new codepipeline_actions.ManualApprovalAction({
  actionName: 'Approve',
});
approveStage.addAction(manualApprovalAction);

const role = iam.Role.fromRoleArn(this, 'Admin', Arn.format({ service: 'iam', resource: 'role', resourceName: 'Admin' }, this));
manualApprovalAction.grantManualApproval(role);

AWS 兰布达

此模块包含一个动作, 允许您在管道中引用 Lambda 函数 :

declare const fn: lambda.Function;
const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const lambdaAction = new codepipeline_actions.LambdaInvokeAction({
  actionName: 'Lambda',
  lambda: fn,
});
pipeline.addStage({
  stageName: 'Lambda',
  actions: [lambdaAction],
});

Lambda行动最多可以有5个投入, 最多5个产出:

declare const fn: lambda.Function;
const sourceOutput = new codepipeline.Artifact();
const buildOutput = new codepipeline.Artifact();
const lambdaAction = new codepipeline_actions.LambdaInvokeAction({
  actionName: 'Lambda',
  inputs: [
    sourceOutput,
    buildOutput,
  ],
  outputs: [
    new codepipeline.Artifact('Out1'),
    new codepipeline.Artifact('Out2'),
  ],
  lambda: fn,
});

Lambda Action 支持自定义用户参数进行管道 将传递给 Lambda 函数 :

declare const fn: lambda.Function;

const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const lambdaAction = new codepipeline_actions.LambdaInvokeAction({
  actionName: 'Lambda',
  lambda: fn,
  userParameters: {
    foo: 'bar',
    baz: 'qux',
  },
  // OR
  userParametersString: 'my-parameter-string',
});

Lambda 引用动作的变量 . 与许多其他动作不同,变量不是静止的, 但是动态,由名为 PutJobSuccessResult API 随同 outputVariables 包含变量图的属性 示例

const lambdaInvokeAction = new codepipeline_actions.LambdaInvokeAction({
  actionName: 'Lambda',
  lambda: new lambda.Function(this, 'Func', {
    runtime: lambda.Runtime.NODEJS_14_X,
    handler: 'index.handler',
    code: lambda.Code.fromInline(`
        const AWS = require('aws-sdk');

        exports.handler = async function(event, context) {
            const codepipeline = new AWS.CodePipeline();
            await codepipeline.putJobSuccessResult({
                jobId: event['CodePipeline.job'].id,
                outputVariables: {
                    MY_VAR: "some value",
                },
            }).promise();
        }
    `),
  }),
  variablesNamespace: 'MyNamespace', // optional - by default, a name will be generated for you
});

// later:
declare const project: codebuild.PipelineProject;
const sourceOutput = new codepipeline.Artifact();
new codepipeline_actions.CodeBuildAction({
  actionName: 'CodeBuild',
  project,
  input: sourceOutput,
  environmentVariables: {
    MyVar: {
      value: lambdaInvokeAction.variable('MY_VAR'),
    },
  },
});

见 aWS 文档 如何写出来自 CodePipeline 的 Lambda 函数.

AWS 步函数

此模块包含一个动作, 允许您在管道中引用步骤函数 :

import * as stepfunctions from '@aws-cdk/aws-stepfunctions';
const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const startState = new stepfunctions.Pass(this, 'StartState');
const simpleStateMachine  = new stepfunctions.StateMachine(this, 'SimpleStateMachine', {
  definition: startState,
});
const stepFunctionAction = new codepipeline_actions.StepFunctionInvokeAction({
  actionName: 'Invoke',
  stateMachine: simpleStateMachine,
  stateMachineInput: codepipeline_actions.StateMachineInput.literal({ IsHelloWorldExample: true }),
});
pipeline.addStage({
  stageName: 'StepFunctions',
  actions: [stepFunctionAction],
});

这个 StateMachineInput 可以使用两种静电厂方法之一创建: literal,它把任意地图作为它唯一的论据,或 filePath数字 :

import * as stepfunctions from '@aws-cdk/aws-stepfunctions';

const pipeline = new codepipeline.Pipeline(this, 'MyPipeline');
const inputArtifact = new codepipeline.Artifact();
const startState = new stepfunctions.Pass(this, 'StartState');
const simpleStateMachine  = new stepfunctions.StateMachine(this, 'SimpleStateMachine', {
  definition: startState,
});
const stepFunctionAction = new codepipeline_actions.StepFunctionInvokeAction({
  actionName: 'Invoke',
  stateMachine: simpleStateMachine,
  stateMachineInput: codepipeline_actions.StateMachineInput.filePath(inputArtifact.atPath('assets/input.json')),
});
pipeline.addStage({
  stageName: 'StepFunctions',
  actions: [stepFunctionAction],
});

见 aWS 文档 关于行动结构参考的信息.

版本与发布记录

@aws-cdk/aws-codepipeline-actions 共发布 257 个版本,首次发布于 2019/03/30;过去 12 个月发布了 0 个版本。

版本发布日期距今
1.204.0latest2023/06/203 年前
1.203.02023/06/013 年前
1.202.02023/05/223 年前
1.201.02023/05/113 年前
1.200.02023/04/273 年前
1.199.02023/04/213 年前

关于 @aws-cdk/aws-codepipeline-actions 的常见问题

@aws-cdk/aws-codepipeline-actions 是什么?

AWS 代码管道的具体行动注意:该包已被作者标记为弃用——AWS CDK v1 has reached End-of-Support on 2023-06-01. This package is no longer being updated, and users should migrate to AWS CDK v2. For more information on how to migrate, see https://docs.aws.amazon.com/cdk/v2/guide/migrating-v2.html

如何安装 @aws-cdk/aws-codepipeline-actions?

在项目目录运行 npm install @aws-cdk/aws-codepipeline-actions,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:@aws-cdk/aws-cloudformation(1.204.0)、@aws-cdk/aws-codebuild(1.204.0)、@aws-cdk/aws-codecommit(1.204.0)、@aws-cdk/aws-codedeploy(1.204.0)、@aws-cdk/aws-codepipeline(1.204.0)、@aws-cdk/aws-ec2(1.204.0)、@aws-cdk/aws-ecr(1.204.0)、@aws-cdk/aws-ecs(1.204.0)、@aws-cdk/aws-events(1.204.0)、@aws-cdk/aws-events-targets(1.204.0)、@aws-cdk/aws-iam(1.204.0)、@aws-cdk/aws-kms(1.204.0)、@aws-cdk/aws-lambda(1.204.0)、@aws-cdk/aws-s3(1.204.0)、@aws-cdk/aws-sns(1.204.0)、@aws-cdk/aws-sns-subscriptions(1.204.0)、@aws-cdk/aws-stepfunctions(1.204.0)、@aws-cdk/core(1.204.0)、constructs(^3.3.69)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@aws-cdk/aws-codepipeline-actions 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@aws-cdk/aws-codepipeline-actions 支持 ESM 还是 CommonJS?

以 CommonJS 形式发布,可以直接 require();在 ES Module 项目中也可以用 import 引入(Node.js 会把 module.exports 作为默认导出)。

@aws-cdk/aws-codepipeline-actions 需要什么版本的 Node.js?

package.json 的 engines 字段要求 Node.js >= 14.15.0。版本不符时 npm 默认只给出警告,开启 engine-strict 后会拒绝安装。

@aws-cdk/aws-codepipeline-actions 可以商用吗?

@aws-cdk/aws-codepipeline-actions 使用 Apache-2.0 许可。宽松许可:允许商业使用、修改和再分发,并附带明确的专利授权;分发时需保留许可与 NOTICE 文件,修改过的文件要注明改动。以上为概括,不构成法律意见,请以许可原文为准。

@aws-cdk/aws-codepipeline-actions 的下载量有多少?

根据 npm 官方下载统计,@aws-cdk/aws-codepipeline-actions 在 2026/10/07 – 2026/11/05 这 30 天内被下载 70,528 次,日均约 2,351 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@aws-cdk/aws-codepipeline-actions 还在维护吗?

最新版本 1.204.0 发布于 2023/06/20(3 年前);至今共发布 257 个版本,其中过去 12 个月发布了 0 个;首次发布于 2019/03/30。作者已将其标记为弃用,新项目建议寻找替代方案。