Terraform을 사용하여 Agent Runtime 인스턴스를 선언적으로 프로비저닝하고 관리할 수 있습니다. Terraform으로 에이전트를 배포할 때는 공식 Google Cloud Terraform 프로바이더 (GA 프로바이더 또는 베타 프로바이더)를 사용하여 google_vertex_ai_reasoning_engine 리소스를 관리합니다.
이 페이지의 안내는 Agent Runtime으로 컨테이너화된 에이전트 배포 Codelab에 설명된 샘플 컨테이너화된 에이전트 구현에 해당합니다.
기본 요건
Terraform을 사용하여 에이전트를 배포하기 전에 다음 설정을 완료했는지 확인합니다.
- Terraform (버전 1.5.0 이상)을 설치하고 공식 HashiCorp Terraform 레지스트리 문서에서
google_vertex_ai_reasoning_engine리소스 (GA 제공업체 및 베타 제공업체)를 검토합니다. - 환경을 설정하고 Google Cloud Vertex AI API (
aiplatform.googleapis.com), Artifact Registry API (artifactregistry.googleapis.com), Cloud Build API (cloudbuild.googleapis.com)를 사용 설정합니다. 인증 정보를 사용하여 로컬 환경을 인증합니다. Google Cloud
gcloud auth application-default login애플리케이션 코드를 인프라 관리와 분리하려면 에이전트 작업공간을 전용 애플리케이션 및 Terraform 디렉터리로 구성합니다.
weather-agent-byoc/ ├── main.py # Python ADK agent entrypoint ├── requirements.txt # Python dependencies ├── Dockerfile # Container build definition └── terraform/ # Terraform configuration directory ├── main.tf # Agent Runtime resources and specifications ├── variables.tf # Project, region, and container variables └── outputs.tf # Resource name outputs애플리케이션 파일 (
main.py,requirements.txt,Dockerfile): 에이전트 로직, 웹 프레임워크 래퍼 (예: FastAPI 또는 ADK 앱), Python 종속 항목, 컨테이너 빌드 안내가 포함되어 있습니다.Terraform 디렉터리 (
terraform/): 리소스를 프로비저닝하는 데 사용되는 모든 Terraform 구성 파일이 포함되어 있습니다.variables.tf:project_id,location,repository_name,image_tag와 같은 입력 변수를 선언합니다.main.tf: 프로바이더 설정, 로컬 변수, IAM 역할 바인딩,google_vertex_ai_reasoning_engine리소스 사양을 선언합니다.outputs.tf: 배포 후 Agent Runtime ID 및 전체 리소스 이름과 같은 프로비저닝된 리소스 속성을 내보냅니다.
배포를 실행하는 사용자에 따라 적절한 IAM 역할을 부여합니다.
terraform apply및 로컬 빌드 명령어를 실행하는 인간 개발자 또는 CI/CD 서비스 계정입니다.시스템 관리형 Agent Runtime 서비스 에이전트 (
service-<var>PROJECT_NUMBER</var>@gcp-sa-aiplatform-re.iam.gserviceaccount.com).
배포 준비하기
Terraform은 Agent Runtime에 대해 다음과 같은 배포 경로를 지원합니다.
- 사전 빌드된 컨테이너 이미지에서 배포: 컨테이너 이미지를 사전 빌드하고 Artifact Registry (
{region}-docker.pkg.dev/...)에 푸시한 후container_spec을 사용하여 배포합니다. 컨테이너 빌드 프로세스, 커스텀 기본 이미지 또는 더 낮은 배포 지연 시간을 완전히 제어해야 하는 경우 이 메서드를 사용합니다. - 소스 파일 또는 Dockerfile에서 배포: 로컬 소스 파일 또는 Dockerfile에서 직접 에이전트를 배포합니다. Agent Runtime은 수동 이미지 관리 없이 컨테이너 이미지를 자동으로 빌드하고 프로비저닝합니다.
- Python 패키지 사양을 사용하여 배포 Cloud Storage에 스테이징된 (
package_spec)을 사용하여 배포합니다. Agent Runtime은 수동 이미지 관리 없이 컨테이너 이미지를 자동으로 빌드하고 프로비저닝합니다.
사전 빌드된 컨테이너 이미지에서 배포
컨테이너 이미지를 사전 빌드하고 Artifact Registry에 푸시하는 경우 (예: 커스텀 시스템 라이브러리를 포함하거나, 콜드 스타트 성능을 최적화하거나, 조직 이미지 빌드 제어를 적용하기 위해) container_spec을 사용하여 배포할 수 있습니다. 이미지 요구사항에 대한 자세한 내용은 컨테이너 이미지에서 배포를 참조하세요.
컨테이너 이미지는 Artifact Registry ({LOCATION}-docker.pkg.dev/{PROJECT_ID}/{REPOSITORY}/{IMAGE}:{TAG})에 저장되고, 포트 8080 (또는 container_spec에 지정된 커스텀 포트)에서 수신 대기하며, 런타임 계약을 준수해야 합니다.
컨테이너 이미지를 로컬에서 빌드하고 Artifact Registry 저장소에 푸시합니다.
# 1. Authenticate Docker with your Artifact Registry region gcloud auth configure-docker us-central1-docker.pkg.dev# 2. Build the container image from your application root directory cd weather-agent-byoc docker build -t us-central1-docker.pkg.dev/PROJECT_ID/agents-repo/weather-agent-image:latest .# 3. Push the container image to Artifact Registry docker push us-central1-docker.pkg.dev/PROJECT_ID/agents-repo/weather-agent-image:latestTerraform 배포를 위해 사전 빌드된 컨테이너 이미지를 구성합니다. 다음 구성은
terraform/디렉터리에서variables.tf,main.tf,outputs.tf파일을 만들어 Artifact Registry에 호스팅된 사전 빌드된 컨테이너 이미지를 배포하는 방법을 보여줍니다.입력 변수 (
terraform/variables.tf)variable "project_id" { type = string description = "The Google Cloud Project ID" } variable "project_number" { type = string description = "The Google Cloud Project Number" } variable "location" { type = string default = "us-central1" description = "The region to deploy Agent Runtime" } variable "repository_name" { type = string default = "agents-repo" description = "The Artifact Registry repository name" } variable "image_tag" { type = string default = "latest" description = "The tag of the container image to deploy" }리소스 사양 (
terraform/main.tf)terraform { required_providers { google = { source = "hashicorp/google" version = ">= 5.28.0" } } } provider "google" { project = var.project_id region = var.location } locals { class_methods = [ { "name" = "get_session", "api_mode" = "" }, { "name" = "list_sessions", "api_mode" = "" }, { "name" = "create_session", "api_mode" = "" }, { "name" = "delete_session", "api_mode" = "" }, { "name" = "async_get_session", "api_mode" = "async" }, { "name" = "async_list_sessions", "api_mode" = "async" }, { "name" = "async_create_session", "api_mode" = "async" }, { "name" = "async_delete_session", "api_mode" = "async" }, { "name" = "async_add_session_to_memory", "api_mode" = "async" }, { "name" = "async_search_memory", "api_mode" = "async" }, { "name" = "stream_query", "api_mode" = "stream" }, { "name" = "async_stream_query", "api_mode" = "async_stream" }, { "name" = "streaming_agent_run_with_events", "api_mode" = "async_stream" } ] } # Grant Artifact Registry Reader permission to the Agent Runtime Service Agent resource "google_project_iam_member" "re_service_agent_ar_reader" { project = var.project_id role = "roles/artifactregistry.reader" member = "serviceAccount:service-${var.project_number}@gcp-sa-aiplatform-re.iam.gserviceaccount.com" } # Define the Agent Runtime resource with BYOC container configuration resource "google_vertex_ai_reasoning_engine" "byoc_weather_agent" { display_name = "byoc_weather_agent_tf" description = "BYOC weather agent deployed using Terraform" project = var.project_id location = var.location spec { agent_framework = "google-adk" container_spec { image_uri = "${var.location}-docker.pkg.dev/${var.project_id}/${var.repository_name}/weather-agent-image:${var.image_tag}" } class_methods = jsonencode(local.class_methods) } # Ensure service agent permission exists before provisioning to prevent IMAGE_PULL_BACKOFF depends_on = [google_project_iam_member.re_service_agent_ar_reader] }리소스 출력 (
terraform/outputs.tf)output "reasoning_engine_id" { value = google_vertex_ai_reasoning_engine.byoc_weather_agent.id description = "The ID of the deployed Agent Runtime instance" } output "reasoning_engine_resource_name" { value = google_vertex_ai_reasoning_engine.byoc_weather_agent.name description = "The resource name of the deployed Agent Runtime instance" }
Dockerfile 또는 소스 저장소에서 배포
Dockerfile에서 배포할 때는 source_code_spec에서 소스 보관 파일을 지정하고 빈 image_spec {} 블록을 설정하여 Agent Runtime이 Dockerfile을 사용하여 컨테이너 이미지를 빌드하도록 안내합니다. Dockerfile에서 빌드된 컨테이너는 런타임
계약을 준수해야 합니다.
배포 작동 방식에 대한 자세한 내용은 Dockerfile에서 배포 또는 소스 파일에서 배포를 참조하세요.
애플리케이션 코드 (
main.py), Python 종속 항목 매니페스트 (requirements.txt), 컨테이너 빌드 안내 (Dockerfile)를 gzip으로 압축된 tar 파일 보관 파일로 압축합니다.애플리케이션 루트 디렉터리에서 다음 명령어를 실행합니다 (예에서는 루트 디렉터리
weather-agent-byoc/및 tar 파일 보관 파일weather_agent_source.tar.gz를 사용함).cd weather-agent-byoc tar -czvf terraform/weather_agent_source.tar.gz main.py requirements.txt Dockerfileterraform/디렉터리에서variables.tf,main.tf,outputs.tf파일을 만듭니다.입력 변수 (
terraform/variables.tf)variable "project_id" { type = string description = "The Google Cloud Project ID" } variable "location" { type = string default = "us-central1" description = "The region to deploy Agent Runtime" }리소스 사양 (
terraform/main.tf)terraform { required_providers { google = { source = "hashicorp/google" version = ">= 5.28.0" } } } provider "google" { project = var.project_id region = var.location } resource "google_vertex_ai_reasoning_engine" "dockerfile_agent" { display_name = "dockerfile_weather_agent_tf" description = "BYOC weather agent deployed using Dockerfile" project = var.project_id location = var.location spec { agent_framework = "google-adk" source_code_spec { inline_source { source_archive = filebase64("weather_agent_source.tar.gz") } # Empty image_spec instructs the runtime to build using the Dockerfile image_spec {} } class_methods = jsonencode([ { "name" = "get_session", "api_mode" = "" }, { "name" = "list_sessions", "api_mode" = "" }, { "name" = "create_session", "api_mode" = "" }, { "name" = "delete_session", "api_mode" = "" }, { "name" = "async_get_session", "api_mode" = "async" }, { "name" = "async_list_sessions", "api_mode" = "async" }, { "name" = "async_create_session", "api_mode" = "async" }, { "name" = "async_delete_session", "api_mode" = "async" }, { "name" = "async_add_session_to_memory", "api_mode" = "async" }, { "name" = "async_search_memory", "api_mode" = "async" }, { "name" = "stream_query", "api_mode" = "stream" }, { "name" = "async_stream_query", "api_mode" = "async_stream" }, { "name" = "streaming_agent_run_with_events", "api_mode" = "async_stream" } ]) } }리소스 출력 (
terraform/outputs.tf)output "dockerfile_agent_id" { value = google_vertex_ai_reasoning_engine.dockerfile_agent.id description = "Resource ID of the deployed Dockerfile agent" }
Python 패키지 사양을 사용하여 배포
에이전트가 Python SDK 객체 또는 피클된 애플리케이션 (예:
ADK, LangChain 또는 커스텀 Python 에이전트)을 사용하여 빌드된 경우 직렬화된 에이전트
(.pkl) 및 종속 항목 구성 (requirements.txt)을 Cloud Storage
버킷에 스테이징하고 package_spec을 사용하여 참조할 수 있습니다.
배포 작동 방식에 대한 자세한 내용은 Python 객체에서 배포 를 참조하세요.
다음 Python 스크립트를 실행하여 에이전트를 직렬화하고 Cloud Storage에 배포 아티팩트를 스테이징합니다.
import cloudpickle from google.adk.agents import Agent from google.cloud import storage from vertexai.agent_engines import AdkApp PROJECT_ID = "PROJECT_ID" BUCKET_NAME = "BUCKET_NAME" GCS_DIR = "agents/weather_agent" # 1. Define agent logic root_agent = Agent( model="gemini-3.1-flash-lite", name="weather_agent", description="Agent deployed using Terraform package_spec.", ) local_app = AdkApp(agent=root_agent) # 2. Upload pickle to Cloud Storage storage_client = storage.Client(project=PROJECT_ID) bucket = storage_client.bucket(BUCKET_NAME) pkl_blob = bucket.blob(f"{GCS_DIR}/agent.pkl") with pkl_blob.open("wb") as f: cloudpickle.dump(local_app, f) # 3. Upload requirements.txt requirements_content = """google-cloud-aiplatform[agent_engines,adk]>=1.144 cloudpickle==3.0.0 """ req_blob = bucket.blob(f"{GCS_DIR}/requirements.txt") req_blob.upload_from_string(requirements_content) print(f"Artifacts uploaded to gs://{BUCKET_NAME}/{GCS_DIR}/")스테이징된 Cloud Storage URI를 참조하는
terraform/디렉터리에서variables.tf,main.tf,outputs.tf파일을 만듭니다.입력 변수 (
terraform/variables.tf)variable "project_id" { type = string description = "The Google Cloud Project ID" } variable "location" { type = string default = "us-central1" description = "The region to deploy Agent Runtime" } variable "bucket_name" { type = string description = "Cloud Storage bucket name containing agent artifacts" }리소스 사양 (
terraform/main.tf)terraform { required_providers { google = { source = "hashicorp/google" version = ">= 5.28.0" } } } provider "google" { project = var.project_id region = var.location } resource "google_vertex_ai_reasoning_engine" "package_agent" { display_name = "weather_agent_package_tf" description = "Agent Runtime instance deployed using package_spec" project = var.project_id location = var.location spec { agent_framework = "google-adk" package_spec { python_version = "3.11" pickle_object_gcs_uri = "gs://${var.bucket_name}/agents/weather_agent/agent.pkl" requirements_gcs_uri = "gs://${var.bucket_name}/agents/weather_agent/requirements.txt" } } }리소스 출력 (
terraform/outputs.tf)output "package_agent_id" { value = google_vertex_ai_reasoning_engine.package_agent.id description = "Resource ID of the deployed package agent" }
환경 변수 및 보안 비밀 구성
배포 전에 커스텀 런타임 서비스 계정을 에이전트에 연결하고 환경 변수 (env) 또는 Secret Manager 참조(secret_env)를 전달할 수 있습니다.
다음 예에서는 환경 변수 (LOCATION, MODEL,
MODEL_REGION)를 구성하고 Secret Manager에서
런타임 서비스 계정으로 API 키를 안전하게 전달합니다.terraform/main.tf
# 1. Dedicated Runtime Service Account
resource "google_service_account" "agent_runtime_sa" {
account_id = "agent-runtime-sa"
display_name = "Agent Runtime Identity"
project = var.project_id
}
# 2. Secret Manager Secret for Agent Credentials
resource "google_secret_manager_secret" "api_key_secret" {
secret_id = "agent-api-key"
project = var.project_id
replication {
auto {}
}
}
resource "google_secret_manager_secret_version" "api_key_version" {
secret = google_secret_manager_secret.api_key_secret.id
secret_data = var.api_key_value
}
# Grant Secret Accessor role to Runtime Service Account
resource "google_secret_manager_secret_iam_member" "secret_accessor" {
secret_id = google_secret_manager_secret.api_key_secret.id
role = "roles/secretmanager.secretAccessor"
member = "serviceAccount:${google_service_account.agent_runtime_sa.email}"
}
# Grant Artifact Registry Reader permission to the Agent Runtime Service Agent
resource "google_project_iam_member" "re_service_agent_ar_reader" {
project = var.project_id
role = "roles/artifactregistry.reader"
member = "serviceAccount:service-${var.project_number}@gcp-sa-aiplatform-re.iam.gserviceaccount.com"
}
# 3. Agent Runtime Resource with Environment Variables and Secret References
resource "google_vertex_ai_reasoning_engine" "advanced_weather_agent" {
display_name = "byoc_weather_agent_advanced_tf"
description = "BYOC weather agent with custom service account and secrets"
project = var.project_id
location = var.location
spec {
agent_framework = "google-adk"
service_account = google_service_account.agent_runtime_sa.email
container_spec {
image_uri = "${var.location}-docker.pkg.dev/${var.project_id}/${var.repository_name}/weather-agent-image:${var.image_tag}"
}
deployment_spec {
env {
name = "LOCATION"
value = var.location
}
env {
name = "MODEL"
value = "gemini-3.1-flash-lite"
}
env {
name = "MODEL_REGION"
value = "global"
}
secret_env {
name = "API_KEY"
secret_ref {
secret = google_secret_manager_secret.api_key_secret.secret_id
version = "latest"
}
}
}
class_methods = jsonencode([
{ "name" = "get_session", "api_mode" = "" },
{ "name" = "create_session", "api_mode" = "" },
{ "name" = "stream_query", "api_mode" = "stream" },
{ "name" = "async_stream_query", "api_mode" = "async_stream" }
])
}
depends_on = [
google_secret_manager_secret_iam_member.secret_accessor,
google_project_iam_member.re_service_agent_ar_reader
]
}
실행 및 수명 주기
표준 Terraform 수명 주기를 실행하여 에이전트 리소스를 계획, 배포, 호출, 폐기합니다.
Terraform 구성 적용
Terraform 구성을 적용하여 에이전트를 배포합니다.
Terraform 디렉터리로 변경합니다 (예:
cd weather-agent-byoc/terraform).cd weather-agent-byoc/terraform작업 디렉터리를 초기화합니다.
terraform init배포 계획을 미리 봅니다.
terraform plan -var="project_id=PROJECT_ID" -var="project_number=PROJECT_NUMBER"구성을 적용하여 에이전트를 프로비저닝합니다.
terraform apply -var="project_id=PROJECT_ID" -var="project_number=PROJECT_NUMBER"
배포된 에이전트 쿼리
Terraform이 google_vertex_ai_reasoning_engine 리소스를 프로비저닝한 후 HTTP POST 요청을 :streamQuery?alt=sse 엔드포인트로 전송하여 서버 전송 이벤트 (SSE)를 사용하여 응답 이벤트를 실시간으로 스트리밍합니다.
LOCATION="LOCATION" PROJECT_ID="PROJECT_ID" REASONING_ENGINE_ID="REASONING_ENGINE_ID"curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json; charset=utf-8" \ -d '{ "class_method": "async_stream_query", "input": { "user_id": "terraform_test_user", "message": "What is the temperature in Seattle?" } }' \ "https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/reasoningEngines/${REASONING_ENGINE_ID}:streamQuery?alt=sse"
- OAuth 액세스 토큰:
Authorization: Bearer $(gcloud auth print-access-token)은 로컬 인증 정보를 사용하여 수명이 짧은 OAuth 2.0 액세스 토큰을 생성합니다. Google Cloud - JSON
input봉투: 요청 본문에는input객체가 포함된 JSON 페이로드가 필요합니다.async_stream_query와 같은 명시적 클래스 메서드를 호출할 때는"input"과 함께"class_method"매개변수를 포함합니다. - 응답 페이로드: 응답은
data: { ... }서버 전송 이벤트 (SSE) 청크로 지속적으로 제공됩니다.
에이전트 리소스 폐기
리소스를 정리하고 예기치 않은 청구 요금을 방지하려면 terraform/ 디렉터리 (예: cd weather-agent-byoc/terraform)로 변경하고 terraform destroy를 실행합니다.
cd weather-agent-byoc/terraform
terraform destroy -var="project_id=PROJECT_ID" -var="project_number=PROJECT_NUMBER"다음 단계
- HashiCorp Terraform 레지스트리 —
google_vertex_ai_reasoning_engine(GA) - HashiCorp Terraform 레지스트리 —
google_vertex_ai_reasoning_engine(베타) - Google Cloud 생성형 AI — Agent Runtime Terraform 배포 튜토리얼 (GitHub)
- Google 개발자 포럼 — 엔터프라이즈 방식으로 Terraform을 사용하여 Agent Runtime 배포