可易

用 GitHub Actions 在 Amazon Bedrock AgentCore 上部署 AI 智能体

可易团队阅读约 8 分钟

用 GitHub Actions、OIDC 和 IAM 最小权限,把智能体容器经 ECR 与 Inspector 扫描后部署到 AgentCore Runtime,并给出测试与清理步骤。

目录

#用 GitHub Actions 在 Amazon Bedrock AgentCore 上部署 AI 智能体

AWS 近期发布了 Amazon Bedrock AgentCore。这是一项灵活的服务,帮助开发者跨不同框架和模型无缝创建并管理 AI 智能体(AI agents),无论模型托管在 Amazon Bedrock 还是其他环境。具体而言,AgentCore Runtime 提供一个安全、无服务器、专为部署和运行 AI 智能体或工具而建的托管环境。AgentCore Runtime 与框架无关,可与 LangGraph、Strands、CrewAI 等常见框架配合,在自动扩缩和内置安全能力下部署 AI 智能体和工具。

本文演示如何使用 GitHub Actions 工作流,在 AgentCore Runtime 上自动部署 AI 智能体。这一做法提供可扩展的方案和企业级安全控制,并给出完整的持续集成与持续交付(continuous integration and delivery,CI/CD)自动化。通过实施完整流水线,我们按 AWS 最佳实践实现无缝的智能体部署,包括 OpenID Connect(OIDC)认证、最小权限访问控制,以及环境隔离。该方案便于高效更新已有智能体,并纳入持续安全扫描和严格的代码质量检查。结果是一套稳健的部署策略,有助于降低运维复杂度、加强安全,并加快企业环境中的 AI 智能体开发。

Amazon Bedrock AgentCore Runtime 的收益

AgentCore Runtime 适合生产环境中的智能体部署:

  • 提供与框架无关的环境来运行智能体
  • 可使用大语言模型(large language models,LLMs),例如 Amazon Bedrock 提供的模型以及 Anthropic Claude
  • 通过让每个用户会话运行在独立的 microVM 中,提供会话隔离,CPU、内存和文件系统资源彼此隔离
  • 同时支持实时交互和最长 8 小时的长时间运行工作负载
  • 提供内置的认证与可观测性能力

方案概览

我们用 GitHub Actions 开发了一套完整的 CI/CD 流水线,以符合安全标准的方式简化智能体部署。该流水线可作为现成方案,无缝接入现有开发工作流。方案包含以下关键组件:

下图说明该方案的架构。

架构

数据流包含以下步骤:

  1. 开发者把代码变更从本地仓库提交到 GitHub 仓库。本方案中 GitHub Action 由人工触发,但也可以改为自动触发。
  2. GitHub Action 触发构建阶段。
  3. GitHub 的 OIDC 使用令牌向 AWS 认证并访问资源。
  4. GitHub Actions 调用命令,直接根据 Dockerfile 构建智能体容器镜像并推送到 Amazon ECR。
  5. 镜像上传后,AWS Inspector 触发高级安全扫描。
  6. 使用该容器镜像创建 AgentCore Runtime 实例。
  7. 智能体可按其配置进一步查询 Amazon Bedrock 模型并调用工具。

在以下各节中,我们逐步完成方案部署:

  1. 从 GitHub 仓库下载源代码。
  2. 创建智能体代码。
  3. 设置 GitHub 密钥。
  4. 创建 IAM 角色和策略。
  5. 创建 GitHub Actions 工作流。
  6. 触发并监控流水线。
  7. 验证部署。

前提条件

在使用这套安全的 CI/CD 流水线把智能体部署到 AgentCore Runtime 之前,确认已具备以下前提:

下载源代码

克隆源代码仓库:bedrock-agentcore-runtime-cicd

git clone https://github.com/aws-samples/sample-bedrock-agentcore-runtime-cicd.git

仓库目录结构如下:

bedrock-agentcore-runtime-cicd/
├── .github/
│   └── workflows/
│       └── deploy-agentcore.yml         # file contains the set of action to build and deploy the agent on AgentCore Runtime
│       └── test-agent.yml               # after deployment this file is used to test agent via manual workflow dispatch
├── agents/
│   ├── strands_agent.py                 # uses BedrockAgentCoreApp app that creates an AI agent using the Strands framework with Claude as the underlying model
│   ├── requirements.txt                 # contains dependencies 
├── scripts
│   ├── create_iam_role.py               # IAM role required for Bedrock AgentCore Runtime
│   ├── deploy_agent.py                  # deploys a custom agent to AWS Bedrock's AgentCore Runtime platform, which allows you to run containerized AI agents on AWS infrastructure 
│   └── setup_oidc.py                    # OIDC setup for Github Authentication and Authorization to access AWS account to deploy required services
│   └── cleanup_ecr.py                   # keeps 9 recent images in ECR registry, can be customized
│   └── create_guardrail.py              # setup minimum guardrail for content filtering, can be customized according to use case
│   └── test_agent.py                    # contains test cases
└── Dockerfile                           # contain instructions to build Docker image
└── README.md

创建智能体代码

使用 AgentCore Runtime 工具包,以你选择的框架创建智能体。该工具包使用 BedrockAgentCoreApp 创建应用,提供一种标准化方式,把 AI 智能体代码打包成可在 AgentCore Runtime 托管基础设施上运行的容器。它还使用 app.entrypoint,这是一个 Python 装饰器,用于把某个函数标记为主入口。当 Amazon Bedrock 智能体收到传入的 API 请求时,该函数接收并处理用户请求。在这份示例智能体代码中,当有人通过 API 调用你的 Amazon Bedrock 智能体时,AgentCore Runtime 会自动调用 strands_agent_bedrock(payload) 函数。

本文使用 agents/strands_agent.py 文件,基于 Strands Agents 框架创建智能体:

"""
This module defines a conversational AI agent that can perform calculations
using the Strands framework.
"""
from bedrock_agentcore.runtime import BedrockAgentCoreApp
from strands import Agent
from strands.models import BedrockModel
from strands_tools import calculator
# Initialize the Bedrock AgentCore application
app = BedrockAgentCoreApp()
# Configure the Claude model for the agent with guardrail
model_id = "us.anthropic.claude-sonnet-4-20250514-v1:0"
# Load guardrail ID if available
guardrail_config = None
try:
    with open("guardrail_id.txt", "r", encoding="utf-8") as f:
        guardrail_id = f.read().strip()
        if guardrail_id:
            guardrail_config = {
                "guardrailIdentifier": guardrail_id,
                "guardrailVersion": "1",
            }
            print(f"Loaded guardrail: {guardrail_id}")
except FileNotFoundError:
    print("No guardrail file found - running without guardrail")
model = BedrockModel(model_id=model_id, guardrail=guardrail_config)
# Create the agent with tools and system prompt
agent = Agent(
    model=model,
    tools=[calculator],
    system_prompt="You're a helpful assistant. You can do simple math calculation.",
)
@app.entrypoint
def strands_agent_bedrock(payload):
    """
    Main entrypoint for the Bedrock AgentCore Runtime.
    This function is called by AWS Bedrock AgentCore when the agent receives
    a request. It processes the user input and returns the agent's response.
    Args:
        payload (dict): Request payload containing user input
                       Expected format: {"prompt": "user question"}
    Returns:
        str: The agent's text response to the user's prompt
    """
    # Extract the user's prompt from the payload
    user_input = payload.get("prompt")
    # Process the input through the agent (handles tool selection and model inference)
    response = agent(user_input)
    # Extract and return the text content from the response
    return response.message["content"][0]["text"]
if __name__ == "__main__":
    # Run the application locally for testing
    # In production, this is handled by Bedrock AgentCore Runtime
    app.run()

设置 GitHub 密钥

GitHub Actions 工作流必须访问你 AWS 账户中的资源。本文使用 IAM OpenID Connect 身份提供方,以及带 IAM 策略的 IAM 角色来访问 AWS 资源。OIDC 让 GitHub Actions 工作流访问 AWS 资源时,不必把 AWS 凭证作为长期 GitHub 密钥保存。这些凭证作为 GitHub 密钥,保存在 GitHub 仓库 Settings 下的 Secrets 选项中。更多信息见 在 GitHub Actions 中使用密钥。

创建 IAM 角色和策略

要在 AgentCore Runtime 中运行智能体或工具,需要一个 IAM 执行角色。关于创建 IAM 角色的信息,见 IAM 角色创建。

本文为 AgentCore Runtime 创建所需的信任策略和执行角色。更多细节见 AgentCore Runtime 的 IAM 权限。

以下代码是 AgentCore Runtime 信任策略:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "AssumeRolePolicy",
      "Effect": "Allow",
      "Principal": {
        "Service": "bedrock-agentcore.amazonaws.com"
      },
      "Action": "sts:AssumeRole",
      "Condition": {
            "StringEquals": {
                "aws:SourceAccount": "accountId"
            },
            "ArnLike": {
                "aws:SourceArn": "arn:aws:bedrock-agentcore:region:accountId:*"
            }
       }
    }
  ]
}

以下代码是 AgentCore Runtime 执行角色:

{
        "Version": "2012-10-17",
        "Statement": [
            {
                "Effect": "Allow",
                "Action": [
                    "bedrock:InvokeModel",
                    "bedrock:InvokeModelWithResponseStream",
                    "bedrock:Converse",
                    "bedrock:ConverseStream"
                ],
                "Resource": [
                    "arn:aws:bedrock:*::foundation-model/us.anthropic.claude-sonnet-4-*",
                    "arn:aws:bedrock:*::foundation-model/anthropic.claude-*",
                    "arn:aws:bedrock:*:*:inference-profile/us.anthropic.claude-sonnet-4-*",
                    "arn:aws:bedrock:*:*:inference-profile/anthropic.claude-*"
                ]
            },
            {
                "Effect": "Allow",
                "Action": [
                    "ecr:GetAuthorizationToken",
                    "ecr:BatchCheckLayerAvailability",
                    "ecr:GetDownloadUrlForLayer",
                    "ecr:BatchGetImage"
                ],
                "Resource": "arn:aws:ecr:::repository/bedrock-agentcore-*"
            },
            {
                "Effect": "Allow",
                "Action": [
                    "logs:CreateLogGroup",
                    "logs:CreateLogStream",
                    "logs:PutLogEvents"
                ],
                "Resource": "arn:aws:logs:*:*:*"
            }
        ]
    }

创建 GitHub Actions 工作流

创建工作流的细节见 CI/CD 工作流文件 .github/workflows/deploy-agentcore.yml。工作流将执行以下步骤:

  • 对流水线中给出的任务使用默认的 Ubuntu Github Runner。
  • 工作流安装 requirement.txt 文件中列出的所需依赖。
  • 它构建 Docker 镜像并部署到 ECR 仓库。
  • 使用 Amazon Inspector 扫描镜像,以识别潜在漏洞。
  • AgentCore Runtime 把智能体部署为一个端点。
  • 工作流测试智能体端点以验证功能。

触发并监控流水线

该流水线可以由 agents 文件夹中的代码变更触发,也可以使用 workflow dispatch 选项手动触发。这可能会随组织的分支策略进一步变化。更新 .github/workflows/deploy-agentcore.yml 中的代码即可改变这一触发行为。

流水线
详细步骤

测试智能体

智能体部署完成后,我们将通过 workflow dispatch 选项手动触发 Test Agent 工作流,以验证其功能。

测试智能体流水线
测试智能体

AgentCore Runtime 版本控制与端点

Amazon Bedrock AgentCore 对 AgentCore Runtime 实施自动版本控制,并让你使用端点管理不同配置。端点提供引用 AgentCore Runtime 特定版本的方式。更多细节和示例代码见 AgentCore Runtime 版本控制与端点。

清理

为避免后续产生费用,完成以下步骤:

  1. 在 Amazon ECR 控制台中,删除通过 GitHub Actions 部署创建的 ECR 镜像。
  2. 删除部署在 AgentCore Runtime 中的智能体。

结论

本文演示了一种综合做法:使用 GitHub Actions,在 AgentCore Runtime 上以更安全、可扩展的方式部署 AI 智能体。该方案为生成式 AI 应用提供稳健、自动化且受控的环境,通过自动化依赖管理、实施持续代码质量检查、执行全面漏洞扫描,以及促成一致的部署过程,应对关键的企业部署挑战。通过把基础设施复杂性抽象掉,这条流水线帮助开发者聚焦智能体逻辑和功能,同时提供一种与框架无关的做法,支持大规模无缝管理多个 AI 智能体。随着 AI 智能体持续改变企业能力,该方案是简化 AI 智能体开发与运维管理的重要一步,为现代生成式 AI 应用提供一种标准化、安全且高效的部署机制。

作为下一步,你可以使用 Amazon Q 智能增强并定制 AI 智能体部署流水线,用先进的、具备上下文感知的自动化改造 CI/CD 流程。

PRIMARY_SOURCE: https://aws.amazon.com/blogs/machine-learning/deploy-ai-agents-on-amazon-bedrock-agentcore-using-github-actions

  • #GitHub Actions
  • #AgentCore
  • #CI/CD
  • #OIDC
  • #ECR