Claude Code × AWS CodePipeline/CodeBuild 完全ガイド|CI/CDパイプラインを自動構築
AWS CodePipeline・CodeBuildによるCI/CDをClaude Codeで自動構築。パイプライン設計・buildspec.yml生成・テスト自動化・CDKでのインフラ定義まで実例コードで解説。
「GitHub Actions でいいじゃん、なんでわざわざ AWS CodePipeline を使うの?」——これはよく聞かれる質問です。
答えは AWS リソースとの統合の深さにあります。ECRへのプッシュ、ECSへのデプロイ、CloudFormationスタックの更新——これらをAWSネイティブで完結させたい場合、CodePipeline + CodeBuildの組み合わせが最もシームレスです。
私は業務で複数のAWSサービスを組み合わせたパイプラインを管理していますが、Claude Code にパイプライン要件を伝えるだけで、buildspec.yml・CDKコード・IAMポリシーが一式生成されるようになってから、新規パイプラインの構築時間が1/4になりました。
CodePipeline / CodeBuild の基本構造
CodePipeline (オーケストレーター)
│
├─ Source ステージ: GitHub / CodeCommit からコードを取得
├─ Build ステージ: CodeBuild でビルド・テスト・Docker イメージ作成
├─ Test ステージ: 統合テスト・セキュリティスキャン (オプション)
└─ Deploy ステージ: ECS / Elastic Beanstalk / S3 にデプロイ
CodeBuild は buildspec.yml に記述したコマンドを実行します。GitHub Actions の steps: に相当するものと考えると理解しやすいです。
Step 1: buildspec.yml を自動生成
claude -p "
以下の条件で CodeBuild の buildspec.yml を生成して。
【ビルド内容】
- Node.js 20 環境
- npm ci でインストール
- TypeScript のビルド (npm run build)
- ユニットテスト実行 (npm test)
- Docker イメージをビルドして ECR にプッシュ
- イメージタグ: CODEBUILD_RESOLVED_SOURCE_VERSION (Git SHA)
- latest タグも同時に付与
【セキュリティスキャン】
- ECR イメージプッシュ後に Trivy でスキャン
- HIGH/CRITICAL 脆弱性があればビルド失敗
【アーティファクト】
- imagedefinitions.json を出力 (ECS デプロイ用)
"
生成される buildspec.yml:
version: 0.2
env:
variables:
AWS_DEFAULT_REGION: ap-northeast-1
ECR_REPO_NAME: myapp
parameter-store:
ECR_REGISTRY: /myapp/ecr-registry
phases:
install:
runtime-versions:
nodejs: 20
commands:
- echo "Installing dependencies..."
- npm ci
pre_build:
commands:
- echo "Running tests..."
- npm test
- echo "Logging in to Amazon ECR..."
- aws ecr get-login-password | docker login --username AWS --password-stdin $ECR_REGISTRY
- IMAGE_TAG=$CODEBUILD_RESOLVED_SOURCE_VERSION
- IMAGE_URI=$ECR_REGISTRY/$ECR_REPO_NAME:$IMAGE_TAG
build:
commands:
- echo "Building TypeScript..."
- npm run build
- echo "Building Docker image..."
- docker build -t $IMAGE_URI -t $ECR_REGISTRY/$ECR_REPO_NAME:latest .
post_build:
commands:
- echo "Pushing image to ECR..."
- docker push $IMAGE_URI
- docker push $ECR_REGISTRY/$ECR_REPO_NAME:latest
- echo "Scanning image for vulnerabilities..."
- |
docker run --rm \
-v /var/run/docker.sock:/var/run/docker.sock \
aquasec/trivy:latest image \
--exit-code 1 \
--severity HIGH,CRITICAL \
$IMAGE_URI
- echo "Creating imagedefinitions.json..."
- printf '[{"name":"app","imageUri":"%s"}]' $IMAGE_URI > imagedefinitions.json
artifacts:
files:
- imagedefinitions.json
reports:
test-reports:
files:
- "coverage/junit.xml"
file-format: JUNITXML
Step 2: CDK でパイプライン全体を構築
claude -p "
lib/pipeline-stack.ts に以下の CodePipeline を CDK TypeScript で実装して。
【パイプライン構成】
- Source: GitHub (owner/repo の main ブランチ)
- Build: CodeBuild (上の buildspec.yml を使用)
- Deploy: ECS サービスへの Blue/Green デプロイ
【通知】
- パイプライン失敗時に SNS → Slack に通知
- デプロイ成功時にも Slack に通知
【アーティファクトストア】
- S3 バケット (暗号化・バージョニング有効)
"
// lib/pipeline-stack.ts
import * as cdk from "aws-cdk-lib";
import * as codepipeline from "aws-cdk-lib/aws-codepipeline";
import * as codepipeline_actions from "aws-cdk-lib/aws-codepipeline-actions";
import * as codebuild from "aws-cdk-lib/aws-codebuild";
import * as s3 from "aws-cdk-lib/aws-s3";
import * as iam from "aws-cdk-lib/aws-iam";
import * as sns from "aws-cdk-lib/aws-sns";
export class PipelineStack extends cdk.Stack {
constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
super(scope, id, props);
// アーティファクトストア S3
const artifactBucket = new s3.Bucket(this, "ArtifactBucket", {
versioned: true,
encryption: s3.BucketEncryption.S3_MANAGED,
removalPolicy: cdk.RemovalPolicy.RETAIN,
});
// アーティファクト定義
const sourceOutput = new codepipeline.Artifact("SourceOutput");
const buildOutput = new codepipeline.Artifact("BuildOutput");
// CodeBuild プロジェクト
const buildProject = new codebuild.PipelineProject(this, "BuildProject", {
buildSpec: codebuild.BuildSpec.fromSourceFilename("buildspec.yml"),
environment: {
buildImage: codebuild.LinuxBuildImage.STANDARD_7_0,
privileged: true, // Docker ビルドに必要
},
environmentVariables: {
AWS_ACCOUNT_ID: { value: this.account },
},
});
// ECR へのアクセス権を付与
buildProject.addToRolePolicy(new iam.PolicyStatement({
actions: [
"ecr:GetAuthorizationToken",
"ecr:BatchCheckLayerAvailability",
"ecr:PutImage",
"ecr:InitiateLayerUpload",
"ecr:UploadLayerPart",
"ecr:CompleteLayerUpload",
],
resources: ["*"],
}));
// パイプライン
const pipeline = new codepipeline.Pipeline(this, "Pipeline", {
pipelineName: "myapp-pipeline",
artifactBucket,
stages: [
{
stageName: "Source",
actions: [
new codepipeline_actions.GitHubSourceAction({
actionName: "GitHub_Source",
owner: "your-org",
repo: "your-repo",
branch: "main",
oauthToken: cdk.SecretValue.secretsManager("github-token"),
output: sourceOutput,
}),
],
},
{
stageName: "Build",
actions: [
new codepipeline_actions.CodeBuildAction({
actionName: "Build_and_Test",
project: buildProject,
input: sourceOutput,
outputs: [buildOutput],
}),
],
},
{
stageName: "Deploy",
actions: [
new codepipeline_actions.EcsDeployAction({
actionName: "Deploy_to_ECS",
service: ecs.FargateService.fromFargateServiceAttributes(
this, "EcsService", {
cluster: ecs.Cluster.fromClusterArn(
this, "Cluster",
`arn:aws:ecs:${this.region}:${this.account}:cluster/myapp-cluster`
),
serviceName: "myapp-service",
}
),
input: buildOutput,
}),
],
},
],
});
// 失敗通知
const alertTopic = new sns.Topic(this, "AlertTopic");
pipeline.notifyOnAnyStageStateChange("PipelineNotification", alertTopic, {
events: [
codepipeline.PipelineNotificationEvents.PIPELINE_EXECUTION_FAILED,
codepipeline.PipelineNotificationEvents.PIPELINE_EXECUTION_SUCCEEDED,
],
});
}
}
Step 3: テスト結果レポートの設定
claude -p "
CodeBuild でテスト結果を CodeBuild Reports に送信して
PR ごとに品質レポートを確認できるようにしたい。
- テストフレームワーク: Vitest
- カバレッジレポート: Istanbul (lcov形式)
- buildspec.yml に reports セクションを追加
- CDK でレポートグループも定義
"
# buildspec.yml の reports セクション
reports:
UnitTestResults:
files:
- "test-results/junit.xml"
file-format: JUNITXML
CodeCoverage:
files:
- "coverage/lcov.info"
file-format: CLOVERXML
Step 4: マルチ環境パイプラインの設計
claude -p "
dev → staging → prod の3環境への段階デプロイパイプラインを CDK で設計して。
- dev: main ブランチに push で自動デプロイ
- staging: dev デプロイ成功後、手動承認後にデプロイ
- prod: staging デプロイ成功後、手動承認後にデプロイ
- 各環境のデプロイ完了を Slack に通知
"
// staging → prod の手動承認ゲートを追加
{
stageName: "Approve_Staging",
actions: [
new codepipeline_actions.ManualApprovalAction({
actionName: "Approve_Deploy_to_Staging",
notificationTopic: alertTopic,
additionalInformation: "Staging へのデプロイを承認しますか?",
}),
],
},
{
stageName: "Deploy_Staging",
actions: [
new codepipeline_actions.EcsDeployAction({
actionName: "Deploy_to_Staging",
service: stagingService,
input: buildOutput,
}),
],
},
落とし穴4選
1. CodeBuild の privileged: true を忘れる
Docker イメージをビルドするには privileged: true が必須。これがないと Cannot connect to the Docker daemon エラーが出ます。
2. GitHub OAuth トークンの権限不足
GitHubソースには repo スコープが必要。public_repo だけだとプライベートリポジトリに使えません。
3. S3アーティファクトバケットのリージョン
パイプラインとアーティファクトS3バケットは同じリージョンである必要があります。クロスリージョンパイプラインは別途設定が必要。
4. ECS デプロイアクションの imagedefinitions.json 形式
ECS デプロイには正確な形式が必要です:
[{"name": "コンテナ名", "imageUri": "イメージURI"}]
コンテナ名はタスク定義のコンテナ名と完全一致させてください。
まとめ
| タスク | Claude Code の貢献 |
|---|---|
| buildspec.yml 生成 | ビルド・テスト・Docker・セキュリティスキャン込みで生成 |
| CDKパイプライン | Source→Build→Deploy の全ステージを自動生成 |
| マルチ環境設計 | 手動承認ゲート付きの段階デプロイを設計 |
| テストレポート | CodeBuild Reports の設定を自動化 |
CodePipeline の設定は複雑に見えますが、Claude Code に「こういうパイプラインが欲しい」と伝えるだけで buildspec.yml も CDK コードも一式揃います。まず buildspec.yml から試してみてください。
関連記事
- Claude Code × AWS ECS/Fargate 完全ガイド
- Claude Code × AWS CloudFormation/CDK 完全ガイド
- Claude Code × AWS IAM 完全ガイド
参考資料
無料PDF: Claude Code 5分でわかるチートシート
メールアドレスを登録するだけで、A4 1枚のチートシートPDFを今すぐお送りします。
個人情報は厳重に管理し、スパムは送りません。
この記事を書いた人
Masa
現役DX室長|Claude Code でゼロから多言語AI技術メディア運営中。実務直結の自動化、AI開発相談・研修受付中。
関連書籍・参考図書
この記事のテーマに関連する書籍を楽天ブックスで探せます。
※ 当サイトは楽天市場のアフィリエイトプログラムに参加しています。上記リンクから商品をご購入いただくと、運営者に紹介料が支払われる場合があります。
関連記事
Claude Code × Amazon Bedrock 完全ガイド|AWS上でClaudeを本番運用する
Claude CodeでAmazon Bedrockを活用する完全ガイド。IAM認証・ストリーミング・Lambda統合・RAG実装・コスト最適化まで、Masaの業務実装経験をもとに解説。
Claude Code × AWS CloudWatch 完全ガイド|ログ分析・アラーム設定・ダッシュボード自動構築
AWS CloudWatchをClaude Codeで効率化。ログのパターン分析・アラーム自動設定・メトリクスダッシュボード構築・インシデント調査まで実例コードで解説。
Claude Code × AWS ECS/Fargate 完全ガイド|コンテナデプロイを自動化する
AWS ECS/FargateへのデプロイをClaude Codeで自動化。タスク定義・サービス設定・Blue/Greenデプロイ・CDKでのインフラ構築まで、Masaの実務経験をもとに解説。