目次

AWS CodeConnections 完全ガイド v2.0(2026年最新対応)

マネージドコネクター・外部リポジトリ統合・DevOps自動化


目次


ドキュメントメタデータ

  • 最終更新: 2026-04-26
  • バージョン: v2.0
  • 対象者: DevOps エンジニア、CI/CD パイプラインアーキテクト、Platform Engineer
  • 難易度: 初級~中級
  • 関連サービス: CodePipeline、CodeBuild、CodeDeploy、CodeCatalyst、GitHub/GitLab/Bitbucket

概要と課題

本質

AWS CodeConnections(旧: AWS CodeStar Connections)は、「GitHub・GitLab・Bitbucket などの外部ソースコードリポジトリと AWS の DevOps サービス(CodePipeline・CodeBuild・CodeCatalyst)を安全に接続するマネージドコネクターサービス」である。OAuth ベースの認証で一度接続を設定すれば、複数の AWS サービスが同一の接続を再利用でき、トークン管理・有効期限更新の手間を排除する。

このサービスを選ぶ理由

なぜ AWS CodeConnections でないといけないのか?

  1. GitHub トークン管理の複雑性を排除

    • 従来の CodePipeline(CodeStarSourceConnection の前身)では GitHub の Personal Access Token(PAT)を直接入力・管理する必要があり、トークン有効期限切れでパイプラインが停止するリスク
    • CodeConnections は OAuth ベースの GitHub App インストールで安全に接続でき、AWS が自動的にトークン更新・リフレッシュを管理
    • 個人の GitHub アカウント依存を排除し、組織レベルの GitHub App インストールで複数メンバーが利用可能
  2. 複数 AWS サービスからの接続再利用

    • 一度設定した Connection ARN を CodePipeline・CodeBuild・CodeCatalyst が共有可能
    • 各サービスごとに個別の認証情報を管理する必要がなく、中央管理で一括更新可能
    • Connection の削除時に全サービスに自動反映され、不正アクセスリスク最小化
  3. GitHub Enterprise / GitLab Self-Managed のオンプレミス統合

    • パブリック GitHub だけでなく、社内オンプレミスの GitHub Enterprise Server・GitLab Self-Managed・Bitbucket Data Center にも対応
    • Host 設定で VPC 経由のプライベート接続をサポート
    • コードが外部に出せない金融・医療・政府機関でも AWS CI/CD を活用可能
  4. 複数リポジトリプロバイダーの一元管理

    • GitHub・GitHub Enterprise・GitLab・GitLab Self-Managed・Bitbucket Cloud・Bitbucket Self-Managed をすべてサポート
    • リポジトリプロバイダーごとに別途認証ツール(GitHub App、GitLab CI/CD Variables、Bitbucket Pipelines OIDC)を構築する必要がなく、統一インターフェースで管理
    • マルチリポジトリプロバイダー運用企業でのオペレーション統一
  5. セキュアなコード配送(Shift Left)

    • PR トリガーで CodePipeline・CodeBuild を起動し、コードレビュー・CI/CD を統合
    • GitHub Actions の Webhook ベースの実行ではなく、AWS ネイティブの IAM・CloudTrail 監査ログで完全なトレーサビリティ実現

このサービスを選ばない理由

  • CodeCommit 専用使用(AWS ネイティブで十分)
  • 外部リポジトリを使わない環境
  • OAuth 認証不可の制限環境(ただし Host 設定でプライベート接続は可能)

アーキテクチャと設計原則

全体構成図(Mermaid 1)

graph TB
    subgraph External["外部リポジトリ(ユーザー管理)"]
        GH["GitHub / GitHub Enterprise"]
        GL["GitLab / GitLab SM"]
        BB["Bitbucket / Bitbucket SM"]
    end
    
    subgraph AWS["AWS アカウント(CodeConnections管理)"]
        CC["CodeConnections Service<br/>Connection Resource"]
        CP["CodePipeline<br/>(Source Stage)"]
        CB["CodeBuild<br/>(Build/Test)"]
        CAT["CodeCatalyst"]
    end
    
    subgraph Auth["認証・認可フロー"]
        OAUTH["OAuth 2.0<br/>Authorization Code Flow"]
        GH_APP["GitHub App<br/>Installation"]
    end
    
    GH -->|Install GitHub App| GH_APP
    GH_APP -->|OAuth Handshake| OAUTH
    OAUTH -->|Connection ARN<br/>Access Token| CC
    GL -->|Custom App| CC
    BB -->|OIDC / OAuth| CC
    
    CC -->|UseConnection<br/>权限| CP
    CC -->|UseConnection| CB
    CC -->|useConnection| CAT
    
    CP -->|Clone via SSH/HTTPS| GH
    CB -->|git fetch| GL
    CAT -->|PR Trigger| BB
    
    style CC fill:#e8f4f8
    style CP fill:#fff3cd
    style CB fill:#f8f9fa
    style OAUTH fill:#cfe2ff
    style GH_APP fill:#d1ecf1

コンポーネント階層

CodeConnections
├── Connection(接続リソース)
│   ├── Name(識別名)
│   ├── ARN(一意の識別子)
│   ├── Status(Pending / Available / Failed)
│   ├── Provider Type(GitHub / GitLab / Bitbucket など)
│   └── Installation(OAuth トークン・メタデータ)
│
├── Host(オンプレミス用)
│   ├── Name
│   ├── Provider Endpoint(https://gitlab.company.com)
│   ├── Provider Type(GitLabSelfManaged / BitbucketSelfManaged)
│   └── TLS Certificate Validation
│
└── Service Integration
    ├── CodePipeline(Source Action)
    ├── CodeBuild(Source Provider)
    └── CodeCatalyst(Space Connection)

サポートプロバイダー一覧

プロバイダー タイプ ホスト設定 OAuth方式 IAM ロール 特記事項
GitHub クラウド GitHub App 必須 最も一般的・GitHub App インストール推奨
GitHub Enterprise Cloud クラウド GitHub App 必須 組織レベルの App 認証
GitHub Enterprise Server オンプレ GitHub App 必須 VPC エンドポイント・AWS PrivateLink サポート
GitLab クラウド Personal Access Token 必須 gitlab.com 対応
GitLab Self-Managed オンプレ Personal Access Token 必須 ホスト設定で社内 URL 指定
Bitbucket Cloud クラウド OIDC / OAuth 必須 Atlassian OAuth フロー
Bitbucket Self-Managed オンプレ Personal Access Token 必須 Data Center の認証情報

コアコンポーネント

1. Connection リソース

定義

  • 外部リポジトリへのアクセス権を保持する AWS マネージド リソース
  • ARN ベースで一意に識別され、複数の AWS サービスから参照可能
  • OAuth トークン・認証情報は AWS Secrets Manager で安全に暗号化・保管

ライフサイクル

作成後: Pending
    ↓
コンソール / CLI で認証確認(ブラウザリダイレクト)
    ↓
Available
    ↓
CodePipeline / CodeBuild で利用可能
    ↓
削除時: リソース削除(使用中のパイプラインは自動停止)

属性

- ConnectionArn: arn:aws:codeconnections:region:account:connection/name
- ConnectionName: 識別名(変更不可)
- ProviderType: GitHub | GitLab | Bitbucket
- HostArn: (Self-Managed の場合)
- Status: Pending | Available | Failed
- CreateTime: ISO 8601

2. Host リソース(Self-Managed 用)

定義

  • GitLab Self-Managed・Bitbucket Data Center などのオンプレミスリポジトリへのアクセス設定
  • 社内ホストの URL・TLS 証明書を登録

設定内容

aws codeconnections create-host \
  --name "my-gitlab-datacenter" \
  --provider-type GitLabSelfManaged \
  --provider-endpoint "https://gitlab.internal.company.com" \
  --vpc-configuration "SecurityGroupIds=sg-xxx,SubnetIds=subnet-xxx"

3. GitHub App

インストール手順

  1. AWS CodeConnections コンソールで Connection 作成(Provider: GitHub)
  2. Status が Pending 状態で「Pending connection」リンクをクリック
  3. GitHub に認証・GitHub App インストール認可画面に遷移
  4. リポジトリ選択(All repositories / 特定リポジトリのみ)
  5. 確認後 AWS に戻り、Status が Available に変更

権限スコープ

GitHub App が CodeConnections に要求する権限:
  - Administration: write(デプロイキー設定)
  - Contents: read & write(コードアクセス・PR コメント)
  - Metadata: read(リポジトリメタデータ)
  - Pull requests: read & write(PR トリガー)
  - Webhooks: write(イベント通知登録)

4. OutputArtifactFormat(CodePipeline)

CODE_ZIP(デフォルト)

  • ソースコードを ZIP 形式で S3 にアップロード
  • git メタデータ(履歴・ブランチ情報)なし
  • 軽量でシンプルなビルドに推奨
  • CodeBuild で git コマンド使用不可

CODEBUILD_CLONE_REF

  • git リポジトリのフルクローン(全履歴・ブランチ情報保持)
  • git loggit describe --tags・バージョニング などに必須
  • CodeBuild IAM ロールに codeconnections:UseConnection 権限必須
  • 若干遅いがセマンティックバージョニング・リリースノート自動生成に推奨

主要ユースケース

1. GitHub → CodePipeline による CI/CD パイプライン自動化

シナリオ: 開発チームが GitHub で日々のコード更新を行い、main ブランチへのマージで自動的に AWS 上のテスト・デプロイを実行したい

aws codeconnections create-connection \
  --provider-type GitHub \
  --connection-name my-github-prod-connection

# → Status: Pending(コンソールで GitHub 認証)

# CodePipeline で Connection 使用
aws codepipeline create-pipeline --cli-input-json '{
  "pipeline": {
    "name": "github-to-prod",
    "roleArn": "arn:aws:iam::123456789012:role/codepipeline-role",
    "stages": [{
      "name": "Source",
      "actions": [{
        "name": "GitHubSource",
        "actionTypeId": {
          "category": "Source",
          "owner": "AWS",
          "provider": "CodeStarSourceConnection",
          "version": "1"
        },
        "configuration": {
          "ConnectionArn": "arn:aws:codeconnections:ap-northeast-1:123456789012:connection/my-github-prod-connection",
          "FullRepositoryId": "myorg/myapp",
          "BranchName": "main",
          "OutputArtifactFormat": "CODE_ZIP",
          "DetectChanges": "true"
        },
        "outputArtifacts": [{"name": "SourceOutput"}]
      }]
    }]
  }
}'

メリット

  • GitHub トークン管理不要(OAuth App 管理に一本化)
  • PR マージ・Push 自動トリガー
  • 複数パイプラインが同一 Connection を共有

2. GitLab Self-Managed → CodeBuild での社内ビルド統合

シナリオ: 社内オンプレミス GitLab からコードをビルドし、AWS CodeBuild で Docker イメージ構築・ECR プッシュを実行

# Host 作成(GitLab Self-Managed)
aws codeconnections create-host \
  --name "internal-gitlab" \
  --provider-type GitLabSelfManaged \
  --provider-endpoint "https://gitlab.internal.company.com"

# Connection 作成(Host を参照)
aws codeconnections create-connection \
  --provider-type GitLabSelfManaged \
  --connection-name internal-gitlab-connection \
  --host-arn arn:aws:codeconnections:ap-northeast-1:123456789012:host/internal-gitlab

# CodeBuild プロジェクトで使用
aws codebuild create-project --name my-build --source '{
  "type": "GITHUB",
  "location": "https://gitlab.internal.company.com/mygroup/myrepo",
  "auth": {
    "type": "CODECONNECTIONS",
    "resource": "arn:aws:codeconnections:ap-northeast-1:123456789012:connection/internal-gitlab-connection"
  }
}' --service-role arn:aws:iam::123456789012:role/codebuild-role

メリット

  • VPC PrivateLink で社内ネットワーク接続
  • コードが外部に出ない
  • AWS 監査ログで全アクセス記録

3. PR トリガー(CodePipeline V2)

シナリオ: GitHub PR 作成時に CodePipeline を起動してテスト実行・自動デプロイをステージング環境で実行

{
  "pipeline": {
    "pipelineType": "V2",
    "triggers": [{
      "providerType": "CodeStarSourceConnection",
      "gitConfiguration": {
        "pullRequest": [{
          "events": ["OPEN", "UPDATED"],
          "branches": {
            "includes": ["main", "develop"]
          },
          "filePaths": {
            "includes": ["src/**", "buildspec.yml"]
          }
        }]
      }
    }]
  }
}

4. 複数 CodeBuild プロジェクトからの共有 Connection

シナリオ: GitHub のリポジトリを複数の異なるビルド(Unit Test、Integration Test、SonarQube 解析)で参照

# Connection を一度作成
CONN_ARN="arn:aws:codeconnections:ap-northeast-1:123456789012:connection/shared-github"

# 複数プロジェクトで再利用
for BUILD_NAME in unit-test integration-test sonarqube-scan; do
  aws codebuild create-project \
    --name $BUILD_NAME \
    --source '{
      "type": "GITHUB",
      "location": "https://github.com/myorg/myrepo",
      "auth": {"type": "CODECONNECTIONS", "resource": "'$CONN_ARN'"}
    }' \
    --service-role arn:aws:iam::123456789012:role/codebuild-role
done

5. デプロイキー・SSH キー管理の自動化

CodeConnections の GitHub App が自動化

  • リポジトリへのデプロイキー登録(AWS CodeBuild で git clone 用)
  • トークンリフレッシュ(有効期限切れ前の自動更新)
  • GitHub App の権限更新(UI で即反映)

6. Organization レベルの App 管理

複数チームの一元管理

# GitHub 側(Organization Settings → GitHub Apps)で
# CodeConnections GitHub App を Organization に Install
# → 所属全リポジトリへのアクセス権自動付与
# → Connection ARN 一つで全リポジトリ対応

7. BitBucket Cloud への接続

aws codeconnections create-connection \
  --provider-type Bitbucket \
  --connection-name my-bitbucket-connection

# Bitbucket の OAuth 画面で認可
# → Status: Available

# CodePipeline で使用(GitHub と同じ構文)

8. CodeCatalyst 連携

定義 CodeCatalyst(AWS の新世代 IDE・DevOps プラットフォーム)から GitHub リポジトリを直接連携

aws codecatalyst associate-github-repo-to-space \
  --space-name my-space \
  --github-connection-arn arn:aws:codeconnections:ap-northeast-1:123456789012:connection/github-conn

9. 複数 Organization の App 管理

各 GitHub Organization で独立した App をインストール

  • Organization A → GitHub App “CodeConnections-OrgA”
  • Organization B → GitHub App “CodeConnections-OrgB”
  • 各 Organization に個別 Connection を作成
  • → 権限分離・監査ログ明確化

10. リポジトリ削除時の接続維持

GitHub App のリポジトリ削除後も Connection は Available のまま

  • 別リポジトリへの変更は管理者画面で管理
  • Connection ARN を変更する必要なし

11. Pull Request コメント統合(CodeGuru / CodePipeline)

CodeGuru Reviewer との統合

{
  "configuration": {
    "ConnectionArn": "arn:aws:codeconnections:...",
    "FullRepositoryId": "myorg/myrepo",
    "BranchName": "main"
  }
}

→ PR コメントで CodeGuru の自動レビューコメント投稿

12. クロスアカウント Connection 共有(AWS Organizations)

親アカウント Connection を複数子アカウント CodePipeline で参照

# 親アカウント
aws codeconnections create-connection --provider-type GitHub

# 子アカウント CodePipeline から親の Connection ARN を参照(IAM 権限に基づく)

設定・操作の具体例

CLI 操作(5 パターン)

1. GitHub Connection の基本作成・確認

# Connection 作成
aws codeconnections create-connection \
  --provider-type GitHub \
  --connection-name github-main-prod \
  --tags "Key=Environment,Value=Production" "Key=Team,Value=DevOps"

# 返り値例
{
  "ConnectionArn": "arn:aws:codeconnections:ap-northeast-1:123456789012:connection/github-main-prod",
  "ConnectionStatus": "PENDING"
}

# Status 確認(Available になるまで待機)
aws codeconnections get-connection \
  --connection-arn arn:aws:codeconnections:ap-northeast-1:123456789012:connection/github-main-prod \
  --query 'Connection.[ConnectionStatus,ProviderType,ConnectionName]' \
  --output table

# Connection 一覧取得
aws codeconnections list-connections \
  --provider-type GitHub \
  --max-results 10

2. GitLab Self-Managed との複合設定

# ステップ1: Host リソース作成
HOST_ARN=$(aws codeconnections create-host \
  --name internal-gitlab-host \
  --provider-type GitLabSelfManaged \
  --provider-endpoint https://gitlab.company.internal:443 \
  --query 'HostArn' \
  --output text)

echo "Created Host: $HOST_ARN"

# ステップ2: Host に対応する Connection 作成
CONN_ARN=$(aws codeconnections create-connection \
  --provider-type GitLabSelfManaged \
  --connection-name internal-gitlab-prod \
  --host-arn $HOST_ARN \
  --query 'ConnectionArn' \
  --output text)

echo "Created Connection: $CONN_ARN"

# ステップ3: Connection 詳細確認
aws codeconnections describe-host \
  --host-arn $HOST_ARN

3. Connection 削除・再作成

# 削除前に使用状況確認
CONN_ARN="arn:aws:codeconnections:ap-northeast-1:123456789012:connection/old-github-conn"

# CodePipeline で使用中の場合は先に削除・修正
aws codepipeline list-pipelines --query 'pipelines[].name' --output text | while read PIPE; do
  aws codepipeline get-pipeline --name $PIPE | grep -q $CONN_ARN && echo "使用中: $PIPE"
done

# Connection 削除
aws codeconnections delete-connection --connection-arn $CONN_ARN

# 新規作成
aws codeconnections create-connection \
  --provider-type GitHub \
  --connection-name new-github-conn

4. イベントベース トリガー設定(CodePipeline V2)

# Pipeline JSON テンプレート
cat > pipeline-v2-pr-trigger.json <<'EOF'
{
  "pipeline": {
    "name": "pr-triggered-pipeline",
    "pipelineType": "V2",
    "roleArn": "arn:aws:iam::123456789012:role/codepipeline-role",
    "triggers": [{
      "providerType": "CodeStarSourceConnection",
      "gitConfiguration": {
        "pullRequest": [{
          "events": ["OPEN", "UPDATED", "CLOSED"],
          "branches": {
            "includes": ["main", "release/*"],
            "excludes": ["hotfix/*"]
          },
          "filePaths": {
            "includes": ["src/**", "tests/**", "buildspec.yml"],
            "excludes": ["*.md", ".gitignore"]
          }
        }]
      }
    }],
    "stages": [{
      "name": "SourceStage",
      "actions": [{
        "name": "GitHubSource",
        "actionTypeId": {
          "category": "Source",
          "owner": "AWS",
          "provider": "CodeStarSourceConnection",
          "version": "1"
        },
        "configuration": {
          "ConnectionArn": "arn:aws:codeconnections:ap-northeast-1:123456789012:connection/github-main",
          "FullRepositoryId": "myorg/myapp",
          "BranchName": "main",
          "OutputArtifactFormat": "CODEBUILD_CLONE_REF"
        },
        "outputArtifacts": [{"name": "SourceOutput"}]
      }]
    }]
  }
}
EOF

aws codepipeline create-pipeline --cli-input-json file://pipeline-v2-pr-trigger.json

5. CodeBuild での git clone フル履歴利用

# buildspec.yml
cat > buildspec.yml <<'EOF'
version: 0.2

phases:
  pre_build:
    commands:
      - echo "Getting latest tag for versioning..."
      - export VERSION=$(git describe --tags --always)
      - echo "Version: $VERSION"
  build:
    commands:
      - echo "Building version $VERSION..."
      - npm run build
      - docker build -t myapp:$VERSION .
  post_build:
    commands:
      - docker push 123456789012.dkr.ecr.ap-northeast-1.amazonaws.com/myapp:$VERSION
EOF

# CodeBuild Project(OutputArtifactFormat: CODEBUILD_CLONE_REF 必須)
aws codebuild create-project \
  --name version-aware-build \
  --source '{
    "type": "GITHUB",
    "location": "https://github.com/myorg/myapp",
    "auth": {
      "type": "CODECONNECTIONS",
      "resource": "arn:aws:codeconnections:ap-northeast-1:123456789012:connection/github-conn"
    }
  }' \
  --service-role arn:aws:iam::123456789012:role/codebuild-role \
  --environment '{
    "type": "LINUX_CONTAINER",
    "image": "aws/codebuild/standard:7.0",
    "computeType": "BUILD_GENERAL1_MEDIUM"
  }' \
  --source-version main

SDK / Infrastructure as Code(5 パターン)

1. CloudFormation で Connection 作成

AWSTemplateFormatVersion: '2010-09-09'
Description: 'CodeConnections GitHub Setup'

Resources:
  GitHubConnection:
    Type: AWS::CodeStarConnections::Connection
    Properties:
      ConnectionName: github-prod-conn
      ProviderType: GitHub

Outputs:
  ConnectionArn:
    Description: GitHub Connection ARN
    Value: !GetAtt GitHubConnection.ConnectionArn
    Export:
      Name: !Sub '${AWS::StackName}-ConnectionArn'

2. Python SDK(Boto3)での自動化

import boto3

def setup_github_connection(region, conn_name, tags=None):
    """GitHub Connection を作成して Status を監視"""
    client = boto3.client('codeconnections', region_name=region)
    
    # Connection 作成
    response = client.create_connection(
        ProviderType='GitHub',
        ConnectionName=conn_name,
        Tags=tags or []
    )
    
    conn_arn = response['ConnectionArn']
    print(f"Created: {conn_arn}")
    print(f"Status: {response['ConnectionStatus']}")
    print("\nPlease visit the AWS Console to complete GitHub OAuth authorization")
    print(f"Connection Name: {conn_name}")
    
    # Status が Available になるまでポーリング(オプション)
    waiter = client.get_waiter('connection_available')
    try:
        waiter.wait(ConnectionArn=conn_arn)
        print("Connection is now Available!")
    except Exception as e:
        print(f"Waiting failed: {e}")
    
    return conn_arn

def list_all_connections(region):
    """全 Connection を一覧"""
    client = boto3.client('codeconnections', region_name=region)
    paginator = client.get_paginator('list_connections')
    
    for page in paginator.paginate():
        for conn in page['Connections']:
            print(f"Name: {conn['ConnectionName']}")
            print(f"  ARN: {conn['ConnectionArn']}")
            print(f"  Provider: {conn['ProviderType']}")
            print(f"  Status: {conn['ConnectionStatus']}")

if __name__ == '__main__':
    setup_github_connection('ap-northeast-1', 'my-github-conn')
    list_all_connections('ap-northeast-1')

3. Terraform での Connection・CodePipeline 統合

terraform {
  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = "~> 5.0"
    }
  }
}

provider "aws" {
  region = "ap-northeast-1"
}

# GitHub Connection
resource "aws_codeconnections_connection" "github" {
  name            = "github-prod"
  provider_type   = "GitHub"

  lifecycle {
    ignore_changes = [authorization_result]
  }

  tags = {
    Environment = "Production"
    Team        = "DevOps"
  }
}

# CodePipeline
resource "aws_codepipeline" "example" {
  name     = "github-to-codebuild-pipeline"
  role_arn = aws_iam_role.codepipeline_role.arn

  artifact_store {
    location = aws_s3_bucket.pipeline_artifacts.id
    type     = "S3"
  }

  stage {
    name = "Source"

    action {
      name             = "GitHub"
      category         = "Source"
      owner            = "AWS"
      provider         = "CodeStarSourceConnection"
      version          = "1"
      output_artifacts = ["source_output"]

      configuration = {
        ConnectionArn            = aws_codeconnections_connection.github.arn
        FullRepositoryId         = "myorg/myapp"
        BranchName               = "main"
        OutputArtifactFormat     = "CODE_ZIP"
        DetectChanges            = "true"
      }
    }
  }

  stage {
    name = "Build"

    action {
      name            = "Build"
      category        = "Build"
      owner           = "AWS"
      provider        = "CodeBuild"
      input_artifacts = ["source_output"]
      version         = "1"

      configuration = {
        ProjectName = aws_codebuild_project.example.name
      }
    }
  }
}

# CodeBuild Project
resource "aws_codebuild_project" "example" {
  name          = "github-build"
  service_role  = aws_iam_role.codebuild_role.arn

  artifacts {
    type = "CODEPIPELINE"
  }

  environment {
    compute_type                = "BUILD_GENERAL1_SMALL"
    image                       = "aws/codebuild/standard:7.0"
    type                        = "LINUX_CONTAINER"
    image_pull_credentials_type = "CODEBUILD"
  }

  source {
    type            = "CODEPIPELINE"
    buildspec       = "buildspec.yml"
  }
}

4. CDK(TypeScript)での完全パイプライン構築

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 iam from 'aws-cdk-lib/aws-iam';

export class GitHubCIPipelineStack extends cdk.Stack {
  constructor(scope: cdk.App, id: string, props?: cdk.StackProps) {
    super(scope, id, props);

    // CodeConnections Connection
    const sourceConnection = new codepipeline_actions.CodeStarConnectionsSourceAction({
      actionName: 'GitHub_Source',
      owner: 'myorg',
      repo: 'myapp',
      branch: 'main',
      output: new codepipeline.Artifact('SourceOutput'),
      connectionArn: 'arn:aws:codeconnections:ap-northeast-1:123456789012:connection/github-conn',
      runOrder: 1,
    });

    // CodeBuild Project
    const buildProject = new codebuild.PipelineProject(this, 'BuildProject', {
      buildSpec: codebuild.BuildSpec.fromSourceFilename('buildspec.yml'),
      environment: {
        buildImage: codebuild.LinuxBuildImage.STANDARD_7_0,
        computeType: codebuild.ComputeType.SMALL,
      },
    });

    // Pipeline
    const pipeline = new codepipeline.Pipeline(this, 'Pipeline', {
      pipelineName: 'GitHubCIPipeline',
      stages: [
        {
          stageName: 'Source',
          actions: [sourceConnection],
        },
        {
          stageName: 'Build',
          actions: [
            new codepipeline_actions.CodeBuildAction({
              actionName: 'Build',
              project: buildProject,
              input: new codepipeline.Artifact('SourceOutput'),
            }),
          ],
        },
      ],
    });
  }
}

const app = new cdk.App();
new GitHubCIPipelineStack(app, 'GitHubPipelineStack');

5. AWS SAM(Serverless Application Model)での Lambda カスタムアクション

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31

Resources:
  # CodeConnections Connection
  GitHubConnection:
    Type: AWS::CodeStarConnections::Connection
    Properties:
      ConnectionName: github-sam-conn
      ProviderType: GitHub

  # Lambda for Custom Pipeline Action
  PipelineApprovalLambda:
    Type: AWS::Serverless::Function
    Properties:
      FunctionName: codepipeline-custom-approval
      Handler: index.handler
      Runtime: python3.11
      Policies:
        - Version: '2012-10-17'
          Statement:
            - Effect: Allow
              Action:
                - codepipeline:PutJobSuccessResult
                - codepipeline:PutJobFailureResult
              Resource: '*'
      InlineCode: |
        import json
        import boto3

        def handler(event, context):
            codepipeline = boto3.client('codepipeline')
            job_id = event['CodePipeline.job']['id']

            # Custom logic for approval
            approval_result = custom_approval_logic()

            if approval_result:
                codepipeline.put_job_success_result(jobId=job_id)
            else:
                codepipeline.put_job_failure_result(
                    jobId=job_id,
                    failureDetails={'message': 'Approval denied'}
                )

        def custom_approval_logic():
            return True  # Placeholder

  # CodePipeline using CodeConnections
  Pipeline:
    Type: AWS::CodePipeline::Pipeline
    Properties:
      Name: GitHubSAMPipeline
      RoleArn: !GetAtt CodePipelineRole.Arn
      ArtifactStore:
        Type: S3
        Location: !Ref ArtifactBucket
      Stages:
        - Name: Source
          Actions:
            - Name: GitHubSource
              ActionTypeId:
                Category: Source
                Owner: AWS
                Provider: CodeStarSourceConnection
                Version: '1'
              Configuration:
                ConnectionArn: !GetAtt GitHubConnection.ConnectionArn
                FullRepositoryId: myorg/myapp
                BranchName: main
                OutputArtifactFormat: CODE_ZIP
              OutputArtifacts:
                - Name: SourceOutput

  # S3 Bucket for Artifacts
  ArtifactBucket:
    Type: AWS::S3::Bucket

  # IAM Role for CodePipeline
  CodePipelineRole:
    Type: AWS::IAM::Role
    Properties:
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: codepipeline.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AWSCodePipelineFullAccess
      Policies:
        - PolicyName: CodeConnectionsAccess
          PolicyDocument:
            Version: '2012-10-17'
            Statement:
              - Effect: Allow
                Action:
                  - codeconnections:UseConnection
                Resource: !GetAtt GitHubConnection.ConnectionArn

Outputs:
  PipelineUrl:
    Description: CodePipeline URL
    Value: !Sub 'https://console.aws.amazon.com/codepipeline/home?region=${AWS::Region}#/view/${Pipeline}'
  ConnectionArn:
    Description: CodeConnections ARN
    Value: !GetAtt GitHubConnection.ConnectionArn

類似サービス比較表

観点 CodeConnections GitHub Apps(直接) GitLab CI/CD Variables Bitbucket Pipelines AWS CodeCommit
認証方式 OAuth + App GitHub App Personal Token OIDC + OAuth IAM ロール
トークン管理 AWS 一元管理 GitHub 側管理 手動管理 OIDC 自動 IAM ポリシー
複数 AWS サービス共有 ✅(ARN参照) N/A
Self-Managed 対応 ✅(Host設定) ✅(ただし API設定複雑) N/A
PR トリガー ✅(V2) ✅(GitHub Actions) N/A
IAM 監査ログ ✅(CloudTrail) 制限的 GitHub ログのみ GitHub ログのみ ✅(完全)
有効期限更新 自動 手動 手動 自動(OIDC) N/A
AWS 統合度 ネイティブ エージェント必要 エージェント エージェント 最高
推奨用途 GitHub/GitLab/BB → AWS GitHub Actions 統合 GitLab 専用 Bitbucket 専用 AWS 専用

ベストプラクティス

✅ 推奨事項

# プラクティス 理由
1 GitHub App インストール(Personal Token 回避) OAuth フロー自動管理・セキュア・スケーラブル
2 Organization レベルの GitHub App 全リポジトリ自動カバー・権限一元化
3 OutputArtifactFormat = CODEBUILD_CLONE_REF(版管理) git describe・セマンティックバージョニング対応
4 Self-Managed 時は Host 設定で VPC 接続 プライベートネットワーク・コード外部流出防止
5 IAM ロールに codeconnections:UseConnection 権限制限 最小権限原則
6 Connection ARN を環境変数・SSM で管理 ハードコード回避
7 CodePipeline V2 で PR トリガー設定 Branch/File Path フィルター・自動化度向上
8 複数リージョン時は リージョン別 Connection リージョンごとに独立した接続管理
9 定期的な Connection Status 監視 認証失敗の早期発見
10 CloudTrail で codeconnections API 呼び出しログ セキュリティ・コンプライアンス監査

❌ アンチパターン

# 反パターン 問題点
1 Personal Access Token を直接入力 トークン有効期限・権限漏洩リスク
2 OutputArtifactFormat = CODE_ZIP で git log 使用 メタデータなし・バージョニング失敗
3 全リポジトリで個別 Connection 作成 管理複雑化・トークン増加・有効期限管理負荷
4 Self-Managed をホスト設定なしで接続 オンプレ→AWS 通信経路非セキュア
5 Connection ARN をパイプライン定義にハードコード 変更時全定義更新必要
6 CodeConnections API 権限を全サービス許可 過度な権限付与・セキュリティリスク
7 PR トリガーなし(定期ポーリングのみ) リアルタイム性なし・遅延
8 削除した Connection を参照し続ける パイプラインエラー・自動トリガー停止

トラブルシューティング表

エラーメッセージ 原因 対策
ConnectionStatus: FAILED GitHub App インストール認可が完了していない AWS コンソール → CodeConnections → Connection クリック → GitHub 認証完了
“Connection not found” in CodePipeline Connection ARN が誤り・削除済み aws codeconnections list-connections で正しい ARN 確認
“CodeBuild cannot clone repository” OutputArtifactFormat = CODEBUILD_CLONE_REF だが IAM 権限なし CodeBuild IAM ロールに codeconnections:UseConnection 権限追加
**“Host endpoint unreachable”(Self-Managed) Host URL が誤り・ネットワーク不通 VPC 設定・セキュリティグループ・URL スキーム(http vs https)確認
**“PR trigger not firing”(V2 Pipeline) PR filter が排除している・Connection pending gitConfiguration の branch/filePath フィルター確認・Status を Available に
“Unauthorized to access this repository” GitHub App リポジトリアクセス権不足 GitHub Organization → GitHub Apps → CodeConnections → “Install” で対象リポジトリ選択
“Token expired” エラー GitLab/Bitbucket の Personal Token 有効期限切れ Connection を再認証(削除→再作成 or AWS Console 再認可)
CodePipeline Stage が Unknown エラー 古い CodeStarSourceConnection provider を参照 Pipeline 定義で provider: “CodeStarSourceConnection” 確認(V2 対応)
“Cannot use CODEBUILD_CLONE_REF with S3 source” OutputArtifactFormat が S3 ソースに非対応 CODE_ZIP を使用 or CodeConnections を使用
**“SecurityGroup subnet validation failed”(Host) VPC 設定で SubnetIds / SecurityGroupIds が不正 VPC・Subnet・SG が同じ VPC に属しているか確認

2025-2026 最新動向

1. CodeGuru との統合強化(2025-2026)

CodeGuru Reviewer・Security が CodeConnections PR をネイティブサポート

# CodeConnections Connection が自動検出
# → PR にセキュリティ脆弱性・コード品質コメント自動投稿

2. AI-powered Reviewer(Amazon Q)の PR コメント統合

2026 上半期 GA 予定

  • Amazon Q が PR コメントを自動生成
  • CodeConnections PR トリガーと統合
  • コード修正提案の自動生成

3. GitLab / Bitbucket の拡張機能対応

GitLab Merge Request トリガー(従来は推しづらかった)

  • CodePipeline V2 で MR トリガー正式対応予定

Bitbucket Cloud での Pull Request OIDC 強化

  • 従来の Personal Token から OIDC への完全移行推奨

4. クロスリージョン Connection リプリケーション

複数リージョンでの Connection 自動同期

  • 親リージョンで Connection 作成 → 子リージョンに自動レプリケーション
  • まだ実装待ちだが RFC が提案中

5. CodeCatalyst の GitHub 統合統一

CodeCatalyst がプライマリ IDE に昇格

  • CodeConnections をベースに GitHub リポジトリを直接管理
  • GitHub Copilot 統合強化

学習リソース・参考文献

AWS 公式ドキュメント

  1. What is AWS CodeConnections

  2. CodeConnections User Guide

  3. CodeConnections API Reference

  4. CodePipeline Source Actions

  5. CodeBuild Source Specification

  6. GitHub App Installation Guide

  7. AWS IAM Best Practices

オープンソース・ベンダー リソース

  1. AWS CodePipeline Workshop(GitHub)

  2. Terraform AWS Provider(CodeConnections)

  3. AWS CDK(aws-codepipeline-actions)

  4. AWS Samples GitHub

  5. GitHub Actions + AWS サンプル


実装例・チェックリスト

実装例:GitHub → CodePipeline → CodeBuild → ECR フルパイプライン

#!/bin/bash
set -e

AWS_REGION="ap-northeast-1"
AWS_ACCOUNT_ID="123456789012"
GITHUB_ORG="myorg"
GITHUB_REPO="myapp"
GITHUB_BRANCH="main"

# Step 1: CodeConnections GitHub Connection 作成
echo "Creating GitHub Connection..."
CONN_ARN=$(aws codeconnections create-connection \
  --provider-type GitHub \
  --connection-name github-prod-connection \
  --region $AWS_REGION \
  --query 'ConnectionArn' \
  --output text)

echo "Created Connection: $CONN_ARN"
echo "⚠️  Please complete GitHub OAuth in AWS Console before proceeding..."
read -p "Press Enter after completing OAuth authentication..."

# Step 2: Connection Status を Available に確認
STATUS=$(aws codeconnections get-connection \
  --connection-arn $CONN_ARN \
  --region $AWS_REGION \
  --query 'Connection.ConnectionStatus' \
  --output text)

if [ "$STATUS" != "AVAILABLE" ]; then
  echo "Error: Connection status is $STATUS, not AVAILABLE"
  exit 1
fi

echo "✅ Connection is AVAILABLE"

# Step 3: S3 Artifact Bucket 作成
echo "Creating S3 artifact bucket..."
ARTIFACT_BUCKET="codepipeline-artifacts-${AWS_ACCOUNT_ID}-${AWS_REGION}"
aws s3api create-bucket \
  --bucket $ARTIFACT_BUCKET \
  --region $AWS_REGION \
  --create-bucket-configuration LocationConstraint=$AWS_REGION || echo "Bucket already exists"

# Step 4: IAM Role 作成(CodePipeline)
echo "Creating IAM roles..."
cat > trust-policy.json <<EOF
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {"Service": "codepipeline.amazonaws.com"},
    "Action": "sts:AssumeRole"
  }]
}
EOF

CODEPIPELINE_ROLE_ARN=$(aws iam create-role \
  --role-name codepipeline-github-role \
  --assume-role-policy-document file://trust-policy.json \
  --region $AWS_REGION \
  --query 'Role.Arn' \
  --output text) || \
CODEPIPELINE_ROLE_ARN=$(aws iam get-role --role-name codepipeline-github-role --query 'Role.Arn' --output text)

# Step 5: IAM Policy 作成
cat > codepipeline-policy.json <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": [
        "s3:*",
        "codeconnections:UseConnection",
        "codebuild:BatchGetBuilds",
        "codebuild:BatchGetProjects",
        "codebuild:BatchBuildIdentifiers",
        "codebuild:StartBuild"
      ],
      "Resource": "*"
    }
  ]
}
EOF

aws iam put-role-policy \
  --role-name codepipeline-github-role \
  --policy-name codepipeline-policy \
  --policy-document file://codepipeline-policy.json

# Step 6: CodeBuild Project 作成
echo "Creating CodeBuild project..."
cat > buildspec.yml <<'BUILDEOF'
version: 0.2

phases:
  pre_build:
    commands:
      - echo "Logging in to Amazon ECR..."
      - aws ecr get-login-password --region $AWS_REGION | docker login --username AWS --password-stdin $AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com
      - REPO_URI=$AWS_ACCOUNT_ID.dkr.ecr.$AWS_REGION.amazonaws.com/myapp
      - IMAGE_TAG=$(git describe --tags --always 2>/dev/null || echo "latest")
  build:
    commands:
      - echo "Building Docker image on `date`"
      - docker build -t $REPO_URI:$IMAGE_TAG .
      - docker tag $REPO_URI:$IMAGE_TAG $REPO_URI:latest
  post_build:
    commands:
      - echo "Pushing Docker image..."
      - docker push $REPO_URI:$IMAGE_TAG
      - docker push $REPO_URI:latest
      - echo "Creating image definitions file..."
      - printf '[{"name":"myapp","imageUri":"%s"}]' $REPO_URI:$IMAGE_TAG > imagedefinitions.json

artifacts:
  files:
    - imagedefinitions.json

cache:
  paths:
    - '/root/.docker/**/*'
BUILDEOF

cat > codebuild-trust.json <<EOF
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {"Service": "codebuild.amazonaws.com"},
    "Action": "sts:AssumeRole"
  }]
}
EOF

CODEBUILD_ROLE_ARN=$(aws iam create-role \
  --role-name codebuild-github-role \
  --assume-role-policy-document file://codebuild-trust.json \
  --region $AWS_REGION \
  --query 'Role.Arn' \
  --output text) || \
CODEBUILD_ROLE_ARN=$(aws iam get-role --role-name codebuild-github-role --query 'Role.Arn' --output text)

cat > codebuild-policy.json <<EOF
{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Effect": "Allow",
      "Action": ["logs:*", "ecr:*", "s3:*", "codeconnections:UseConnection"],
      "Resource": "*"
    }
  ]
}
EOF

aws iam put-role-policy \
  --role-name codebuild-github-role \
  --policy-name codebuild-policy \
  --policy-document file://codebuild-policy.json

aws codebuild create-project \
  --name github-docker-build \
  --source type=CODEPIPELINE \
  --artifacts type=CODEPIPELINE \
  --environment type=LINUX_CONTAINER,image=aws/codebuild/standard:7.0,computeType=BUILD_GENERAL1_SMALL \
  --service-role $CODEBUILD_ROLE_ARN \
  --region $AWS_REGION || echo "Project already exists"

# Step 7: CodePipeline 作成
echo "Creating CodePipeline..."
cat > pipeline.json <<EOF
{
  "pipeline": {
    "name": "github-to-ecr-pipeline",
    "roleArn": "$CODEPIPELINE_ROLE_ARN",
    "artifactStore": {
      "type": "S3",
      "location": "$ARTIFACT_BUCKET"
    },
    "stages": [
      {
        "name": "Source",
        "actions": [{
          "name": "GitHubSource",
          "actionTypeId": {
            "category": "Source",
            "owner": "AWS",
            "provider": "CodeStarSourceConnection",
            "version": "1"
          },
          "configuration": {
            "ConnectionArn": "$CONN_ARN",
            "FullRepositoryId": "$GITHUB_ORG/$GITHUB_REPO",
            "BranchName": "$GITHUB_BRANCH",
            "OutputArtifactFormat": "CODEBUILD_CLONE_REF"
          },
          "outputArtifacts": [{"name": "SourceOutput"}]
        }]
      },
      {
        "name": "Build",
        "actions": [{
          "name": "Build",
          "actionTypeId": {
            "category": "Build",
            "owner": "AWS",
            "provider": "CodeBuild",
            "version": "1"
          },
          "configuration": {"ProjectName": "github-docker-build"},
          "inputArtifacts": [{"name": "SourceOutput"}],
          "outputArtifacts": [{"name": "BuildOutput"}]
        }]
      }
    ]
  }
}
EOF

aws codepipeline create-pipeline \
  --cli-input-json file://pipeline.json \
  --region $AWS_REGION || echo "Pipeline already exists"

echo "✅ Pipeline setup complete!"
echo "GitHub Connection ARN: $CONN_ARN"
echo "Artifact Bucket: $ARTIFACT_BUCKET"
echo "Pipeline Name: github-to-ecr-pipeline"

# Cleanup
rm -f trust-policy.json codebuild-trust.json codepipeline-policy.json codebuild-policy.json pipeline.json

採用チェックリスト

  • [ ] GitHub / GitLab / Bitbucket の外部リポジトリを AWS 上の CI/CD で使用する
  • [ ] CodePipeline / CodeBuild を使用している
  • [ ] Personal Access Token の管理・有効期限切れのリスクがある
  • [ ] 複数の AWS サービスで同一リポジトリを参照している
  • [ ] GitHub Enterprise Server / GitLab Self-Managed を使用している
  • [ ] PR ベースの自動トリガーが必要(main ブランチ以外)
  • [ ] git describe・semantic versioning が必要(CODEBUILD_CLONE_REF)
  • [ ] CodeCatalyst を検討している
  • [ ] IAM ベースの監査ログが必要
  • [ ] Organization レベルの接続管理が必要

まとめ

AWS CodeConnections は 「GitHub・GitLab・Bitbucket などの外部リポジトリと AWS DevOps サービスを安全に接続するマネージドコネクターサービス」。OAuth ベースの認証で トークン管理の複雑さを排除し、複数 AWS サービスが同一 Connection ARN を再利用できる。Self-Managed リポジトリにも対応し、CodePipeline V2 の PR トリガーと組み合わせることで、GitHub Actions 並みの自動化を AWS ネイティブに実現する。Personal Access Token の有効期限切れ・権限漏洩のリスクを排除しながら、IAM・CloudTrail による完全な監査ログを備えたエンタープライズグレードの外部リポジトリ接続ソリューション。


最終更新:2026-04-26 バージョン:v2.0