Cloud Run에서 Claude Agent SDK를 사용하여 자율 에이전트를 배포하는 방법

1. 소개

개요

AI 에이전트는 단순한 대화형 챗봇에서 bash 명령어를 실행하고, 단위 테스트를 실행하고, API를 쿼리하고, 소스 코드를 수정할 수 있는 자율 시스템으로 전환되고 있습니다. 이러한 워크로드를 프로덕션에서 안전하게 실행하려면 두 가지 핵심 아키텍처 과제가 있습니다.

  1. 코드 실행 안전성: LLM에서 생성된 신뢰할 수 없는 코드는 호스트 운영체제에서 직접 실행되거나 플랫폼 보안 비밀 및 사용자 인증 정보에 액세스해서는 안 됩니다.
  2. 상태 및 컴퓨팅 수명 주기: 에이전트 워크플로에는 영구적인 전용 작업공간(예: 장기 실행 개발자 환경, 대화형 터미널, 백그라운드 개발 서버) 또는 스테이트리스(Stateless) 이벤트 기반 Scale-to-Zero API(예: 수신 웹훅, 자동 문제 분류)가 필요할 수 있습니다.

이 Codelab에서는 Google Cloud Run에서 공식 Claude Agent SDK(claude-agent-sdk)를 사용하여 자율 AI 에이전트를 빌드하고 배포합니다. 이때 소프트웨어 격리 gVisor 코드 실행을 위해 샌드박스 템플릿(공개 프리뷰)과 함께 Cloud Run Sandboxes를 사용합니다.

다음 두 가지 배포 모델 중 하나를 사용하여 에이전트 하네스를 배포할 수 있습니다.

  • 경로 A: Cloud Run 인스턴스(공개 프리뷰 - 최대 7일 동안 전용 싱글톤 호스트, 결정론적 URL, 대화 전반에서 지속되는 /workspace 볼륨, 컴퓨팅 비용 월 약 11.40달러)
  • 경로 B: concurrency=1를 사용하는 Cloud Run 서비스(Scale-to-zero 서버리스, 요청당 지불, 유휴 컴퓨팅 비용 0달러, 임시 실행)

아키텍처: 브레인과 핸즈 분리

보안 경계를 설명하기 위해 '뇌와 손' 비유(공식 제품 용어가 아닌 설명용 정신 모델)를 사용합니다. 두 배포 경로 모두 뇌(호스트 컨테이너)가 손(샌드박스)에서 격리되는 엄격한 불변성을 적용합니다.

┌────────────────────────────────────────────────────────────────────────┐
│ Cloud Run Host Container (The Brain)                                   │
│ - FastAPI Web Server (POST /chat, IAM-authenticated by default)        │
│ - Claude Agent SDK (`claude-agent-sdk`, state in `/tmp/claude`)        │
│ - Calls Claude on Agent Platform using Cloud Run service account (ADC) │
│                                                                        │
│   │                                                                    │
│   ▼ Dispatches untrusted commands via In-Process MCP Tool              │
│                                                                        │
│ ┌──────────────────────────────────────────────────────────────────┐   │
│ │ Cloud Run Sandbox (The Hands)                                    │   │
│ │ - Spawned using `/usr/local/gcp/bin/sandbox do --template`       │   │
│ │ - Dedicated sibling container image (`sandboxes.templates`)      │   │
│ │ - Dedicated gVisor kernel; no access to host FS, env, or creds   │   │
│ │ - Writable per-sandbox overlay + configurable internet egress    │   │
│ └──────────────────────────────────────────────────────────────────┘   │
└────────────────────────────────────────────────────────────────────────┘

학습할 내용

  • Claude Agent SDK 및 프로세스 내 모델 컨텍스트 프로토콜(MCP) 도구를 사용하여 에이전트 하네스를 빌드하는 방법
  • /usr/local/gcp/bin/sandbox를 통해 신뢰할 수 없는 셸 명령어를 소프트웨어 격리 Cloud Run 샌드박스로 라우팅하는 방법
  • 스테이트풀니스 및 비용 목표에 따라 Cloud Run 인스턴스와 Cloud Run 서비스(concurrency=1) 중에서 선택하는 방법
  • 관리할 API 키 없이 애플리케이션 기본 사용자 인증 정보(ADC)를 사용하여 Agent Platform(CLAUDE_CODE_USE_VERTEX=1)으로 Claude Agent SDK를 인증하는 방법
  • 샌드박스 격리 및 아웃바운드 네트워크 연결을 확인하는 방법

2. 인스턴스 및 서비스

배포하기 전에 아래의 결정 매트릭스를 검토하여 타겟 워크로드에 가장 적합한 경로를 선택하세요.

아키텍처 측정항목

경로 A: Cloud Run 인스턴스

경로 B: Cloud Run 서비스(concurrency=1)

컴퓨팅 모델

전용 싱글톤 컨테이너(최대 7일 동안 지속적으로 실행)

임시 자동 확장 컨테이너 풀

확장 및 최대 인스턴스

단일 인스턴스(인스턴스 1개)

0에서 최대 --max-instances까지 확장(이 Codelab에서는 최대 동시 비용을 제한하기 위해 5로 설정)

유휴 비용

컴퓨팅 월 약$11.40(공유 CPU에서 vCPU 2개/2GiB)

$0.00(유휴 상태일 때 인스턴스 0개로 확장)

결제 세분화

인스턴스가 존재하는 동안 지속적으로 청구됨(Claude 토큰은 별도로 청구됨)

요청당 밀리초 단위로 청구(Claude 토큰은 별도로 청구)

URL 및 주소 지정

인스턴스별 전용 URL(https://INSTANCE_URL.run.app)

서비스 엔드포인트(https://SERVICE_URL.run.app), 기본적으로 세션 어피니티 없음(사용 설정 시 최선 노력)

라우팅 안정성

100% 결정론적 1:1 인스턴스 라우팅

자동 확장되는 Cloud Run 서비스 인스턴스 간에 부하 분산

샌드박스 및 호스트 상태

sandbox do --template는 명령어당 실행되며 차례 간에 공유 인메모리 /workspace 볼륨을 마운트합니다(최대 7일).

sandbox do --template는 명령어당 일시적으로 실행되며 유휴 상태일 때 인스턴스가 0으로 축소됩니다.

백그라운드 프로세스

호스트 또는 분리된 샌드박스 내부에서 지원됨(sandbox run --detach)

요청이 완료되면 제한되거나 정지됨

주요 사용 사례

개인 에이전트 어시스턴트, IDE 도우미, 코딩 봇

웹훅 핸들러, 이벤트 기반 파이프라인, 자동화된 문제 분류

어떤 경로를 선택해야 할까요?

  • 영구 호스트 작업공간(최대 7일)과 장기 실행 백그라운드 개발 서버가 필요한 단일 소유자 코딩 파트너 또는 개인 어시스턴트를 빌드하는 경우 경로 A(인스턴스)를 선택합니다. 또한 커스텀 라우팅 헤더 없이 도구 및 웹훅과 함께 작동하는 전용 URL도 제공됩니다.
  • 웹훅 엔드포인트(예: GitHub PR 봇 또는 Slack 봇), 자동화된 이벤트 기반 파이프라인을 빌드하거나 간헐적인 이벤트 사이에 서비스가 완전히 0으로 확장되는 유휴 비용이 없는 경우(--max-instances가 최대 동시 지출을 제한함) 경로 B(서비스)를 선택합니다.

(동일한 컨테이너 이미지를 사용하여 두 경로를 모두 완료하고 운영 메커니즘을 직접 비교할 수도 있습니다.)

3. 설정 및 요구사항

Google Cloud 프로젝트 설정 및 필수 역할

  1. Google Cloud 콘솔에 로그인합니다.
  2. 결제가 사용 설정된 Google Cloud 프로젝트를 선택하거나 만듭니다.
  3. 계정에 프로젝트에 대한 다음 IAM 역할이 있는지 확인합니다(Owner에 포함되거나 개별적으로 부여됨).
    • 인스턴스 및 서비스를 배포하기 위한 Cloud Run 개발자(roles/run.developer) 및 서비스 계정 사용자(roles/iam.serviceAccountUser)
    • 서비스 계정 관리자(roles/iam.serviceAccountAdmin), 서비스 사용량 관리자(roles/serviceusage.serviceUsageAdmin), 프로젝트 IAM 관리자(roles/resourcemanager.projectIamAdmin)를 사용하여 런타임 서비스 계정을 만들고, API를 사용 설정하고, IAM 역할을 부여합니다.
    • 소비자 조달 사용 권한 관리자(roles/consumerprocurement.entitlementManager): Model Garden에서 파트너 Claude 모델을 사용 설정합니다.

Cloud Shell 열기

Cloud 콘솔의 상단 탐색 메뉴에서 Google Cloud Shell을 활성화합니다.

IAM으로 보호되는 Cloud Run 엔드포인트를 테스트할 때 gcloud auth print-identity-token에서 OpenID Connect(OIDC) ID 토큰을 생성할 수 있도록 사용자 인증 정보를 인증합니다.

gcloud auth login

환경 변수 설정

프로젝트 ID, 배포 리전, 전용 런타임 서비스 계정 이름을 설정합니다. Cloud Shell 세션이 다시 연결되면 다음 export 명령어를 다시 실행하세요.

export PROJECT_ID="<YOUR_PROJECT_ID>"
export REGION="us-west1"
export SA_NAME="claude-agent-sa"
export RUN_SA="${SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com"

gcloud config set project ${PROJECT_ID}

gcloud 베타 설치(로컬 터미널만 해당)

Cloud Shell에는 gcloud beta가 이미 사전 설치되어 있습니다(구성요소 관리자가 사용 중지된 Cloud Shell에서는 이 단계 건너뛰기). 대신 로컬 터미널에서 실행하는 경우 beta를 설치하고 업데이트합니다.

gcloud components install beta --quiet
gcloud components update --quiet

필수 Google Cloud API 사용 설정

Cloud Run, Agent Platform(aiplatform.googleapis.com), IAM, Cloud Build, Artifact Registry API를 사용 설정합니다.

gcloud services enable \
  run.googleapis.com \
  aiplatform.googleapis.com \
  iam.googleapis.com \
  cloudbuild.googleapis.com \
  artifactregistry.googleapis.com

4. Agent Platform에서 Claude 사용 설정 및 IAM 구성

Claude Agent SDK는 정적 Anthropic API 키를 관리하는 대신 Cloud Run 서비스 계정의 애플리케이션 기본 사용자 인증 정보(ADC)를 사용하여 Agent Platform에 직접 인증할 수 있습니다.

1. Model Garden에서 Claude Sonnet 5.5 사용 설정

  1. Google Cloud 콘솔에서 Model Garden을 엽니다.
  2. Claude Sonnet 5.5(claude-sonnet-5-5) 또는 Claude Opus 5.5(claude-opus-5-5)를 검색하고 사용 설정을 클릭하여 프로젝트에 대한 Anthropic 파트너 약관에 동의합니다.

2. 전용 런타임 서비스 계정 만들기

Cloud Run 에이전트의 전용 런타임 서비스 계정을 만들고 Claude 모델을 호출할 수 있도록 Agent Platform 사용자(roles/aiplatform.user)를 부여합니다.

gcloud iam service-accounts create "${SA_NAME}" \
  --display-name="Claude Agent Runtime Service Account" \
  --project="${PROJECT_ID}" \
  --quiet

export RUN_SA="${SA_NAME}@${PROJECT_ID}.iam.gserviceaccount.com"

gcloud projects add-iam-policy-binding ${PROJECT_ID} \
  --member="serviceAccount:${RUN_SA}" \
  --role="roles/aiplatform.user"

3. 선택사항: 빌드하기 전에 Claude 액세스 확인

컨테이너를 빌드하기 전에 프로젝트에서 claude-sonnet-5-5가 사용 설정되어 있는지 확인하기 위해 빠른 테스트 요청을 전송합니다. 전체 API 응답 또는 오류 본문을 검사하려면 | jq '{content}'를 삭제합니다.

curl -sS --fail-with-body \
  -H "Authorization: Bearer $(gcloud auth print-access-token)" \
  -H "Content-Type: application/json" \
  "https://aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/global/publishers/anthropic/models/claude-sonnet-5-5:rawPredict" \
  -d @- << 'EOF' | jq '{content}'
{
  "anthropic_version": "vertex-2023-10-16",
  "max_tokens": 64,
  "messages": [
    {"role": "user", "content": "Reply with Hello! I'm Claude."}
  ]
}
EOF

예상 출력:

{
  "content": [
    {
      "type": "text",
      "text": "Hello! I'm Claude."
    }
  ]
}

5. 에이전트 애플리케이션 컨테이너 빌드

에이전트 소스 코드를 위한 빈 디렉터리를 만듭니다.

mkdir -p claude-agent-app && cd claude-agent-app

cat <<'EOF' 명령어를 사용하여 claude-agent-app에 파일 5개를 만듭니다. 이렇게 하면 Cloud Shell에서 각 블록을 직접 복사하고 실행할 수 있습니다.

  1. sandbox_runner.py: /usr/local/gcp/bin/sandbox를 래핑하여 셸 명령어를 gVisor 샌드박스로 전달합니다.
  2. agent.py: Claude Agent SDK를 인스턴스화하고 프로세스 내 bash 실행 MCP 도구를 구성합니다.
  3. server.py: POST /chat를 제공하는 경량 FastAPI 웹 서버입니다.
  4. requirements.txt: Python 패키지 종속 항목입니다.
  5. Dockerfile: FastAPI 호스트 런타임을 패키징하는 컨테이너 정의입니다.

1. sandbox_runner.py 만들기

이 모듈은 에이전트 하네스와 Cloud Run 샌드박스 런처 간의 실행 브리지를 제공합니다.

cat <<'EOF' > sandbox_runner.py
"""Sandbox Runner utilizing Cloud Run Sandbox launcher."""

from __future__ import annotations

import logging
import os
import subprocess
from dataclasses import dataclass

logger = logging.getLogger("sandbox-runner")


@dataclass
class ExecutionResult:
    stdout: str
    stderr: str
    exit_code: int


def _env_bool(name: str, default: bool) -> bool:
    raw = os.environ.get(name)
    if raw is None:
        return default
    return raw.strip().lower() in ("1", "true", "yes", "on")


class CloudRunSandboxRunner:
    """Dispatches shell commands into isolated gVisor sandbox templates."""

    def __init__(
        self,
        sandbox_bin: str = "/usr/local/gcp/bin/sandbox",
        template: str | None = None,
        default_allow_egress: bool | None = None,
    ):
        self.sandbox_bin = sandbox_bin
        self.template = (
            template
            if template is not None
            else os.environ.get("SANDBOX_TEMPLATE", "code-sandbox").strip()
        )
        self.default_allow_egress = (
            default_allow_egress
            if default_allow_egress is not None
            else _env_bool("SANDBOX_ALLOW_EGRESS", True)
        )
        self.is_available = os.path.exists(sandbox_bin) and os.access(
            sandbox_bin, os.X_OK
        )

    def execute(
        self,
        command: str,
        timeout: int = 60,
        allow_egress: bool | None = None,
    ) -> ExecutionResult:
        """Executes a command inside an ephemeral templated sandbox."""
        if not self.is_available:
            return ExecutionResult(
                stdout="",
                stderr="Cloud Run Sandbox binary is unavailable on this host.",
                exit_code=1,
            )
        if not self.template:
            return ExecutionResult(
                stdout="",
                stderr=(
                    "SANDBOX_TEMPLATE must be set to launch a sandbox template."
                ),
                exit_code=1,
            )

        egress = (
            self.default_allow_egress if allow_egress is None else allow_egress
        )
        cmd = [
            self.sandbox_bin,
            "do",
            "--stdin=false",
            "--template",
            self.template,
        ]
        if egress:
            cmd.append("--allow-egress")
        cmd.extend(["--", "/bin/sh", "-c", command])

        try:
            res = subprocess.run(
                cmd, capture_output=True, text=True, timeout=timeout, check=False
            )
            return ExecutionResult(
                stdout=res.stdout, stderr=res.stderr.strip(), exit_code=res.returncode
            )
        except subprocess.TimeoutExpired:
            return ExecutionResult(
                stdout="", stderr=f"Command timed out after {timeout} seconds.", exit_code=124
            )
        except Exception as e:
            logger.exception("Unexpected error during sandbox execution")
            return ExecutionResult(stdout="", stderr=str(e), exit_code=1)
EOF

2. agent.py 만들기

Claude 에이전트 하네스를 정의하고 셸 명령어를 샌드박스 실행기로 라우팅하는 execute_bash라는 인프로세스 MCP 도구를 등록합니다. tools=[]을 설정하면 Claude Code의 기본 제공 도구(Bash, Write, Edit 등)가 사용 중지되므로 execute_bash가 유일한 명령어 도구가 됩니다. 각 요청은 query()를 사용하여 하나의 Claude Agent SDK 세션을 완료까지 실행합니다.

cat <<'EOF' > agent.py
"""Claude Agent harness with in-process Cloud Run Sandbox tool."""

from __future__ import annotations

from typing import Any

from claude_agent_sdk import (
    ClaudeAgentOptions,
    ResultMessage,
    create_sdk_mcp_server,
    query,
    tool,
)
from sandbox_runner import CloudRunSandboxRunner

runner = CloudRunSandboxRunner()


@tool(
    "execute_bash",
    "Execute shell commands inside an isolated sandbox with internet egress.",
    {"command": str},
)
async def execute_bash(args: dict[str, Any]) -> dict[str, Any]:
    """Executes a command inside the gVisor sandbox and returns the combined output."""
    result = runner.execute(args["command"])
    output = []
    if result.stdout:
        output.append(result.stdout)
    if result.stderr:
        output.append(f"[STDERR]\n{result.stderr}")
    output.append(f"[Exit Code: {result.exit_code}]")
    return {"content": [{"type": "text", "text": "\n".join(output)}]}


class ClaudeAgent:
    """Runs one Claude Agent SDK session per prompt."""

    def __init__(self, options: ClaudeAgentOptions):
        self.options = options

    async def run(self, prompt: str) -> str:
        """Runs the agent loop to completion and returns Claude's final answer."""
        async for message in query(prompt=prompt, options=self.options):
            if isinstance(message, ResultMessage):
                if message.is_error:
                    raise RuntimeError(message.result or message.subtype)
                return message.result or ""
        raise RuntimeError("Claude Agent SDK ended without a result.")


def create_claude_agent() -> ClaudeAgent:
    """Initializes the Claude Agent with the sandbox as its only execution tool."""
    system_prompt = (
        "You are an autonomous AI coding assistant running on Google Cloud Run. "
        "You have access to a secure bash tool called 'execute_bash'. "
        "All bash commands run inside an isolated gVisor sandbox with outbound internet access. "
        "If /workspace exists, store persistent project files there across turns. "
        "Use this tool to explore the environment, execute Python code, compile programs, or run tests."
    )
    options = ClaudeAgentOptions(
        # Swap to another enabled Model Garden ID (e.g., "claude-opus-5-5") as needed.
        model="claude-sonnet-5-5",
        system_prompt=system_prompt,
        mcp_servers={"sandbox": create_sdk_mcp_server("sandbox", tools=[execute_bash])},
        allowed_tools=["mcp__sandbox__execute_bash"],
        # Disable Claude Code's built-in tools (Bash, Write, Edit, ...) so the
        # only way to run commands is through the sandboxed execute_bash tool.
        tools=[],
    )
    return ClaudeAgent(options)
EOF

3. server.py 만들기

POST /chat를 노출하는 깨끗한 FastAPI 서버를 만듭니다.

cat <<'EOF' > server.py
"""FastAPI endpoint serving the Claude Agent."""

from __future__ import annotations

import logging
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel

from agent import create_claude_agent

logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("claude-service")

app = FastAPI(title="Claude Agent Cloud Run Service")
agent = create_claude_agent()


class ChatRequest(BaseModel):
    prompt: str


class ChatResponse(BaseModel):
    response: str


@app.post("/chat", response_model=ChatResponse)
async def chat_endpoint(req: ChatRequest):
    if not req.prompt.strip():
        raise HTTPException(status_code=400, detail="Prompt must not be empty.")
    try:
        result = await agent.run(req.prompt)
        return ChatResponse(response=str(result))
    except Exception as e:
        logger.exception("Error during agent processing")
        raise HTTPException(status_code=500, detail=str(e))
EOF

4. requirements.txt 만들기

cat <<'EOF' > requirements.txt
fastapi>=0.110.0
uvicorn>=0.28.0
pydantic>=2.0.0
claude-agent-sdk>=0.1.81
anthropic[vertex]>=0.40.0
EOF

5. Dockerfile 만들기

cat <<'EOF' > Dockerfile
FROM python:3.11-slim

ENV PYTHONUNBUFFERED=1
ENV PORT=8080
# Store Claude Agent SDK session files in /tmp on the host container
# (defense-in-depth alongside sandbox template file system isolation).
ENV CLAUDE_CONFIG_DIR=/tmp/claude

WORKDIR /app

# Ensure CA certificates are present for TLS connections
RUN apt-get update && apt-get install -y --no-install-recommends \
    ca-certificates \
    && rm -rf /var/lib/apt/lists/*

COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

COPY . .

EXPOSE 8080

CMD ["uvicorn", "server:app", "--host", "0.0.0.0", "--port", "8080"]
EOF

6. 컨테이너 이미지 빌드 및 푸시

Artifact Registry Docker 저장소를 만듭니다(프로젝트에 agent-repo가 이미 있는 경우 아래의 빌드 명령어로 건너뜀).

gcloud artifacts repositories create agent-repo \
  --repository-format=docker \
  --location=${REGION} \
  --description="Repository for Claude Agent containers"

Cloud Build를 사용하여 FastAPI 호스트 컨테이너 이미지를 빌드하고 푸시합니다.

export IMAGE_URI="${REGION}-docker.pkg.dev/${PROJECT_ID}/agent-repo/claude-agent:latest"

gcloud builds submit --tag ${IMAGE_URI}

6. 경로 A: Cloud Run 인스턴스에 배포

경로 A: 전용 싱글톤 호스트(최대 7일)를 선택한 경우 이 단계를 따르세요. (그렇지 않은 경우 경로 B의 다음 섹션으로 바로 이동)

1. instance.yaml 만들기

전용 code-sandbox 템플릿과 공유 인메모리 /workspace 볼륨을 사용하여 instance.yaml를 만듭니다.

cat <<EOF > instance.yaml
apiVersion: run.googleapis.com/v1
kind: Instance
metadata:
  name: claude-agent-instance
  annotations:
    run.googleapis.com/launch-stage: BETA
spec:
  serviceAccountName: ${RUN_SA}
  containers:
  - image: ${IMAGE_URI}
    ports:
    - containerPort: 8080
    resources:
      limits:
        cpu: "2"
        memory: 2Gi
    sandboxLauncher: true
    volumeMounts:
    - name: workspace
      mountPath: /workspace
    env:
    - name: CLAUDE_CODE_USE_VERTEX
      value: "1"
    - name: ANTHROPIC_VERTEX_PROJECT_ID
      value: "${PROJECT_ID}"
    - name: CLOUD_ML_REGION
      value: "global"
    - name: SANDBOX_TEMPLATE
      value: "code-sandbox"
  volumes:
  - name: workspace
    emptyDir:
      medium: Memory
  sandboxes:
    templates:
    - name: code-sandbox
      image: python:3.11-slim
      volumeMounts:
      - name: workspace
        mountPath: /workspace
EOF

2. Cloud Run 인스턴스 배포

공개 프리뷰(run.googleapis.com/launch-stage: BETA) 중에는 샌드박스 템플릿(sandboxes.templates)이 gcloud CLI 플래그가 아닌 YAML을 사용하여 선언적으로 구성됩니다. gcloud beta run instances replace를 사용하여 instance.yaml에서 인스턴스를 배포합니다.

gcloud beta run instances replace instance.yaml --region ${REGION}

주요 파라미터 분류

  • serviceAccountName: 기본 Compute Engine 서비스 계정이 아닌 전용 claude-agent-sa 서비스 계정으로 호스트 컨테이너를 실행합니다.
  • sandboxLauncher: true: gVisor 샌드박스를 감독할 수 있도록 /usr/local/gcp/bin/sandbox를 호스트 컨테이너에 삽입합니다.
  • sandboxes.templates 및 volumes: code-sandbox 동위 컨테이너 이미지(python:3.11-slim)를 정의하고 호스트 컨테이너와 code-sandbox 모두에 공유 인메모리 emptyDir 볼륨(/workspace의 workspace, 인스턴스의 2 GiB 메모리 한도에 반영됨)을 마운트합니다. 각 sandbox do --template code-sandbox 호출은 새로운 /tmp 및 루트 오버레이를 가져오고, /app 또는 /tmp/claude에 액세스할 수 없으며, 최대 7일 동안 차례 간에 /workspace에 지속적으로 액세스할 수 있습니다.
  • IAM 인증(기본값): 호출자 IAM 검사를 사용 중지하지 않고 containerPort: 8080를 할당하면 Cloud Run IAM으로 보호되는 전용 HTTPS URL이 생성되어 constraints/run.managed.requireInvokerIam를 충족합니다.
  • env: 인스턴스의 서비스 계정 사용자 인증 정보를 사용하여 Agent Platform(global)에서 Claude를 호출하도록 Claude Agent SDK(CLAUDE_CODE_USE_VERTEX=1)를 구성하고 SANDBOX_TEMPLATE=code-sandbox를 설정합니다.
# Optional (personal, non-enterprise projects only):
gcloud beta run instances update claude-agent-instance \
  --region ${REGION} \
  --public

3. 인스턴스 URL 검색

export INSTANCE_URL=$(gcloud beta run instances describe claude-agent-instance \
  --region ${REGION} \
  --format="value(status.urls[0])")

echo "Instance URL: ${INSTANCE_URL}"

7. 경로 B: Cloud Run 서비스에 배포(동시 실행=1)

경로 B: Scale-to-Zero 서버리스를 선택한 경우 이 단계를 따르세요.

1. service.yaml 만들기

containerConcurrency: 1 및 전용 code-sandbox 템플릿을 사용하여 service.yaml를 만듭니다.

cat <<EOF > service.yaml
apiVersion: serving.knative.dev/v1
kind: Service
metadata:
  name: claude-agent-service
  annotations:
    run.googleapis.com/launch-stage: BETA
spec:
  template:
    metadata:
      annotations:
        autoscaling.knative.dev/minScale: "0"
        autoscaling.knative.dev/maxScale: "5"
        run.googleapis.com/execution-environment: gen2
    spec:
      serviceAccountName: ${RUN_SA}
      containerConcurrency: 1
      timeoutSeconds: 900
      containers:
      - image: ${IMAGE_URI}
        ports:
        - containerPort: 8080
        resources:
          limits:
            cpu: "2"
            memory: 2Gi
        sandboxLauncher: true
        env:
        - name: CLAUDE_CODE_USE_VERTEX
          value: "1"
        - name: ANTHROPIC_VERTEX_PROJECT_ID
          value: "${PROJECT_ID}"
        - name: CLOUD_ML_REGION
          value: "global"
        - name: SANDBOX_TEMPLATE
          value: "code-sandbox"
      sandboxes:
        templates:
        - name: code-sandbox
          image: python:3.11-slim
EOF

2. Cloud Run 서비스 배포

공개 프리뷰(run.googleapis.com/launch-stage: BETA) 중에는 샌드박스 템플릿(sandboxes.templates)이 gcloud beta run deploy 플래그가 아닌 YAML을 사용하여 선언적으로 구성됩니다. gcloud beta run services replace를 사용하여 service.yaml에서 서비스를 배포합니다.

gcloud beta run services replace service.yaml --region ${REGION}

주요 파라미터 분류

  • serviceAccountName: 기본 Compute Engine 서비스 계정이 아닌 전용 claude-agent-sa 서비스 계정으로 각 Cloud Run 서비스 인스턴스를 실행합니다.
  • containerConcurrency: 1: 각 Cloud Run 서비스 인스턴스가 한 번에 하나의 에이전트 차례만 처리하도록 보장하여 동시 샌드박스가 인스턴스의 2 vCPU/2GiB 예산을 두고 경합하지 않도록 합니다.
  • timeoutSeconds: 900: 요청당 HTTP 제한 시간을 기본값인 5분(300s)에서 15분(최대 3600s)으로 연장하여 여러 단계로 구성된 에이전트 실행이 중간에 타임아웃되지 않도록 합니다(Cloud Run 인스턴스의 기본값은 60분).
  • minScale: "0" 및 maxScale: "5": 유휴 상태일 때 CPU 요금이 $0.00이 되도록 0으로 축소하는 동시에 동시 Cloud Run 서비스 인스턴스를 제한하여 비용과 Claude API 할당량 사용량을 제한합니다.
  • execution-environment: gen2: 샌드박스 실행에 필요한 2세대 실행 환경을 선택합니다.
  • sandboxLauncher: true 및 sandboxes.templates: 샌드박스별 쓰기 가능한 오버레이가 있고 호스트 파일 시스템에 액세스할 수 없는 전용 python:3.11-slim 동위 컨테이너(code-sandbox)에서 각 명령어를 실행합니다.
  • IAM 인증(기본값): services replace로 새 서비스를 만들면 기본적으로 allUsers가 부여되지 않으므로 승인된 호출자만 에이전트를 호출할 수 있어 constraints/iam.allowedPolicyMemberDomains를 충족합니다.
  • env: 서비스 계정 사용자 인증 정보를 사용하여 Claude Agent SDK 호출(CLAUDE_CODE_USE_VERTEX=1)을 Agent Platform(global)으로 라우팅하고 SANDBOX_TEMPLATE=code-sandbox를 설정합니다.
# Optional (personal, non-enterprise projects only):
gcloud run services add-iam-policy-binding claude-agent-service \
  --region ${REGION} \
  --member="allUsers" \
  --role="roles/run.invoker"

3. 서비스 URL 가져오기

export SERVICE_URL=$(gcloud run services describe claude-agent-service \
  --region ${REGION} \
  --format="value(status.url)")

echo "Service URL: ${SERVICE_URL}"

8. 에이전트 테스트 및 샌드박스 격리 확인

완료한 배포 경로와 일치하는 블록만 실행하여 TARGET_URL를 설정합니다(curl를 실행하기 전에 출력된 URL이 비어 있지 않은지 확인).

  • 경로 A(Cloud Run 인스턴스)를 배포한 경우:
export TARGET_URL="${INSTANCE_URL}"
echo "Target URL: ${TARGET_URL}"
  • 경로 B(Cloud Run 서비스)를 배포한 경우:
export TARGET_URL="${SERVICE_URL}"
echo "Target URL: ${TARGET_URL}"

1. 커널 및 샌드박스 격리 확인

에이전트에게 커널 버전과 운영체제 환경을 확인하고 Google Cloud OIDC ID 토큰으로 인증하도록 요청합니다.

curl -X POST "${TARGET_URL}/chat" \
  -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Run uname -a and cat /etc/os-release using bash and report the kernel and distro."}'

예상 대답:

{
  "response": "The kernel is 4.19.0-gvisor and the distro is Debian GNU/Linux 13 (trixie)."
}

에이전트가 샌드박스 내에서 execute_bash 도구를 호출하고 python:3.11-slim Debian 배포와 함께 4.19.0-gvisor 샌드박스 커널을 보고하여 명령어가 호스트 커널이 아닌 격리된 샌드박스 내에서 실행됨을 확인합니다.

2. 아웃바운드 네트워크 이그레스 확인

에이전트에게 Python의 표준 라이브러리를 사용하여 python:3.11-slim 샌드박스 내에서 네트워크 이그레스를 확인하도록 요청합니다.

curl -X POST "${TARGET_URL}/chat" \
  -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Use execute_bash to fetch https://www.google.com with Python urllib.request and report the HTTP status code."}'

예상 대답:

{
  "response": "The HTTP response status from https://www.google.com is 200."
}

SANDBOX_ALLOW_EGRESS는 CloudRunSandboxRunner에서 기본적으로 true로 설정되므로 샌드박스는 안전하게 샌드박스 처리된 상태에서 종속 항목을 가져오고, Git 저장소를 다운로드하고, 공개 API를 쿼리할 수 있습니다(아웃바운드 네트워크 액세스를 차단하려면 SANDBOX_ALLOW_EGRESS=false 설정).

3. 호스트 파일 시스템, 환경, 스크립트 격리 확인

에이전트에게 샌드박스 내에서 호스트 컨테이너의 /app 디렉터리, /tmp/claude 세션 파일 또는 호스트 환경 변수를 볼 수 있는지 확인하도록 지시합니다.

curl -X POST "${TARGET_URL}/chat" \
  -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Run ls -la /app, ls -la /tmp, and env inside bash and tell me if you can see /app, /tmp/claude, ANTHROPIC_VERTEX_PROJECT_ID, or CLAUDE_CODE_USE_VERTEX."}'

예상 대답:

{
  "response": "ls: cannot access '/app': No such file or directory. /tmp is empty (no /tmp/claude), and neither ANTHROPIC_VERTEX_PROJECT_ID nor CLAUDE_CODE_USE_VERTEX is set in env."
}

에이전트는 /app가 존재하지 않고(No such file or directory), /tmp/claude가 없으며, 샌드박스 환경에 ANTHROPIC_VERTEX_PROJECT_ID와 CLAUDE_CODE_USE_VERTEX가 모두 없다고 보고합니다. --template code-sandbox는 자체 python:3.11-slim 이미지의 동위 컨테이너 내에서 각 명령어를 실행하므로 호스트 컨테이너의 파일 시스템, 사용자 인증 정보, 세션 스크립트가 브레인 내에서 격리된 상태로 유지됩니다.

4. 요청 간 영구 /workspace 확인(경로 A: 인스턴스)

경로 A(Cloud Run 인스턴스)를 배포한 경우 instance.yaml는 code-sandbox의 /workspace에 인메모리 emptyDir 볼륨을 마운트합니다. 두 개의 개별 HTTP 요청을 전송하여 /workspace에 작성된 파일이 임시 sandbox do 호출 간에 유지되는 반면 /tmp는 매번 재설정되는지 확인합니다.

# Request 1: Write one file to /workspace and one file to /tmp
curl -X POST "${INSTANCE_URL}/chat" \
  -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Use bash to write the current UTC timestamp to /workspace/session_note.txt and also write ephemeral to /tmp/ephemeral.txt, then confirm both files exist."}'

# Request 2: Read both files in a new request (new sandbox do invocation)
curl -X POST "${INSTANCE_URL}/chat" \
  -H "Authorization: Bearer $(gcloud auth print-identity-token)" \
  -H "Content-Type: application/json" \
  -d '{"prompt": "Use bash to check cat /workspace/session_note.txt and ls -la /tmp/ephemeral.txt and report which file persisted."}'

예상 응답(요청 2):

{
  "response": "/workspace/session_note.txt persisted with timestamp 2026-..., while /tmp/ephemeral.txt does not exist (No such file or directory)."
}

/workspace/session_note.txt는 메모리에서 대화 전반에 걸쳐 유지되지만(활성 Cloud Run 인스턴스에서 최대 7일), /tmp/ephemeral.txt는 요청 1의 sandbox do 컨테이너가 종료되는 즉시 삭제되었습니다.

9. 상태 및 샌드박스 세부사항(심층 분석)

Cloud Run 서비스에서 containerConcurrency: 1가 필수적인 이유

표준 스테이트리스(Stateless) 웹 애플리케이션은 Cloud Run 서비스 인스턴스당 80개 이상의 동시 요청을 처리합니다. 샌드박스를 실행하는 AI 에이전트의 경우 단일 요청 동시 실행이 중요합니다.

  1. 공유 인스턴스 CPU 및 메모리 예산: 샌드박스 템플릿 컨테이너는 동일한 Cloud Run 서비스 인스턴스 내에서 실행되며 2 vCPU 및 2GiB 메모리 할당을 공유합니다. containerConcurrency: 1를 설정하면 각 활성 에이전트 차례에 동시 컴파일러나 Python 런타임의 경합 없이 전체 인스턴스 CPU 및 메모리 예산을 받을 수 있습니다.
  2. 호스트 측 SDK 격리: 차례별 Claude Agent SDK 실행을 감독자 컨테이너에서 격리하여 동시 차례가 호스트 메모리나 스크래치 공간을 두고 경쟁하지 않도록 합니다.

샌드박스 템플릿, 엔드포인트 인증, 다중 사용자 세션 승인

  • 전용 샌드박스 루트 파일 시스템(sandboxes.templates): sandbox do --template code-sandbox를 실행하면 쓰기 가능한 샌드박스별 오버레이(기본적으로 --write=true)가 있는 전용 동위 컨테이너(python:3.11-slim)에서 각 명령어가 실행됩니다. 샌드박스는 호스트 컨테이너의 파일 시스템에 액세스할 수 없으므로 /app, Secret Manager 또는 Cloud Storage 볼륨 마운트, /tmp/claude 스크립트를 보호합니다. FastAPI 호스트 컨테이너에 컴파일러나 CLI를 추가하지 않고도 샌드박스 템플릿에서 최대 10개의 고유한 도구 이미지를 정의할 수 있습니다.
  • 엔드포인트 수준 액세스(Cloud Run IAM 및 IAP): 호출자 IAM 검사를 사용 설정하면 승인된 주 구성원(또는 IAP(Identity-Aware Proxy) 뒤에 있는 사용자)만 POST /chat에 도달할 수 있습니다. 경로 A(인스턴스)는 멀티테넌트 트래픽이 아닌 단일 소유자 개인 에이전트를 위한 단일 공유 호스트 환경을 실행합니다.
  • 다중 사용자 세션 소유권: 멀티턴 resume에 대해 session_id를 허용하도록 POST /chat를 확장하는 경우 Cloud Run IAM 및 IAP는 서비스를 호출할 수 있는 사용자만 확인합니다. 세션을 재개하기 전에 각 session_id를 앱에서 인증된 호출자의 ID에 바인딩합니다.

상태 지속성: 로컬 메모리 및 스냅샷 리하이드레이션 비교

  • 경로 A(인스턴스) - 세 가지 독립 상태 레이어:
    1. 샌드박스 /workspace 파일: 공유 인메모리 emptyDir 볼륨에서 최대 7일 동안 sandbox do 차례에 걸쳐 유지됩니다(인스턴스의 2GiB 메모리 한도에 반영됨). 반면 /tmp 및 루트 오버레이 쓰기는 모든 명령어 후에 재설정됩니다.
    2. 장기 실행 백그라운드 프로세스: sandbox do는 각 명령어 후에 종료되므로 샌드박스 내의 개발 서버 또는 감시자에는 분리된 샌드박스(sandbox exec가 있는 sandbox run --detach)가 필요합니다.
    3. 멀티턴 대화 기록: query()는 기본적으로 새로운 프롬프트 차례를 시작합니다. resume(또는 ClaudeSDKClient)를 전달하거나 스크립트를 외부 저장소에 유지하여 요청 간에 채팅 기록을 전달합니다.
  • 경로 B(서비스): 트래픽이 중단된 후 Cloud Run 서비스 인스턴스가 0으로 축소되면 로컬 디스크 및 메모리 상태가 삭제됩니다. 멀티턴 파일과 세션 상태를 외부 저장소(예: Cloud Storage, Firestore, Cloud Spanner)에 저장하고 각 턴이 시작될 때 다시 로드합니다.

10. 삭제

Google Cloud 요금이 계속 청구되지 않도록 하려면(특히 삭제할 때까지 월 약 11.40달러가 청구되는 경로 A) 만든 리소스를 삭제하세요.

  • 경로 A(Cloud Run 인스턴스)를 배포한 경우:
gcloud beta run instances delete claude-agent-instance --region ${REGION}
  • 경로 B(Cloud Run 서비스)를 배포한 경우:
gcloud run services delete claude-agent-service --region ${REGION}
  • Artifact Registry 저장소(두 경로 모두)를 삭제합니다.
gcloud artifacts repositories delete agent-repo --location ${REGION}
  • 전용 서비스 계정 및 IAM 바인딩 삭제(두 경로 모두):
gcloud projects remove-iam-policy-binding ${PROJECT_ID} \
  --member="serviceAccount:${RUN_SA}" \
  --role="roles/aiplatform.user"
gcloud iam service-accounts delete "${RUN_SA}" --project="${PROJECT_ID}"

11. 축하합니다

Google Cloud Run에서 Claude Sonnet 5.5 및 Claude Agent SDK를 기반으로 하는 자율 AI 에이전트를 배포했습니다.

실습한 내용

  • Brain versus Hands 아키텍처 분리를 사용하여 강화된 에이전트 하네스를 빌드했습니다.
  • 신뢰할 수 없는 bash 명령어를 gVisor를 실행하는 소프트웨어 격리 Cloud Run 샌드박스(sandboxes.templates)로 라우팅했습니다.
  • 애플리케이션 기본 사용자 인증 정보와 Agent Platform 사용자(roles/aiplatform.user) 역할을 사용하여 키 없는 Agent Platform 인증(CLAUDE_CODE_USE_VERTEX=1)을 구성했습니다.
  • Cloud Run 인스턴스(전용 URL, 최대 7일 동안 유지되는 영구 인메모리 /workspace 볼륨, 월 약 11.40달러의 컴퓨팅 비용)와 Cloud Run 서비스(concurrency=1)(Scale-to-zero, 이벤트 기반, maxScale로 제한) 간의 장단점을 살펴봤습니다.