我正在使用官方 AWS 文档来使用 CDK 创建管道:https://docs.aws.amazon.com/cdk/latest/guide/cdk_pipeline.html#cdk_pipeline_define https://docs.aws.amazon.com/cdk/latest/guide/cdk_pipeline.html#cdk_pipeline_define(与文档略有不同,我使用了 CodeStar 连接,正如代码注释所建议的那样)
这会自动创建一个自变异管道,具有三个阶段:Source、Synth 和 UpdatePipeline。那太棒了。
我想添加一个带有 CodeBuild 操作的新阶段。我希望 CodeBuild 操作基于源目录中的 buildspec.yml 文件。
在控制台上,我可以通过单击“添加新阶段”、“添加操作”并从下拉菜单中选择输入工件来轻松完成此操作。
然而,在 CDK 上,使用推荐的设置并没有简单的方法来访问输入工件。
我通过强迫设法做到了buildPipeline()
并这样做:
import * as cdk from "@aws-cdk/core";
import {
CodePipeline,
ShellStep,
CodePipelineSource,
} from "@aws-cdk/pipelines";
import * as codebuild from "@aws-cdk/aws-codebuild";
import * as codepipelineActions from "@aws-cdk/aws-codepipeline-actions";
export class PipelineStack extends cdk.Stack {
public readonly source: cdk.CfnOutput
constructor(scope: cdk.Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
const source = CodePipelineSource.connection("someuser/somerepo", "master", {
connectionArn: "arn:aws:codestar-connections:us-east-1:REDACTED:connection/REDACTED"
});
const synthShellStep = new ShellStep("Synth", {
input: source,
commands: [
"cd infrastructure",
"npm run ci",
"npm run build",
"npx cdk synth"
],
"primaryOutputDirectory": "infrastructure/cdk.out"
});
const pipeline = new CodePipeline(this, "Pipeline", {
pipelineName: "FancyPipeline",
synth: synthShellStep
});
// Need to build the pipeline to access the
// source artifact
pipeline.buildPipeline();
const sourceStage = pipeline.pipeline.stage("Source");
if (sourceStage) {
const sourceOutputs = sourceStage.actions[0].actionProperties.outputs;
if (sourceOutputs && sourceOutputs.length > 0) {
const sourceArtifact = sourceOutputs[0];
const codeBuildProject = new codebuild.PipelineProject(this, 'DockerBuildProject', {
environment: {
privileged: true
}
});
const buildAction = new codepipelineActions.CodeBuildAction({
actionName: 'DockerBuild',
project: codeBuildProject,
input: sourceArtifact,
environmentVariables: {
AWS_DEFAULT_REGION: {
value: this.region
},
AWS_ACCOUNT_ID: {
value: this.account
},
IMAGE_REPO_NAME: {
value: "somereponame"
},
IMAGE_TAG: {
value: "latest"
}
}
});
pipeline.pipeline.addStage({
stageName: "DockerBuildStage",
actions: [buildAction],
});
}
}
}
}
但这总体感觉很尴尬,而且我无法打电话addStage()
on the CodePipeline
不再建造。当然有更好的方法来做我想做的事情吗?
任何帮助/建议将不胜感激。谢谢。