目次

Amazon EC2 Image Builder 完全ガイド v2.0

セキュアなゴールデン AMI 自動ビルド・テスト・配布の包括的解説


ドキュメントの目的

本ガイドは以下を対象としています。

  • 初心者向け:EC2 Image Builder とは何か、ゴールデン AMI をなぜ自動化するのかを学びたい方
  • DevOps エンジニア向け:Image Pipeline・レシピ・コンポーネントの実装を習得したい方
  • インフラストラクチャエンジニア向け:STIG・CIS コンプライアンス自動化を構築したい方
  • セキュリティ責任者向け:セキュアな AMI 管理・コンプライアンス自動化を理解したい方
  • マルチアカウント運用者向け:組織全体の ゴールデン AMI 統一管理を実現したい方

2026 年の Image Builder エコシステム

コンプライアンス自動化の進化

  • STIG 更新:2026 年 Q1 で全レベル(Low/Medium/High)対応、Windows Server 2025 追加
  • CIS Hardening:Level 1・2 ベンチマーク完全対応、Bash / GPO スクリプト提供
  • SUSE Linux Enterprise Server(SLES)対応:2026 年 Q1 追加

コンポーネント・テスト強化

  • AWS Task Orchestrator and Executor(AWSTOE):拡張スクリプティング機能
  • カスタムテストコンポーネント:セキュリティスキャン(Trivy・Grype 統合)
  • マネージドコンポーネント拡充:OS パッチ・CloudWatch Agent・SSM Agent プリセット

CI/CD 統合・DevOps 連携

  • EventBridge トリガー:OS パッチ・親イメージ更新時の自動ビルド
  • Parameter Store 連携:AMI ID の 自動更新・Launch Template 自動反映
  • CodePipeline 統合:完全な IaC パイプライン

マルチリージョン・マルチアカウント配布

  • Image Sharing:複数アカウント・複数リージョンへの自動配布
  • タグ伝播:親イメージタグの自動継承・カスタムタグ追加

目次

  1. 本質・定義
  2. Image Builder が解決する課題
  3. アーキテクチャ・構成要素
  4. コアコンポーネント詳細
  5. Image Recipe(レシピ)の作成
  6. Component(コンポーネント)の作成
  7. Infrastructure Configuration
  8. Distribution Configuration
  9. Image Pipeline の作成・実行
  10. STIG / CIS コンプライアンス
  11. テスト・検証
  12. CloudFormation / IaC
  13. CLI / SDK 実装例
  14. 運用・監視
  15. Packer との比較
  16. ベストプラクティス
  17. トラブルシューティング
  18. 2025-2026 最新動向
  19. 学習リソース・参考文献
  20. 実装例・チェックリスト
  21. まとめ

本質・定義

Amazon EC2 Image Builder は、「セキュアなゴールデン AMI(EC2 マシンイメージ)を自動的にビルド・テスト・配布するサービス」。パッチ適用・ソフトウェアインストール・セキュリティベースラインテスト(CIS・STIG)を自動化し、常に最新・安全な AMI を維持できます。

簡潔な定義

「EC2 AMI の自動ビルド・テスト・配布パイプライン。セキュリティコンプライアンス自動化で、ゴールデンイメージを常時最新化。」

料金:Image Builder 自体は無料。使用した EC2・S3・KMS のコストのみ。


Image Builder が解決する課題

  1. ゴールデン AMI の手動管理の複雑さ

    • パッチ適用漏れ・バージョン不統一
    • 設定ドリフト・属人化
    • 解決:スケジュール実行で常時最新 AMI 自動生成
  2. セキュリティコンプライアンスの自動化

    • CIS ベンチマーク・STIG 等の手動チェック不可
    • 監査対応に時間がかかる
    • 解決:パイプラインでセキュリティテスト自動実行・失敗時ブロック
  3. マルチアカウント・マルチリージョン配布

    • 手動で複数アカウント・リージョン に AMI コピー
    • タグ・権限管理が複雑
    • 解決:Distribution Configuration で 自動配布・タグ伝播
  4. AMI ライフサイクル管理

    • 古い AMI の削除・追跡困難
    • 容量・費用の無駄
    • 解決:自動削除ポリシー・Lambda 統合
  5. Packer 外部ツール依存

    • CI/CD パイプラインの複雑化
    • Version 管理・互換性問題
    • 解決:AWS ネイティブサービスで シンプル化
  6. ソフトウェアサプライチェーン

    • OS パッチ・ライブラリ脆弱性の追跡
    • ビルド再現性・監査ログ
    • 解決:コンポーネント版控管理・CloudTrail 監査

アーキテクチャ・構成要素

graph LR
    Trigger["Trigger<br/>(Schedule/Manual/<br/>Parent Update)"]
    
    Pipeline["Image Pipeline<br/>(Orchestration)"]
    
    Recipe["Image Recipe<br/>・Parent Image<br/>・Components<br/>・Block Device Mapping"]
    
    Build["Build Phase<br/>・EC2 起動<br/>・Components 実行<br/>・OS パッチ適用"]
    
    Test["Test Phase<br/>・EC2 インスタンス起動<br/>・テストコンポーネント実行<br/>・STIG/CIS 検証"]
    
    Dist["Distribution<br/>・複数リージョンにコピー<br/>・複数アカウントに共有<br/>・タグ付け・暗号化"]
    
    Output["Output<br/>・ゴールデン AMI<br/>・Launch Template 自動更新<br/>・Auto Scaling 対応"]
    
    Trigger --> Pipeline
    Pipeline --> Recipe
    Pipeline --> Build
    Build --> Test
    Test --> Dist
    Dist --> Output
    
    style Pipeline fill:#FF9900
    style Build fill:#FF9900
    style Test fill:#FF9900
    style Dist fill:#FF9900
    style Output fill:#146EB4

コアコンポーネント

  1. Image Recipe:ベース AMI・ビルドコンポーネント・テストコンポーネント定義
  2. Component:ビルド手順(OS パッチ・ソフトウェアインストール)・テスト手順
  3. Infrastructure Configuration:ビルド用 EC2 スペック・ロギング・IAM ロール
  4. Distribution Configuration:リージョン・アカウント・タグ・暗号化設定
  5. Image Pipeline:スケジュール・トリガー・全体オーケストレーション

コアコンポーネント詳細

1. Image Recipe(レシピ)

用途:ビルド対象の AMI 構成定義

Name: web-server-recipe
SemanticVersion: 1.0.0
ParentImage: arn:aws:imagebuilder:ap-northeast-1:aws:image/amazon-linux-2023-x86/x.x.x
Components:
  - arn:aws:imagebuilder:ap-northeast-1:aws:component/update-linux/x.x.x
  - arn:aws:imagebuilder:ap-northeast-1:123456789012:component/install-nginx/1.0.0
  - arn:aws:imagebuilder:ap-northeast-1:aws:component/stig-build-linux-high/x.x.x
BlockDeviceMappings:
  - DeviceName: /dev/xvda
    Ebs:
      Encrypted: true
      VolumeSize: 50
      VolumeType: gp3
      Iops: 3000
      DeleteOnTermination: true

2. Component(コンポーネント)

用途:ビルド・テスト手順の詳細定義(AWSTOE スクリプト)

ビルドコンポーネント例

name: InstallNginx
schemaVersion: 1.0
description: "Install and configure nginx"
phases:
  - name: build
    steps:
      - name: UpdateSystem
        action: ExecuteBash
        inputs:
          commands:
            - dnf update -y
      - name: InstallNginx
        action: ExecuteBash
        inputs:
          commands:
            - dnf install -y nginx
            - systemctl enable nginx
            - echo "server_tokens off;" >> /etc/nginx/nginx.conf
      - name: InstallSSMAgent
        action: ExecuteBash
        inputs:
          commands:
            - dnf install -y amazon-ssm-agent
            - systemctl enable amazon-ssm-agent

テストコンポーネント例

name: SecurityTest
schemaVersion: 1.0
phases:
  - name: test
    steps:
      - name: VerifyNginxInstalled
        action: ExecuteBash
        onFailure: Abort
        inputs:
          commands:
            - nginx -v
            - systemctl is-active nginx
      - name: VerifySSHHardening
        action: ExecuteBash
        inputs:
          commands:
            - grep "^PermitRootLogin no" /etc/ssh/sshd_config
            - grep "^PasswordAuthentication no" /etc/ssh/sshd_config
      - name: CheckFirewall
        action: ExecuteBash
        inputs:
          commands:
            - systemctl is-active firewalld || systemctl is-active iptables

3. Infrastructure Configuration

用途:ビルド・テスト用 EC2 環境設定

{
  "Name": "web-server-infra",
  "InstanceProfileName": "EC2InstanceProfileForImageBuilder",
  "InstanceTypes": ["m6i.large", "m6i.xlarge"],
  "SubnetId": "subnet-0123456789abcdef0",
  "SecurityGroupIds": ["sg-0123456789abcdef0"],
  "TerminateInstanceOnFailure": true,
  "Logging": {
    "S3Logs": {
      "S3BucketName": "image-builder-logs-bucket",
      "S3KeyPrefix": "builds/"
    }
  },
  "SnsTopicArn": "arn:aws:sns:ap-northeast-1:123456789012:image-builder-notifications",
  "KeyPair": "image-builder-key"
}

4. Distribution Configuration

用途:ビルド完了後の AMI 配布設定

{
  "Name": "web-server-distribution",
  "Distributions": [
    {
      "Region": "ap-northeast-1",
      "AmiDistributionConfiguration": {
        "Name": "web-server-{{ imagebuilder:buildDate }}",
        "Description": "Web server golden AMI",
        "AmiTags": {
          "Env": "prod",
          "App": "webserver",
          "BuildDate": "{{ imagebuilder:buildDate }}"
        },
        "TargetAccountIds": ["123456789012", "210987654321"],
        "LaunchPermission": {
          "UserIds": ["123456789012", "210987654321"]
        }
      }
    },
    {
      "Region": "us-east-1",
      "AmiDistributionConfiguration": {
        "Name": "web-server-{{ imagebuilder:buildDate }}-us",
        "AmiTags": {"Env": "prod"}
      }
    }
  ]
}

Image Recipe(レシピ)の作成

AWS CLI での作成

# ビルドコンポーネント作成(nginx インストール)
aws imagebuilder create-component \
  --name install-nginx-component \
  --semantic-version "1.0.0" \
  --platform Linux \
  --type BUILD \
  --data 'name: InstallNginx
schemaVersion: 1.0
phases:
  - name: build
    steps:
      - name: InstallNginx
        action: ExecuteBash
        inputs:
          commands:
            - dnf install -y nginx
            - systemctl enable nginx'

# テストコンポーネント作成(検証)
aws imagebuilder create-component \
  --name nginx-test-component \
  --semantic-version "1.0.0" \
  --platform Linux \
  --type TEST \
  --data 'name: NginxTest
schemaVersion: 1.0
phases:
  - name: test
    steps:
      - name: TestNginx
        action: ExecuteBash
        onFailure: Abort
        inputs:
          commands:
            - nginx -v
            - systemctl is-active nginx | grep active'

# Image Recipe 作成
aws imagebuilder create-image-recipe \
  --name web-server-recipe \
  --semantic-version "1.0.0" \
  --components \
    componentArn=arn:aws:imagebuilder:ap-northeast-1:aws:component/update-linux/x.x.x \
    componentArn=arn:aws:imagebuilder:ap-northeast-1:123456789012:component/install-nginx-component/1.0.0 \
    componentArn=arn:aws:imagebuilder:ap-northeast-1:aws:component/stig-build-linux-high/x.x.x \
    componentArn=arn:aws:imagebuilder:ap-northeast-1:123456789012:component/nginx-test-component/1.0.0 \
  --parent-image "arn:aws:imagebuilder:ap-northeast-1:aws:image/amazon-linux-2023-x86/x.x.x" \
  --block-device-mappings \
    deviceName=/dev/xvda,ebs={encrypted=true,volumeSize=30,volumeType=gp3,iops=3000,deleteOnTermination=true}

Component(コンポーネント)の作成

AWSTOE スクリプト言語

サポートされた Action タイプ

  • ExecuteBash:Bash スクリプト(Linux)
  • ExecutePowerShell:PowerShell(Windows)
  • ExecuteFile:外部スクリプトファイル実行
  • S3Download:S3 からファイルダウンロード
  • Reboot:インスタンス再起動

カスタムコンポーネント例(Python 環境構築)

name: InstallPython310
schemaVersion: 1.0
description: "Install Python 3.10 and development tools"
phases:
  - name: build
    steps:
      - name: UpdateYum
        action: ExecuteBash
        inputs:
          commands:
            - dnf update -y
            
      - name: InstallPython
        action: ExecuteBash
        inputs:
          commands:
            - dnf install -y python3.10 python3.10-devel
            - dnf install -y gcc make openssl-devel
            
      - name: InstallPip
        action: ExecuteBash
        inputs:
          commands:
            - python3.10 -m ensurepip --upgrade
            - pip3.10 install --upgrade pip setuptools wheel
            
      - name: InstallRequiredPackages
        action: ExecuteBash
        inputs:
          commands:
            - pip3.10 install boto3 requests numpy pandas
            
  - name: test
    steps:
      - name: VerifyPythonVersion
        action: ExecuteBash
        onFailure: Abort
        inputs:
          commands:
            - python3.10 --version
            
      - name: VerifyPackages
        action: ExecuteBash
        inputs:
          commands:
            - python3.10 -c "import boto3, requests, numpy, pandas; print('All packages imported successfully')"

Infrastructure Configuration

IAM ロール・インスタンスプロファイル設定

# Image Builder 用 IAM ロール作成
cat > trust-policy.json << 'EOF'
{
  "Version": "2012-10-17",
  "Statement": [{
    "Effect": "Allow",
    "Principal": {
      "Service": "ec2.imagebuilder.amazonaws.com"
    },
    "Action": "sts:AssumeRole"
  }]
}
EOF

aws iam create-role \
  --role-name EC2InstanceRoleForImageBuilder \
  --assume-role-policy-document file://trust-policy.json

# ポリシーアタッチ
aws iam attach-role-policy \
  --role-name EC2InstanceRoleForImageBuilder \
  --policy-arn arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore

aws iam attach-role-policy \
  --role-name EC2InstanceRoleForImageBuilder \
  --policy-arn arn:aws:iam::aws:policy/EC2InstanceProfileForImageBuilder

# インスタンスプロファイル作成
aws iam create-instance-profile \
  --instance-profile-name EC2InstanceProfileForImageBuilder

aws iam add-role-to-instance-profile \
  --instance-profile-name EC2InstanceProfileForImageBuilder \
  --role-name EC2InstanceRoleForImageBuilder

# Infrastructure Configuration 作成
aws imagebuilder create-infrastructure-configuration \
  --name web-server-infra \
  --instance-profile-name EC2InstanceProfileForImageBuilder \
  --instance-types m6i.large m6i.xlarge \
  --subnet-id subnet-0123456789abcdef0 \
  --security-group-ids sg-0123456789abcdef0 \
  --terminate-instance-on-failure true \
  --logging s3Logs={s3BucketName=image-builder-logs,s3KeyPrefix=builds/} \
  --sns-topic-arn arn:aws:sns:ap-northeast-1:123456789012:image-builder-notifications

Distribution Configuration

マルチリージョン配布設定

aws imagebuilder create-distribution-configuration \
  --name web-server-distribution \
  --distributions \
    "[
      {
        \"Region\": \"ap-northeast-1\",
        \"AmiDistributionConfiguration\": {
          \"Name\": \"web-server-{{imagebuilder:buildDate}}\",
          \"Description\": \"Web server golden AMI\",
          \"AmiTags\": {
            \"Env\": \"prod\",
            \"App\": \"webserver\",
            \"BuildDate\": \"{{imagebuilder:buildDate}}\"
          },
          \"TargetAccountIds\": [\"123456789012\", \"210987654321\"],
          \"LaunchPermission\": {
            \"UserIds\": [\"123456789012\", \"210987654321\"]
          }
        }
      },
      {
        \"Region\": \"us-east-1\",
        \"AmiDistributionConfiguration\": {
          \"Name\": \"web-server-{{imagebuilder:buildDate}}-us\",
          \"AmiTags\": {\"Env\": \"prod\"}
        }
      }
    ]"

Image Pipeline の作成・実行

スケジュール実行パイプライン

# Image Pipeline 作成(毎週月曜 0:00 UTC に自動ビルド)
aws imagebuilder create-image-pipeline \
  --name web-server-pipeline \
  --image-recipe-arn arn:aws:imagebuilder:ap-northeast-1:123456789012:image-recipe/web-server-recipe/1.0.0 \
  --infrastructure-configuration-arn arn:aws:imagebuilder:ap-northeast-1:123456789012:infrastructure-configuration/web-server-infra \
  --distribution-configuration-arn arn:aws:imagebuilder:ap-northeast-1:123456789012:distribution-configuration/web-server-distribution \
  --schedule '{
    "scheduleExpression": "cron(0 0 ? * MON *)",
    "pipelineExecutionStartCondition": "EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE"
  }' \
  --image-tests-configuration '{
    "imageTestsEnabled": true,
    "timeoutMinutes": 60
  }' \
  --tags '{
    "Environment": "production",
    "ManagedBy": "ImageBuilder"
  }'

# パイプライン手動実行
aws imagebuilder start-image-pipeline-execution \
  --image-pipeline-arn arn:aws:imagebuilder:ap-northeast-1:123456789012:image-pipeline/web-server-pipeline

# パイプライン実行状態確認
aws imagebuilder get-image-pipeline \
  --image-pipeline-arn arn:aws:imagebuilder:ap-northeast-1:123456789012:image-pipeline/web-server-pipeline

# 実行履歴確認
aws imagebuilder list-image-pipeline-images \
  --image-pipeline-arn arn:aws:imagebuilder:ap-northeast-1:123456789012:image-pipeline/web-server-pipeline \
  --query 'imageSummaryList[*].[arn,dateCreated,state.status]'

STIG / CIS コンプライアンス

AWS マネージド STIG コンポーネント

2026 年 Q1 の最新対応

  • STIG Low/Medium/High:全レベル対応
  • Windows Server:2012 R2・2016・2019・2022・2025 新規対応
  • Linux:Amazon Linux 2・AL2023・SLES(新規)・Red Hat・Ubuntu

STIG コンプライアンス Recipe

name: hardened-web-recipe
semanticVersion: 1.0.0
parentImage: arn:aws:imagebuilder:ap-northeast-1:aws:image/amazon-linux-2023-x86/x.x.x
components:
  # OS パッチ適用
  - componentArn: arn:aws:imagebuilder:ap-northeast-1:aws:component/update-linux/x.x.x
  
  # STIG High レベル(DoD Security Technical Implementation Guide)
  - componentArn: arn:aws:imagebuilder:ap-northeast-1:aws:component/stig-build-linux-high/x.x.x
  
  # CIS Hardening Benchmark Level 2
  - componentArn: arn:aws:imagebuilder:ap-northeast-1:aws:component/cis-hardening-benchmark-level2-linux/x.x.x
  
  # CIS Hardening Build Kit
  - componentArn: arn:aws:imagebuilder:ap-northeast-1:aws:component/cis-build-kit-linux/x.x.x
  
  # カスタム セキュリティ検証
  - componentArn: arn:aws:imagebuilder:ap-northeast-1:123456789012:component/security-hardening-test/1.0.0

カスタム CIS テストコンポーネント

name: CISComplianceTest
schemaVersion: 1.0
description: "Validate CIS Benchmark compliance"
phases:
  - name: test
    steps:
      - name: VerifyPAM
        action: ExecuteBash
        inputs:
          commands:
            - grep -E "^password requisite pam_pwquality.so" /etc/pam.d/system-auth
            - grep -E "^password required pam_pwhistory.so" /etc/pam.d/system-auth
      
      - name: VerifySSH
        action: ExecuteBash
        inputs:
          commands:
            - grep "^PermitRootLogin no" /etc/ssh/sshd_config
            - grep "^PasswordAuthentication no" /etc/ssh/sshd_config
            - grep "^X11Forwarding no" /etc/ssh/sshd_config
      
      - name: VerifyAudit
        action: ExecuteBash
        inputs:
          commands:
            - grep "^auditd" /etc/audit/audit.rules
            - systemctl is-active auditd
      
      - name: VerifyFirewall
        action: ExecuteBash
        inputs:
          commands:
            - systemctl is-active firewalld || systemctl is-active iptables

テスト・検証

Image Tests Configuration

# テスト有効化・タイムアウト設定
aws imagebuilder create-image-pipeline \
  --image-tests-configuration '{
    "imageTestsEnabled": true,
    "timeoutMinutes": 120
  }'

テストコンポーネント実行フロー

1. Build Phase
   ├─ EC2 インスタンス起動
   ├─ ビルドコンポーネント実行
   ├─ OS パッチ適用
   └─ ソフトウェアインストール
   
2. Test Phase
   ├─ テスト用 EC2 インスタンス起動
   ├─ ビルドされた AMI からブート
   ├─ テストコンポーネント実行
   │  ├─ セキュリティ検証(STIG/CIS)
   │  ├─ 機能テスト
   │  └─ パフォーマンステスト
   └─ テスト失敗時:ビルド中止
   
3. Distribution Phase
   ├─ マルチリージョン配布
   ├─ マルチアカウント共有
   └─ ゴールデン AMI 完成

CloudFormation / IaC

CloudFormation テンプレート

Resources:
  ImageBuilderRole:
    Type: AWS::IAM::Role
    Properties:
      RoleName: EC2InstanceRoleForImageBuilder
      AssumeRolePolicyDocument:
        Version: '2012-10-17'
        Statement:
          - Effect: Allow
            Principal:
              Service: ec2.imagebuilder.amazonaws.com
            Action: sts:AssumeRole
      ManagedPolicyArns:
        - arn:aws:iam::aws:policy/AmazonSSMManagedInstanceCore
        - arn:aws:iam::aws:policy/EC2InstanceProfileForImageBuilder

  ImageBuilderInstanceProfile:
    Type: AWS::IAM::InstanceProfile
    Properties:
      Roles:
        - !Ref ImageBuilderRole

  ImageRecipe:
    Type: AWS::ImageBuilder::ImageRecipe
    Properties:
      Name: web-server-recipe
      SemanticVersion: '1.0.0'
      ParentImage: arn:aws:imagebuilder:ap-northeast-1:aws:image/amazon-linux-2023-x86/x.x.x
      Components:
        - ComponentArn: arn:aws:imagebuilder:ap-northeast-1:aws:component/update-linux/x.x.x
        - ComponentArn: arn:aws:imagebuilder:ap-northeast-1:aws:component/stig-build-linux-high/x.x.x
      BlockDeviceMappings:
        - DeviceName: /dev/xvda
          Ebs:
            Encrypted: true
            VolumeSize: 30
            VolumeType: gp3
            Iops: 3000

  InfraConfig:
    Type: AWS::ImageBuilder::InfrastructureConfiguration
    Properties:
      Name: web-server-infra
      InstanceProfileName: !Ref ImageBuilderInstanceProfile
      InstanceTypes:
        - m6i.large
        - m6i.xlarge
      SubnetId: subnet-0123456789abcdef0
      SecurityGroupIds:
        - sg-0123456789abcdef0
      TerminateInstanceOnFailure: true
      Logging:
        S3Logs:
          S3BucketName: image-builder-logs
          S3KeyPrefix: builds/

  DistConfig:
    Type: AWS::ImageBuilder::DistributionConfiguration
    Properties:
      Name: web-server-distribution
      Distributions:
        - Region: ap-northeast-1
          AmiDistributionConfiguration:
            Name: web-server-prod-{{ imagebuilder:buildDate }}
            AmiTags:
              Env: prod
              App: webserver

  ImagePipeline:
    Type: AWS::ImageBuilder::ImagePipeline
    Properties:
      Name: web-server-pipeline
      ImageRecipeArn: !GetAtt ImageRecipe.Arn
      InfrastructureConfigurationArn: !GetAtt InfraConfig.Arn
      DistributionConfigurationArn: !GetAtt DistConfig.Arn
      Schedule:
        ScheduleExpression: 'cron(0 0 ? * MON *)'
        PipelineExecutionStartCondition: EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE
      ImageTestsConfiguration:
        ImageTestsEnabled: true
        TimeoutMinutes: 60

CLI / SDK 実装例

Python(Boto3)での AMI ライフサイクル管理

import boto3
from datetime import datetime, timedelta

imagebuilder = boto3.client('imagebuilder')
ec2 = boto3.client('ec2')

def get_pipeline_status(pipeline_arn):
    """パイプラインの実行状態確認"""
    response = imagebuilder.get_image_pipeline(imagePipelineArn=pipeline_arn)
    pipeline = response['imagePipeline']
    print(f"Pipeline: {pipeline['name']}")
    print(f"Status: {pipeline.get('status', 'Unknown')}")
    print(f"Last Execution: {pipeline.get('dateLastRun', 'Never')}")

def list_generated_amis(pipeline_arn):
    """パイプラインで生成された AMI 一覧"""
    response = imagebuilder.list_image_pipeline_images(imagePipelineArn=pipeline_arn)
    for image in response['imageSummaryList']:
        print(f"AMI: {image['arn']}, Status: {image['state']['status']}, Created: {image['dateCreated']}")

def cleanup_old_amis(retention_days=30):
    """指定日数以上前の Image Builder 生成 AMI を削除"""
    response = ec2.describe_images(
        Owners=['self'],
        Filters=[
            {'Name': 'tag:Source', 'Values': ['ImageBuilder']}
        ]
    )
    
    cutoff_date = datetime.now() - timedelta(days=retention_days)
    
    for image in response['Images']:
        created = datetime.fromisoformat(image['CreationDate'].replace('Z', '+00:00'))
        if created < cutoff_date:
            print(f"Deleting old AMI: {image['ImageId']}")
            ec2.deregister_image(ImageId=image['ImageId'])
            
            # スナップショットも削除
            for mapping in image.get('BlockDeviceMappings', []):
                if 'Ebs' in mapping:
                    snapshot_id = mapping['Ebs'].get('SnapshotId')
                    if snapshot_id:
                        ec2.delete_snapshot(SnapshotId=snapshot_id)
                        print(f"Deleted snapshot: {snapshot_id}")

# 使用例
pipeline_arn = "arn:aws:imagebuilder:ap-northeast-1:123456789012:image-pipeline/web-server-pipeline"
get_pipeline_status(pipeline_arn)
list_generated_amis(pipeline_arn)
cleanup_old_amis(retention_days=30)

Launch Template 自動更新(EventBridge 統合)

import boto3
import json

ssm = boto3.client('ssm')
ec2 = boto3.client('ec2')

def update_launch_template_on_ami_available(event, context):
    """
    EventBridge トリガー:Image Builder ビルド完了時に
    Launch Template の最新 AMI ID を自動更新
    """
    
    # Image Builder 出力から AMI ID 取得
    ami_id = event['detail']['outputResources']['amis'][0]['image']
    
    # SSM Parameter に AMI ID 保存
    ssm.put_parameter(
        Name='/ami/web-server/latest',
        Value=ami_id,
        Type='String',
        Overwrite=True
    )
    
    # Launch Template から Latest バージョン取得
    lt_response = ec2.describe_launch_templates(
        LaunchTemplateNames=['web-server-lt']
    )
    lt_id = lt_response['LaunchTemplates'][0]['LaunchTemplateId']
    
    # Launch Template に新 AMI ID を指定した新バージョン作成
    lt_version = ec2.create_launch_template_version(
        LaunchTemplateId=lt_id,
        SourceVersion='$Latest',
        LaunchTemplateData={
            'ImageId': ami_id
        }
    )
    
    # デフォルトバージョンに設定
    ec2.modify_launch_template(
        LaunchTemplateId=lt_id,
        DefaultVersion=str(lt_version['LaunchTemplateVersion']['VersionNumber'])
    )
    
    print(f"Launch Template updated with AMI: {ami_id}")
    return {'statusCode': 200, 'body': json.dumps('Success')}

運用・監視

CloudWatch Metrics・Alarms

# Image Builder パイプライン実行時間監視
aws cloudwatch put-metric-alarm \
  --alarm-name image-builder-long-build \
  --alarm-description "Alert when Image Builder build takes > 2 hours" \
  --namespace AWS/ImageBuilder \
  --metric-name BuildDuration \
  --statistic Average \
  --period 3600 \
  --threshold 7200 \
  --comparison-operator GreaterThanThreshold

# パイプライン実行失敗通知
aws cloudwatch put-metric-alarm \
  --alarm-name image-builder-build-failure \
  --alarm-description "Alert on Image Builder build failure" \
  --namespace AWS/ImageBuilder \
  --metric-name BuildFailures \
  --statistic Sum \
  --period 300 \
  --threshold 1 \
  --comparison-operator GreaterThanOrEqualToThreshold \
  --alarm-actions arn:aws:sns:ap-northeast-1:123456789012:image-builder-alerts

CloudTrail 監査ログ

# Image Builder API 呼び出し監査
aws cloudtrail lookup-events \
  --lookup-attributes AttributeKey=EventName,AttributeValue=CreateImagePipeline \
  --max-results 10

Packer との比較

観点 EC2 Image Builder HashiCorp Packer
運営 AWS(フルマネージド) HashiCorp(OSS)
セットアップ AWS コンソール・CLI のみ Packer インストール・HCL 記述
コンプライアンス STIG・CIS マネージドコンポーネント カスタム スクリプト必要
マルチリージョン配布 ✅ ネイティブ対応 ⚠️ スクリプト化が必要
スケジュール実行 ✅ EventBridge / CloudFormation ❌ 外部オーケストレーション必要
テスト統合 ✅ ビルトイン ⚠️ InSpec 等で補完
学習曲線 低(AWS 知識のみ) 中(HCL・Packer 言語)
コスト 低(EC2・S3 のみ) 低(OSS)

ベストプラクティス

✅ DO(推奨)

  1. セマンティック バージョニングで管理

    • Recipe・Component は semantic version(例:1.0.0)
    • CHANGELOG で変更履歴管理
  2. STIG / CIS コンプライアンス必須化

    • 本番 Recipe には必ず STIG/CIS コンポーネント組み込み
    • テストコンプライアンス確認後のみ配布
  3. マルチリージョン配布を デフォルトに

    • Distribution Configuration で 主要リージョン指定
    • ディザスタリカバリー対応
  4. パイプライン実行トリガーの最適化

    • EXPRESSION_MATCH_AND_DEPENDENCY_UPDATES_AVAILABLE で 親イメージ更新時のみ実行
    • 不要な再ビルド削減
  5. テストコンポーネント充実

    • セキュリティテスト(STIG・CIS・カスタム)
    • 機能テスト(ソフトウェア動作確認)
    • パフォーマンステスト(起動時間・ストレージ)
  6. Launch Template の自動更新

    • EventBridge で AMI ビルド完了時に 自動反映
    • Auto Scaling が 常時最新 AMI を利用
  7. ログ・監視・監査の実装

    • S3 へのビルドログ出力
    • CloudWatch Metrics 監視
    • CloudTrail による API 監査
  8. IaC での完全管理

    • CloudFormation で Pipeline・Recipe・Component 一元管理
    • Git で バージョン控管理

❌ DON’T(非推奨)

  1. マニュアル AMI コンポーネント更新

    • ドリフト・属人化・コンプライアンス喪失
  2. テストなしでの配布

    • セキュリティリスク・デグレード
  3. シングルリージョン配布

    • ディザスタリカバリー不備
  4. 古い AMI の放置

    • 容量・コスト無駄・セキュリティ
  5. Component のハードコード化

    • パラメータ化で再利用性向上

トラブルシューティング

現象 原因 解決方法
ビルド失敗:インスタンス起動不可 IAM ロール権限不足・サブネット容量枯渇 IAM ロール確認・別サブネット試行
コンポーネント実行失敗 AWSTOE スクリプトエラー・依存ファイル不足 S3 ビルドログ確認・スクリプトテスト
テスト失敗:STIG コンプライアンス不合格 セキュリティ設定ミス・パッチ不完全 テストログ詳細確認・コンポーネント修正
マルチリージョン配布失敗 リージョン権限不足・KMS キー未設定 リージョン IAM ポリシー・KMS キー確認
AMI ブート失敗 ドライバ欠落・fstab 設定エラー 親イメージ検証・コンポーネント確認
ビルド時間が長い コンポーネント最適化不足・大容量パッケージ コンポーネント並列化・不要ファイル削減

2025-2026 最新動向

1. STIG・CIS コンプライアンス拡張(2026 年 Q1)

  • STIG 2026 第 1 四半期版:全レベル対応・Windows Server 2025 新規追加
  • CIS Hardening Components:レベル 1・2 ベンチマーク完全サポート
  • SUSE Linux Enterprise Server(SLES)対応:企業向けリナックス拡張

2. コンポーネント・テスト強化

  • AWSTOE 拡張スクリプティング:より柔軟な制御フロー
  • カスタムテストコンポーネント:Trivy・Grype 等のセキュリティスキャン統合
  • マネージドコンポーネント拡充:CloudWatch Agent・SSM Agent・ECS Optimized

3. CI/CD 統合強化

  • EventBridge トリガー拡張:OS パッチ・親イメージ更新時の自動実行
  • Parameter Store 統合:AMI ID の 自動更新・Launch Template 反映
  • CodePipeline ネイティブ対応:完全なパイプライン統合

4. マルチアカウント・マルチリージョン配布

  • Image Sharing 機能:組織全体への自動配布
  • タグ伝播:親イメージタグの 自動継承・カスタムタグ追加

学習リソース・参考文献

AWS 公式ドキュメント(8+)

  1. EC2 Image Builder User Guide
  2. EC2 Image Builder API Reference
  3. STIG Hardening Components
  4. CIS Hardening Benchmarks
  5. Component Language Reference
  6. Image Builder Best Practices
  7. AWSTOE Documentation
  8. Image Builder Pricing

セキュリティ・コンプライアンスリソース(5+)

  1. STIG-Compliant AMI Building
  2. CIS Benchmarks for ECS
  3. EKS Optimized AMI with STIG
  4. Image Builder Workshop
  5. Compliance as Code

実装例・チェックリスト

本番環境運用チェックリスト

  • [ ] Image Recipe:バージョン管理・タグ付け・説明記載
  • [ ] コンポーネント:STIG/CIS コンポーネント必須・カスタムテスト実装
  • [ ] Infrastructure Configuration:IAM ロール・KMS 暗号化・VPC セキュリティグループ
  • [ ] Distribution Configuration:マルチリージョン・マルチアカウント設定
  • [ ] Image Pipeline:スケジュール設定・テスト有効化・タイムアウト設定
  • [ ] 監視・ログ:CloudWatch・CloudTrail・S3 ビルドログ
  • [ ] 自動化:EventBridge で Launch Template 自動更新
  • [ ] バージョン管理:Git / CodeCommit で Pipeline・Recipe・Component 管理
  • [ ] テスト検証:セキュリティテスト・機能テスト・パフォーマンステスト実施
  • [ ] ドキュメント:Pipeline・Component・テスト項目の詳細ドキュメント作成

まとめ

Amazon EC2 Image Builder は 「セキュアなゴールデン AMI の自動ビルド・テスト・配布パイプライン」

主な利点

  • STIG・CIS コンプライアンス自動化
  • マルチリージョン・マルチアカウント配布
  • スケジュール実行で常時最新 AMI 維持
  • AWS ネイティブ(Packer 不要)
  • テスト統合で品質保証

2026 年の強化

  • STIG 2026 Q1・Windows Server 2025 対応
  • CIS Level 1・2 完全サポート
  • SLES Linux 追加対応
  • EventBridge・Parameter Store 統合

推奨アーキテクチャ

  • Parent Image → Image Recipe → Build + Test → Distribution →
  • Launch Template(自動更新) → Auto Scaling → 本番 EC2

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