はじめに
AWS CDKの勉強のためにCDK Workshopをやりました。このWorkshopのCDK PipelinesのセクションではCodeCommitを使っています。ただ、実際の業務ではGitHubを使うことが多いので、勉強がてらGitHubに変更してやってみました。
CDK PipelinesのセクションをCodeCommitではなくGitHubでやる方法
Workshopのセクション毎に手順を記載します。
GETTING STARTED WITH PIPELINES
CodeCommitの場合と同じです。
CREATE REPOSITORY
CodeCommitのリポジトリを作る必要はないです。GitHubにリポジトリを作成して、コードをpushしておきましょう。
CREATE NEW PIPELINE
事前準備
まず、GitHubとのConnectionを作成する必要があります。
-
Connectionを開いて、接続の作成を押しましょう。
-
生成したConnectionのARNは後で使うのでメモしておきましょう。
Define an Empty Pipeline
input
はCodeCommitではなくGitHubを指定しましょう。
また、GitHubのリポジトリ名など必要な情報はコマンドライン引数経由で取得するようにしてます。
import * as cdk from 'aws-cdk-lib';
import { Construct } from 'constructs';
import * as codecommit from 'aws-cdk-lib/aws-codecommit';
import { WorkshopPipelineStage } from './pipeline-stage';
import {
CodeBuildStep,
CodePipeline,
CodePipelineSource,
} from 'aws-cdk-lib/pipelines';
import { Pipeline } from 'aws-cdk-lib/aws-codepipeline';
export class WorkshopGithubPipelineStack extends cdk.Stack {
constructor(scope: Construct, id: string, props?: cdk.StackProps) {
super(scope, id, props);
/* 必要な情報をコマンドライン引数経由で取得 */
const owner = this.node.tryGetContext('Owner') as string
const repository = this.node.tryGetContext('Repository') as string
const branch = this.node.tryGetContext('Branch') as string
const connectionArn = this.node.tryGetContext('ConnectionArn') as string
// The basic pipeline declaration. This sets the initial structure
// of our pipeline
const pipeline = new CodePipeline(this, 'CodePipeline', {
codePipeline: new Pipeline(this, 'Pipeline', {
restartExecutionOnUpdate: false,
}),
selfMutation: false,
synth: new CodeBuildStep('SynthStep', {
/* GitHubから読み込み */
input: CodePipelineSource.connection(
`${owner}/${repository}`,
`${branch}`,
{
connectionArn: connectionArn,
triggerOnPush: false
}
),
installCommands: ['npm install -g aws-cdk'],
commands: [
'npm ci',
'npm run build',
'npx cdk synth',
],
}),
});
}
}
ちなみに、本記事の主題ではないのですが、下記のオプションを指定しています。
-
selfMutation: false
パイプライン実行時にパイプラインの更新をしないようにする。 -
restartExecutionOnUpdate: false
パイプライン更新時に自動実行をしないようにする。 -
triggerOnPush: false
コードpush時に自動実行をしないようにする。
Define an Empty Pipeline
-c
オプションを指定してデプロイしましょう。
- Owner
GitHubリポジトリのOwner名 - Repository
GitHubリポジトリ名 - Branch
GitHubプランチ名 - ConnectionArn
先ほど生成したConnectionのARN
cdk deploy -c Owner={Owner} -c Repository={Repository} -c Branch={Branch} -c ConnectionArn={ConnectionArn}
ADD APPLICATION TO PIPELINE
CodeCommitの場合と同じです。
POLISH PIPELINE
CodeCommitの場合と同じです。
CLEANUP
CodeCommitの場合と同じです。
最後に
全体のソースコードは下記のリポジトリに公開しています。