Terraformで始めるAmazon Bedrock AgentCore ②〜Code Interpreter編〜

に公開

はじめに

Fusicのレオナです。本ブログはAmazon Bedrock AgentCoreをTerraformで構築してみたシリーズブログになります。今回はCode Interpreter編になります。

Amazon Bedrock AgentCoreとは

Amazon Bedrock AgentCoreは、2025年7月にPreview、10月にGAされたサービスです。AIエージェントを安全かつスケーラブルに運用するためのフルマネージド基盤で、実行環境(Runtime)・認証基盤(Identity)・Gateway・Memory・Code Interpreter・Browser・Observabilityのコンポーネントを備えています。GAに伴い、TerraformでIaCとして実装ができるようになりました。

Code Interpreter 概要

Code Interpreterコンポーネントは、AIエージェントがコードをサンドボックス環境で安全に実行できるようにするマネージドサービスです。

特徴 仕様
言語 Python, JavaScript, TypeScript
セッションタイムアウト デフォルト15分、最大8時間まで設定可能
ファイルサイズ インラインアップロード最大100MB、S3経由で最大5GB
セッションデータ保持 30日間のTTL

ネットワークモードの選択

Code Interpreterは、3つのネットワークモードがあります。

モード 説明 ユースケース
PUBLIC インターネットアクセス可能 外部APIへのアクセスが必要な場合
SANDBOX ネットワークアクセス不可 完全に隔離された環境でのコード実行
VPC VPC内のリソースにアクセス可能 RDSやElastiCacheなどのVPCリソースへのアクセス

本ブログでは、SANDBOX モードを使用します。

検証環境

  • Terraform: v1.13.4
  • AWS Provider: v6.20.0
  • Python: 3.12
  • Region: us-west-2

ディレクトリ構造

Code Interpreterモジュールを実装します。

root/
├── modules/
│   └── bedrock-agentcore-code-interpreter/      # Code Interpreter
│       ├── main.tf
│       ├── variables.tf
│       └── outputs.tf
├── envs/dev/                                    # 環境別設定
│   ├── main.tf
│   ├── iam.tf
│   ├── variables.tf
│   ├── outputs.tf
│   └── providers.tf
└── tests/
    └── 02_invoke_code_interpreter.py

0. 事前準備

前提条件

Code Interpreterを使用するには、 IAMロールの設定(Code Interpreter用の実行ロール)が必要です。

1. モジュール実装

1.1 Code Interpreterモジュール

modules/bedrock-agentcore-code-interpreter/main.tf
resource "aws_bedrockagentcore_code_interpreter" "this" {
  name               = var.name
  description        = var.description
  execution_role_arn = var.execution_role_arn

  network_configuration {
    network_mode = "SANDBOX"
  }

  tags = var.tags
}

ポイント:

  • network_mode: SANDBOXを明示的に指定
  • execution_role_arn: Code Interpreterが使用するIAMロール
modules/bedrock-agentcore-code-interpreter/variables.tf
variable "name" {
  description = "Name of the Bedrock AgentCore Code Interpreter."
  type        = string
}

variable "description" {
  description = "Optional description for the Code Interpreter."
  type        = string
  default     = ""
}

variable "execution_role_arn" {
  description = "IAM role ARN assumed by the Code Interpreter."
  type        = string
  default     = null
}

variable "tags" {
  description = "Tags applied to the Code Interpreter resource."
  type        = map(string)
  default     = {}
}

ポイント:

  • SANDBOXモード専用の構成
  • VPC関連の変数は不要
modules/bedrock-agentcore-code-interpreter/outputs.tf
output "code_interpreter_id" {
  description = "Identifier of the Code Interpreter."
  value       = aws_bedrockagentcore_code_interpreter.this.code_interpreter_id
}

output "code_interpreter_arn" {
  description = "ARN of the Code Interpreter."
  value       = aws_bedrockagentcore_code_interpreter.this.code_interpreter_arn
}

1.2 環境設定

envs/dev/main.tf
# Code Interpreter Module
module "code_interpreter" {
  source = "../../modules/bedrock-agentcore-code-interpreter"

  name               = var.code_interpreter_name
  description        = var.code_interpreter_description
  execution_role_arn = aws_iam_role.code_interpreter.arn
  tags               = var.tags
}

ポイント:

  • Code Interpreter専用のIAMロールを指定
  • SANDBOXモードはCode Interperterモジュール内で固定されているため、ここでの指定は不要
envs/dev/variables.tf
# AWS Configuration
variable "aws_profile" {
  description = "AWS CLI/SDK profile for deployment"
  type        = string
  default     = "default"
}

variable "aws_region" {
  description = "AWS region for deployment"
  type        = string
  default     = "us-west-2"
}

# Code Interpreter Configuration
variable "code_interpreter_name" {
  description = "Name assigned to the Bedrock AgentCore Code Interpreter."
  type        = string
  default     = "demo_code_interpreter"
}

variable "code_interpreter_description" {
  description = "Optional description for the Code Interpreter."
  type        = string
  default     = "Code interpreter for demo"
}

variable "tags" {
  description = "Tags to apply to resources"
  type        = map(string)
  default     = {}
}
envs/dev/outputs.tf
output "code_interpreter_id" {
  value       = module.code_interpreter.code_interpreter_id
  description = "Code Interpreter ID"
}
envs/dev/providers.tf
terraform {
  required_version = ">= 1.6.0"

  required_providers {
    aws = {
      source  = "hashicorp/aws"
      version = ">= 6.20.0"
    }
  }
}

provider "aws" {
  profile = var.aws_profile
  region  = var.aws_region
}

1.3 IAM設定

Code Interpreter用のIAMロールを作成します。

envs/dev/iam.tf
# IAM Role for Code Interpreter
resource "aws_iam_role" "code_interpreter" {
  name = "code-interpreter-execution-role"

  assume_role_policy = jsonencode({
    Version = "2012-10-17"
    Statement = [
      {
        Effect = "Allow"
        Principal = {
          Service = "bedrock-agentcore.amazonaws.com"
        }
        Action = "sts:AssumeRole"
      }
    ]
  })

  tags = var.tags
}

2. デプロイ

cd envs/dev
# 初期化
terraform init
# Planの確認
terraform plan -var="aws_profile=your-profile"
# デプロイ実行
terraform apply -var="aws_profile=your-profile"

実行結果:

code_interpreter_id = "demo_code_interpreter-oBBui5nTYa"

3. 動作確認

Code Interpreterはセッションベースで動作します。セッションを開始し、コードを実行し、セッションを停止する流れになります。

セッションのライフサイクル

1. start_code_interpreter_session  → セッション開始
2. invoke_code_interpreter         → コード実行(複数回可)
3. stop_code_interpreter_session   → セッション停止

利用可能なツール

ツール名 説明
executeCode コードを実行(Python, JavaScript, TypeScript)
executeCommand ターミナルコマンドを実行
startCommandExecution 非同期でコマンドを実行開始
getTask 非同期タスクの状態を取得
stopTask 非同期タスクを停止
writeFiles サンドボックス内にファイルを書き込み
readFiles サンドボックス内のファイルを読み取り
listFiles サンドボックス内のファイル一覧を取得
removeFiles サンドボックス内のファイルを削除

テストコード

tests/02_invoke_code_interpreter.py
"""Code Interpreter 動作確認テスト"""

import os
import subprocess
import uuid

import boto3


def terraform_output(name: str) -> str:
    """Terraform outputから値を取得"""
    return (
        subprocess.check_output(
            ["terraform", "-chdir=envs/dev", "output", "-raw", name],
            text=True,
        )
        .strip()
    )


def test_code_interpreter_basic():
    """基本的なコード実行テスト"""

    code_interpreter_id = os.environ.get(
        "CODE_INTERPRETER_ID", terraform_output("code_interpreter_id")
    )

    profile = os.getenv("AWS_PROFILE", "default")
    region = os.getenv("AWS_REGION", "us-west-2")

    session = boto3.Session(profile_name=profile)
    client = session.client("bedrock-agentcore", region_name=region)

    session_name = f"test-session-{uuid.uuid4().hex[:8]}"

    print("=== Code Interpreter Basic Test ===")
    print(f"Code Interpreter ID: {code_interpreter_id}")
    print(f"Session Name: {session_name}")
    print()

    # セッションを開始
    print("--- Starting Session ---")
    start_response = client.start_code_interpreter_session(
        codeInterpreterIdentifier=code_interpreter_id,
        name=session_name,
        sessionTimeoutSeconds=300,
    )
    session_id = start_response["sessionId"]
    print(f"Session ID: {session_id}")
    print()

    # コードを実行
    print("--- Executing Code ---")
    code = """
import math

# 基本的な計算
result = math.sqrt(144) + math.pi
print(f"Result: {result}")

# リスト操作
numbers = [1, 2, 3, 4, 5]
squared = [x**2 for x in numbers]
print(f"Squared: {squared}")
"""

    response = client.invoke_code_interpreter(
        codeInterpreterIdentifier=code_interpreter_id,
        sessionId=session_id,
        name="executeCode",
        arguments={
            "code": code,
            "language": "python",
        },
    )

    # ストリーミングレスポンスを処理
    print("Output:")
    for event in response.get("stream", []):
        if "result" in event:
            result = event["result"]
            structured = result.get("structuredContent", {})
            if structured.get("stdout"):
                print(structured["stdout"])

    print()

    # セッションを停止
    print("--- Stopping Session ---")
    client.stop_code_interpreter_session(
        codeInterpreterIdentifier=code_interpreter_id,
        sessionId=session_id,
    )
    print("Session stopped successfully")


if __name__ == "__main__":
    test_code_interpreter_basic()

実行方法

# AWS認証情報を設定
export AWS_PROFILE=your-profile
export AWS_REGION=us-west-2
# テスト実行(Code Interpreter IDはTerraform outputから自動取得)
uv run python tests/02_invoke_code_interpreter.py

実行結果

=== Code Interpreter Basic Test ===
Code Interpreter ID: demo_code_interpreter-oBBui5nTYa
Session Name: test-session-56e65d90

--- Starting Session ---
Session ID: 01KDC9HGCM54A0B7QJTQWR5ZXR

--- Executing Code ---
Output:
Result: 15.141592653589793
Squared: [1, 4, 9, 16, 25]

--- Stopping Session ---
Session stopped successfully

Pythonのテストコードがサンドボックス環境で正常に実行されました。

最後に

本ブログでは、TerraformでAmazon Bedrock AgentCoreのCode InterpreterをSANDBOX構築・実行する方法を解説しました。

次回予告

次回は、Browserの実装について解説します。
https://zenn.dev/fusic/articles/23d2b02673d7cf

Fusic 技術ブログ

Discussion