bedrock-agentcore-deployment
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseAmazon Bedrock AgentCore Deployment
Amazon Bedrock AgentCore 部署方案
Overview
概述
Deploy AI agents to Amazon Bedrock AgentCore using multiple approaches: starter toolkit for rapid deployment, direct code deployment for customization, and container deployment for complex dependencies. Includes CI/CD patterns and infrastructure as code.
Purpose: Deploy agents from development to production with best practices
Pattern: Workflow-based (4 deployment methods)
Key Principles (validated by AWS December 2025):
- Zero Infrastructure - Managed compute, no servers to manage
- arm64 Architecture - All deployments use arm64
- Session Isolation - Complete isolation between sessions
- Multiple Entry Points - SDK decorator or REST endpoints
- Observability Built-in - CloudWatch and OTel integration
- Framework Agnostic - Works with any Python agent framework
Quality Targets:
- Deployment time: < 5 minutes
- Cold start: < 2 seconds
- Package size: 250MB (zip), 750MB (unzipped)
通过多种方式将AI Agent部署到Amazon Bedrock AgentCore:用于快速部署的入门工具包、用于自定义的直接代码部署,以及用于复杂依赖项的容器部署。同时包含CI/CD模式和基础设施即代码方案。
用途:遵循最佳实践将Agent从开发环境部署到生产环境
模式:基于工作流(4种部署方法)
核心原则(经AWS 2025年12月验证):
- 零基础设施管理 - 托管式计算,无需管理服务器
- arm64架构 - 所有部署均采用arm64
- 会话隔离 - 会话之间完全隔离
- 多入口点 - SDK装饰器或REST端点
- 内置可观测性 - 集成CloudWatch和OTel
- 框架无关 - 兼容任意Python Agent框架
质量指标:
- 部署时间:< 5分钟
- 冷启动时间:< 2秒
- 包大小:250MB(压缩包),750MB(解压后)
When to Use
适用场景
Use bedrock-agentcore-deployment when:
- Deploying agent code to production
- Setting up CI/CD pipelines for agents
- Migrating from development to production
- Managing multiple agent versions
- Implementing blue-green deployments
When NOT to Use:
- Local development/testing (use local server)
- Standard Bedrock Agents with action groups
在以下场景中使用bedrock-agentcore-deployment:
- 将Agent代码部署到生产环境
- 为Agent搭建CI/CD流水线
- 从开发环境迁移到生产环境
- 管理多个Agent版本
- 实现蓝绿部署
不适用场景:
- 本地开发/测试(使用本地服务器)
- 带操作组的标准Bedrock Agents
Prerequisites
前置条件
Required
必需项
- AWS account with AgentCore access
- Python 3.10+ (recommended: 3.13)
- IAM role with AgentCore permissions
- Foundation model access enabled
- 拥有AgentCore访问权限的AWS账户
- Python 3.10+(推荐版本:3.13)
- 拥有AgentCore权限的IAM角色
- 已启用基础模型访问权限
Recommended
推荐项
- AWS CLI configured
- Docker (for container deployments)
- GitHub Actions or GitLab CI (for CI/CD)
- 已配置AWS CLI
- Docker(用于容器部署)
- GitHub Actions或GitLab CI(用于CI/CD)
Deployment Method 1: Starter Toolkit (Fastest)
部署方法1:入门工具包(最快)
Time: 2-5 minutes
Complexity: Low
Best For: Rapid deployment, simple agents
耗时:2-5分钟
复杂度:低
最佳适用:快速部署、简单Agent
Step 1: Install Toolkit
步骤1:安装工具包
bash
pip install bedrock-agentcore strands-agents bedrock-agentcore-starter-toolkitbash
pip install bedrock-agentcore strands-agents bedrock-agentcore-starter-toolkitVerify
验证
agentcore --help
undefinedagentcore --help
undefinedStep 2: Create Agent
步骤2:创建Agent
python
undefinedpython
undefinedmain.py
main.py
from bedrock_agentcore import BedrockAgentCoreApp
from strands import Agent
app = BedrockAgentCoreApp()
agent = Agent(model="anthropic.claude-sonnet-4-20250514-v1:0")
@app.entrypoint
def invoke(payload):
prompt = payload.get("prompt", "Hello!")
result = agent(prompt)
return {"response": result.message}
if name == "main":
app.run()
undefinedfrom bedrock_agentcore import BedrockAgentCoreApp
from strands import Agent
app = BedrockAgentCoreApp()
agent = Agent(model="anthropic.claude-sonnet-4-20250514-v1:0")
@app.entrypoint
def invoke(payload):
prompt = payload.get("prompt", "Hello!")
result = agent(prompt)
return {"response": result.message}
if name == "main":
app.run()
undefinedStep 3: Configure
步骤3:配置
bash
undefinedbash
undefinedInitialize configuration
初始化配置
agentcore configure -e main.py -n my-production-agent
agentcore configure -e main.py -n my-production-agent
This creates .bedrock_agentcore.yaml
此命令会生成.bedrock_agentcore.yaml文件
undefinedundefinedStep 4: Test Locally
步骤4:本地测试
bash
undefinedbash
undefinedStart local server
启动本地服务器
python main.py &
python main.py &
Test
测试
curl -X POST http://localhost:8080/invocations
-H "Content-Type: application/json"
-d '{"prompt": "Hello, world!"}'
-H "Content-Type: application/json"
-d '{"prompt": "Hello, world!"}'
curl -X POST http://localhost:8080/invocations
-H "Content-Type: application/json"
-d '{"prompt": "Hello, world!"}'
-H "Content-Type: application/json"
-d '{"prompt": "Hello, world!"}'
Stop local server
停止本地服务器
pkill -f main.py
undefinedpkill -f main.py
undefinedStep 5: Deploy
步骤5:部署到AWS
bash
undefinedbash
undefinedDeploy to AWS
部署到AWS
agentcore deploy
agentcore deploy
Output: Agent ARN
输出:Agent ARN
arn:aws:bedrock-agentcore:us-east-1:123456789012:agent-runtime/my-production-agent
arn:aws:bedrock-agentcore:us-east-1:123456789012:agent-runtime/my-production-agent
undefinedundefinedStep 6: Test Deployed
步骤6:测试已部署的Agent
bash
undefinedbash
undefinedTest via CLI
通过CLI测试
agentcore invoke '{"prompt": "Hello from production!"}'
agentcore invoke '{"prompt": "Hello from production!"}'
Test via boto3
通过boto3测试
python -c "
import boto3
client = boto3.client('bedrock-agentcore')
response = client.invoke_agent_runtime(
agentRuntimeArn='arn:...',
runtimeSessionId='test-1',
payload={'prompt': 'Hello!'}
)
print(response['payload'])
"
---python -c "
import boto3
client = boto3.client('bedrock-agentcore')
response = client.invoke_agent_runtime(
agentRuntimeArn='arn:...',
runtimeSessionId='test-1',
payload={'prompt': 'Hello!'}
)
print(response['payload'])
"
---Deployment Method 2: Direct Code Deploy
部署方法2:直接代码部署
Time: 10-15 minutes
Complexity: Medium
Best For: Custom dependencies, specific configurations
耗时:10-15分钟
复杂度:中
最佳适用:自定义依赖项、特定配置
Step 1: Project Structure
步骤1:项目结构
my-agent/
├── main.py # Entry point
├── agent/
│ ├── __init__.py
│ └── logic.py # Agent logic
├── pyproject.toml # Dependencies
└── requirements.txt # Alternative deps formatmy-agent/
├── main.py # 入口文件
├── agent/
│ ├── __init__.py
│ └── logic.py # Agent逻辑代码
├── pyproject.toml # 依赖配置
└── requirements.txt # 依赖配置的替代格式Step 2: Create Entry Point
步骤2:创建入口文件
python
undefinedpython
undefinedmain.py - REST endpoint pattern
main.py - REST端点模式
from flask import Flask, request, jsonify
app = Flask(name)
@app.route('/invocations', methods=['POST'])
def invoke():
payload = request.get_json()
prompt = payload.get('prompt', '')
# Your agent logic here
from agent.logic import process_request
result = process_request(prompt)
return jsonify({'response': result})@app.route('/ping', methods=['GET'])
def ping():
return 'OK', 200
if name == 'main':
app.run(host='0.0.0.0', port=8080)
undefinedfrom flask import Flask, request, jsonify
app = Flask(name)
@app.route('/invocations', methods=['POST'])
def invoke():
payload = request.get_json()
prompt = payload.get('prompt', '')
# 在此处添加你的Agent逻辑
from agent.logic import process_request
result = process_request(prompt)
return jsonify({'response': result})@app.route('/ping', methods=['GET'])
def ping():
return 'OK', 200
if name == 'main':
app.run(host='0.0.0.0', port=8080)
undefinedStep 3: Package for arm64
步骤3:为arm64架构打包
bash
undefinedbash
undefinedCreate virtual environment
创建虚拟环境
uv init agent-deploy --python 3.13
cd agent-deploy
uv init agent-deploy --python 3.13
cd agent-deploy
Install dependencies for arm64
为arm64安装依赖
uv pip install
--python-platform aarch64-manylinux2014
--python-version 3.13
--target=deployment_package
--only-binary=:all:
-r requirements.txt
--python-platform aarch64-manylinux2014
--python-version 3.13
--target=deployment_package
--only-binary=:all:
-r requirements.txt
uv pip install
--python-platform aarch64-manylinux2014
--python-version 3.13
--target=deployment_package
--only-binary=:all:
-r requirements.txt
--python-platform aarch64-manylinux2014
--python-version 3.13
--target=deployment_package
--only-binary=:all:
-r requirements.txt
Create ZIP
创建ZIP包
cd deployment_package
zip -r ../deployment_package.zip .
cd ..
cd deployment_package
zip -r ../deployment_package.zip .
cd ..
Add main.py
添加main.py
zip deployment_package.zip main.py
zip deployment_package.zip main.py
Add agent module
添加agent模块
zip -r deployment_package.zip agent/
undefinedzip -r deployment_package.zip agent/
undefinedStep 4: Upload to S3
步骤4:上传到S3
bash
aws s3 cp deployment_package.zip s3://my-bucket/agents/v1.0.0/package.zipbash
aws s3 cp deployment_package.zip s3://my-bucket/agents/v1.0.0/package.zipStep 5: Create Agent Runtime
步骤5:创建Agent Runtime
python
import boto3
control = boto3.client('bedrock-agentcore-control')
response = control.create_agent_runtime(
name='my-custom-agent',
description='Production agent with custom dependencies',
agentRuntimeArtifact={
's3': {
'uri': 's3://my-bucket/agents/v1.0.0/package.zip'
}
},
roleArn='arn:aws:iam::123456789012:role/AgentCoreExecutionRole',
pythonRuntime='PYTHON_3_13',
entryPoint=['main.py'],
environmentVariables={
'LOG_LEVEL': 'INFO',
'CUSTOM_CONFIG': 'production'
}
)
agent_arn = response['agentRuntimeArn']
print(f"Deployed: {agent_arn}")python
import boto3
control = boto3.client('bedrock-agentcore-control')
response = control.create_agent_runtime(
name='my-custom-agent',
description='Production agent with custom dependencies',
agentRuntimeArtifact={
's3': {
'uri': 's3://my-bucket/agents/v1.0.0/package.zip'
}
},
roleArn='arn:aws:iam::123456789012:role/AgentCoreExecutionRole',
pythonRuntime='PYTHON_3_13',
entryPoint=['main.py'],
environmentVariables={
'LOG_LEVEL': 'INFO',
'CUSTOM_CONFIG': 'production'
}
)
agent_arn = response['agentRuntimeArn']
print(f"Deployed: {agent_arn}")Deployment Method 3: Container Deploy
部署方法3:容器部署
Time: 15-30 minutes
Complexity: High
Best For: Complex dependencies, custom runtimes, large packages
耗时:15-30分钟
复杂度:高
最佳适用:复杂依赖项、自定义运行时、大型包
Step 1: Create Dockerfile
步骤1:创建Dockerfile
dockerfile
undefineddockerfile
undefinedDockerfile
Dockerfile
FROM public.ecr.aws/lambda/python:3.13-arm64
FROM public.ecr.aws/lambda/python:3.13-arm64
Install dependencies
安装依赖
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
Copy agent code
复制Agent代码
COPY main.py .
COPY agent/ agent/
COPY main.py .
COPY agent/ agent/
Set entry point
设置入口点
ENV PORT=8080
EXPOSE 8080
CMD ["main.py"]
undefinedENV PORT=8080
EXPOSE 8080
CMD ["main.py"]
undefinedStep 2: Build Image
步骤2:构建镜像
bash
undefinedbash
undefinedLogin to ECR
登录ECR
aws ecr get-login-password --region us-east-1 |
docker login --username AWS --password-stdin 123456789012.dkr.ecr.us-east-1.amazonaws.com
docker login --username AWS --password-stdin 123456789012.dkr.ecr.us-east-1.amazonaws.com
aws ecr get-login-password --region us-east-1 |
docker login --username AWS --password-stdin 123456789012.dkr.ecr.us-east-1.amazonaws.com
docker login --username AWS --password-stdin 123456789012.dkr.ecr.us-east-1.amazonaws.com
Build for arm64
为arm64架构构建
docker buildx build
--platform linux/arm64
-t 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-agent:v1.0.0
--push .
--platform linux/arm64
-t 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-agent:v1.0.0
--push .
undefineddocker buildx build
--platform linux/arm64
-t 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-agent:v1.0.0
--push .
--platform linux/arm64
-t 123456789012.dkr.ecr.us-east-1.amazonaws.com/my-agent:v1.0.0
--push .
undefinedStep 3: Create Agent Runtime
步骤3:创建Agent Runtime
python
response = control.create_agent_runtime(
name='my-container-agent',
description='Agent deployed via container',
agentRuntimeArtifact={
'container': {
'imageUri': '123456789012.dkr.ecr.us-east-1.amazonaws.com/my-agent:v1.0.0'
}
},
roleArn='arn:aws:iam::123456789012:role/AgentCoreExecutionRole'
)python
response = control.create_agent_runtime(
name='my-container-agent',
description='Agent deployed via container',
agentRuntimeArtifact={
'container': {
'imageUri': '123456789012.dkr.ecr.us-east-1.amazonaws.com/my-agent:v1.0.0'
}
},
roleArn='arn:aws:iam::123456789012:role/AgentCoreExecutionRole'
)Deployment Method 4: Infrastructure as Code (Terraform)
部署方法4:基础设施即代码(Terraform)
Time: 20-30 minutes setup, then automated
Complexity: High
Best For: Production environments, team deployments
耗时:20-30分钟配置,之后可自动化部署
复杂度:高
最佳适用:生产环境、团队协作部署
Terraform Configuration
Terraform配置
hcl
undefinedhcl
undefinedmain.tf
main.tf
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
terraform {
required_providers {
aws = {
source = "hashicorp/aws"
version = "~> 5.0"
}
}
}
provider "aws" {
region = "us-east-1"
}
IAM Role for Agent
Agent的IAM角色
resource "aws_iam_role" "agentcore_execution" {
name = "agentcore-execution-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "bedrock-agentcore.amazonaws.com"
}
}]
})
}
resource "aws_iam_role_policy" "agentcore_policy" {
name = "agentcore-policy"
role = aws_iam_role.agentcore_execution.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = [
"bedrock:InvokeModel",
"bedrock:InvokeModelWithResponseStream"
]
Resource = "arn:aws:bedrock:::foundation-model/"
},
{
Effect = "Allow"
Action = [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
]
Resource = ""
},
{
Effect = "Allow"
Action = [
"s3:GetObject"
]
Resource = "${aws_s3_bucket.agent_artifacts.arn}/"
}
]
})
}
resource "aws_iam_role" "agentcore_execution" {
name = "agentcore-execution-role"
assume_role_policy = jsonencode({
Version = "2012-10-17"
Statement = [{
Action = "sts:AssumeRole"
Effect = "Allow"
Principal = {
Service = "bedrock-agentcore.amazonaws.com"
}
}]
})
}
resource "aws_iam_role_policy" "agentcore_policy" {
name = "agentcore-policy"
role = aws_iam_role.agentcore_execution.id
policy = jsonencode({
Version = "2012-10-17"
Statement = [
{
Effect = "Allow"
Action = [
"bedrock:InvokeModel",
"bedrock:InvokeModelWithResponseStream"
]
Resource = "arn:aws:bedrock:::foundation-model/"
},
{
Effect = "Allow"
Action = [
"logs:CreateLogGroup",
"logs:CreateLogStream",
"logs:PutLogEvents"
]
Resource = ""
},
{
Effect = "Allow"
Action = [
"s3:GetObject"
]
Resource = "${aws_s3_bucket.agent_artifacts.arn}/"
}
]
})
}
S3 Bucket for Agent Artifacts
用于存储Agent制品的S3桶
resource "aws_s3_bucket" "agent_artifacts" {
bucket = "my-agentcore-artifacts-${data.aws_caller_identity.current.account_id}"
}
resource "aws_s3_bucket" "agent_artifacts" {
bucket = "my-agentcore-artifacts-${data.aws_caller_identity.current.account_id}"
}
Upload agent package
上传Agent包
resource "aws_s3_object" "agent_package" {
bucket = aws_s3_bucket.agent_artifacts.id
key = "agents/${var.agent_version}/package.zip"
source = "${path.module}/deployment_package.zip"
etag = filemd5("${path.module}/deployment_package.zip")
}
resource "aws_s3_object" "agent_package" {
bucket = aws_s3_bucket.agent_artifacts.id
key = "agents/${var.agent_version}/package.zip"
source = "${path.module}/deployment_package.zip"
etag = filemd5("${path.module}/deployment_package.zip")
}
Note: AgentCore resources may require custom provider or AWS CLI
注意:AgentCore资源可能需要自定义Provider或AWS CLI
Use null_resource with local-exec as workaround
使用null_resource结合local-exec作为临时解决方案
resource "null_resource" "create_agent_runtime" {
triggers = {
package_etag = aws_s3_object.agent_package.etag
}
provisioner "local-exec" {
command = <<-EOT
aws bedrock-agentcore-control create-agent-runtime
--name ${var.agent_name}
--description "Terraform-managed agent"
--agent-runtime-artifact '{"s3":{"uri":"s3://${aws_s3_bucket.agent_artifacts.id}/agents/${var.agent_version}/package.zip"}}'
--role-arn ${aws_iam_role.agentcore_execution.arn}
--python-runtime PYTHON_3_13
--entry-point '["main.py"]' EOT }
--name ${var.agent_name}
--description "Terraform-managed agent"
--agent-runtime-artifact '{"s3":{"uri":"s3://${aws_s3_bucket.agent_artifacts.id}/agents/${var.agent_version}/package.zip"}}'
--role-arn ${aws_iam_role.agentcore_execution.arn}
--python-runtime PYTHON_3_13
--entry-point '["main.py"]' EOT }
depends_on = [aws_s3_object.agent_package]
}
data "aws_caller_identity" "current" {}
variable "agent_name" {
default = "my-production-agent"
}
variable "agent_version" {
default = "1.0.0"
}
---resource "null_resource" "create_agent_runtime" {
triggers = {
package_etag = aws_s3_object.agent_package.etag
}
provisioner "local-exec" {
command = <<-EOT
aws bedrock-agentcore-control create-agent-runtime
--name ${var.agent_name}
--description "Terraform-managed agent"
--agent-runtime-artifact '{"s3":{"uri":"s3://${aws_s3_bucket.agent_artifacts.id}/agents/${var.agent_version}/package.zip"}}'
--role-arn ${aws_iam_role.agentcore_execution.arn}
--python-runtime PYTHON_3_13
--entry-point '["main.py"]' EOT }
--name ${var.agent_name}
--description "Terraform-managed agent"
--agent-runtime-artifact '{"s3":{"uri":"s3://${aws_s3_bucket.agent_artifacts.id}/agents/${var.agent_version}/package.zip"}}'
--role-arn ${aws_iam_role.agentcore_execution.arn}
--python-runtime PYTHON_3_13
--entry-point '["main.py"]' EOT }
depends_on = [aws_s3_object.agent_package]
}
data "aws_caller_identity" "current" {}
variable "agent_name" {
default = "my-production-agent"
}
variable "agent_version" {
default = "1.0.0"
}
---CI/CD Pipeline: GitHub Actions
CI/CD流水线:GitHub Actions
yaml
undefinedyaml
undefined.github/workflows/deploy-agent.yml
.github/workflows/deploy-agent.yml
name: Deploy AgentCore Agent
on:
push:
branches: [main]
pull_request:
branches: [main]
env:
AWS_REGION: us-east-1
AGENT_NAME: my-production-agent
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.13'
- name: Install dependencies
run: |
pip install -r requirements.txt
pip install pytest
- name: Run tests
run: pytest tests/
- name: Test local server
run: |
python main.py &
sleep 5
curl -f http://localhost:8080/ping
curl -X POST http://localhost:8080/invocations \
-H "Content-Type: application/json" \
-d '{"prompt": "test"}'
pkill -f main.pydeploy:
needs: test
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v4
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/GitHubActionsRole
aws-region: ${{ env.AWS_REGION }}
- name: Install AgentCore toolkit
run: pip install bedrock-agentcore-starter-toolkit
- name: Configure agent
run: agentcore configure -e main.py -n ${{ env.AGENT_NAME }}
- name: Deploy agent
run: agentcore deploy
- name: Verify deployment
run: |
agentcore invoke '{"prompt": "Health check"}'
---name: Deploy AgentCore Agent
on:
push:
branches: [main]
pull_request:
branches: [main]
env:
AWS_REGION: us-east-1
AGENT_NAME: my-production-agent
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: '3.13'
- name: Install dependencies
run: |
pip install -r requirements.txt
pip install pytest
- name: Run tests
run: pytest tests/
- name: Test local server
run: |
python main.py &
sleep 5
curl -f http://localhost:8080/ping
curl -X POST http://localhost:8080/invocations \
-H "Content-Type: application/json" \
-d '{"prompt": "test"}'
pkill -f main.pydeploy:
needs: test
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
permissions:
id-token: write
contents: read
steps:
- uses: actions/checkout@v4
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@v4
with:
role-to-assume: arn:aws:iam::${{ secrets.AWS_ACCOUNT_ID }}:role/GitHubActionsRole
aws-region: ${{ env.AWS_REGION }}
- name: Install AgentCore toolkit
run: pip install bedrock-agentcore-starter-toolkit
- name: Configure agent
run: agentcore configure -e main.py -n ${{ env.AGENT_NAME }}
- name: Deploy agent
run: agentcore deploy
- name: Verify deployment
run: |
agentcore invoke '{"prompt": "Health check"}'
---CI/CD Pipeline: GitLab CI
CI/CD流水线:GitLab CI
yaml
undefinedyaml
undefined.gitlab-ci.yml
.gitlab-ci.yml
stages:
- test
- build
- deploy
variables:
AWS_REGION: us-east-1
AGENT_NAME: my-production-agent
test:
stage: test
image: python:3.13
script:
- pip install -r requirements.txt
- pip install pytest
- pytest tests/
build:
stage: build
image: python:3.13
script:
- pip install uv
- uv pip install --python-platform aarch64-manylinux2014 --python-version 3.13 --target=deployment_package --only-binary=:all: -r requirements.txt
- cd deployment_package && zip -r ../package.zip . && cd ..
- zip package.zip main.py
artifacts:
paths:
- package.zip
deploy:
stage: deploy
image: amazon/aws-cli
script:
- aws s3 cp package.zip s3://${ARTIFACT_BUCKET}/agents/${CI_COMMIT_SHA}/package.zip
- |
aws bedrock-agentcore-control update-agent-runtime
--agent-runtime-id ${AGENT_RUNTIME_ID}
--agent-runtime-artifact "{"s3":{"uri":"s3://${ARTIFACT_BUCKET}/agents/${CI_COMMIT_SHA}/package.zip"}}" only: - main
--agent-runtime-id ${AGENT_RUNTIME_ID}
--agent-runtime-artifact "{"s3":{"uri":"s3://${ARTIFACT_BUCKET}/agents/${CI_COMMIT_SHA}/package.zip"}}" only: - main
---stages:
- test
- build
- deploy
variables:
AWS_REGION: us-east-1
AGENT_NAME: my-production-agent
test:
stage: test
image: python:3.13
script:
- pip install -r requirements.txt
- pip install pytest
- pytest tests/
build:
stage: build
image: python:3.13
script:
- pip install uv
- uv pip install --python-platform aarch64-manylinux2014 --python-version 3.13 --target=deployment_package --only-binary=:all: -r requirements.txt
- cd deployment_package && zip -r ../package.zip . && cd ..
- zip package.zip main.py
artifacts:
paths:
- package.zip
deploy:
stage: deploy
image: amazon/aws-cli
script:
- aws s3 cp package.zip s3://${ARTIFACT_BUCKET}/agents/${CI_COMMIT_SHA}/package.zip
- |
aws bedrock-agentcore-control update-agent-runtime
--agent-runtime-id ${AGENT_RUNTIME_ID}
--agent-runtime-artifact "{"s3":{"uri":"s3://${ARTIFACT_BUCKET}/agents/${CI_COMMIT_SHA}/package.zip"}}" only: - main
--agent-runtime-id ${AGENT_RUNTIME_ID}
--agent-runtime-artifact "{"s3":{"uri":"s3://${ARTIFACT_BUCKET}/agents/${CI_COMMIT_SHA}/package.zip"}}" only: - main
---Version Management
版本管理
Blue-Green Deployment
蓝绿部署
python
def blue_green_deploy(agent_name, new_version):
"""Deploy new version alongside old, then switch"""
# Get current (blue) version
blue = control.get_agent_runtime(name=f"{agent_name}-blue")
# Deploy new (green) version
green = control.create_agent_runtime(
name=f"{agent_name}-green",
agentRuntimeArtifact={'s3': {'uri': f's3://bucket/agents/{new_version}/package.zip'}},
roleArn=blue['roleArn'],
pythonRuntime='PYTHON_3_13',
entryPoint=['main.py']
)
# Test green
test_result = run_smoke_tests(green['agentRuntimeArn'])
if test_result.passed:
# Update endpoint to point to green
control.update_agent_runtime_endpoint(
endpointId='production-endpoint',
agentRuntimeArn=green['agentRuntimeArn']
)
# Delete old blue
control.delete_agent_runtime(name=f"{agent_name}-blue")
# Rename green to blue
# (Note: actual rename may require recreate)
else:
# Rollback - delete failed green
control.delete_agent_runtime(name=f"{agent_name}-green")
raise Exception("Green deployment failed tests")python
def blue_green_deploy(agent_name, new_version):
"""在旧版本旁部署新版本,然后切换流量"""
# 获取当前(蓝色)版本
blue = control.get_agent_runtime(name=f"{agent_name}-blue")
# 部署新(绿色)版本
green = control.create_agent_runtime(
name=f"{agent_name}-green",
agentRuntimeArtifact={'s3': {'uri': f's3://bucket/agents/${new_version}/package.zip'}},
roleArn=blue['roleArn'],
pythonRuntime='PYTHON_3_13',
entryPoint=['main.py']
)
# 测试绿色版本
test_result = run_smoke_tests(green['agentRuntimeArn'])
if test_result.passed:
# 更新端点指向绿色版本
control.update_agent_runtime_endpoint(
endpointId='production-endpoint',
agentRuntimeArn=green['agentRuntimeArn']
)
# 删除旧的蓝色版本
control.delete_agent_runtime(name=f"{agent_name}-blue")
# 将绿色版本重命名为蓝色版本
# (注意:实际重命名可能需要重新创建)
else:
# 回滚 - 删除失败的绿色版本
control.delete_agent_runtime(name=f"{agent_name}-green")
raise Exception("Green deployment failed tests")Rollback
回滚
bash
undefinedbash
undefinedQuick rollback via CLI
通过CLI快速回滚
agentcore rollback --to-version v1.0.0
agentcore rollback --to-version v1.0.0
Via boto3
通过boto3回滚
control.update_agent_runtime(
agentRuntimeId='runtime-xxx',
agentRuntimeArtifact={
's3': {'uri': 's3://bucket/agents/v1.0.0/package.zip'}
}
)
---control.update_agent_runtime(
agentRuntimeId='runtime-xxx',
agentRuntimeArtifact={
's3': {'uri': 's3://bucket/agents/v1.0.0/package.zip'}
}
)
---Related Skills
相关技能
- bedrock-agentcore: Core platform features
- bedrock-agentcore-evaluations: Pre-deployment testing
- terraform-aws: Infrastructure as code
- ecs-deployment: Alternative deployment patterns
- bedrock-agentcore:核心平台功能
- bedrock-agentcore-evaluations:部署前测试
- terraform-aws:基础设施即代码
- ecs-deployment:替代部署模式
References
参考资料
- - IAM policy templates
references/iam-policies.md - - Common deployment issues
references/troubleshooting.md - - Optimization guide
references/performance-tuning.md
- - IAM策略模板
references/iam-policies.md - - 常见部署问题
references/troubleshooting.md - - 优化指南
references/performance-tuning.md