Skip to content

Commit 301fb99

Browse files
authored
Add AWS CDK implementation for basic-runtime sample (#507)
* feat: Add AWS CDK implementation for basic AgentCore runtime deployment This commit introduces a comprehensive CDK alternative to the existing CloudFormation basic-runtime sample, providing a cleaner and more maintainable Infrastructure as Code approach for deploying Amazon Bedrock AgentCore resources. - **Complete CDK stack** (`basic_runtime_stack.py`) with proper construct separation - **Dedicated IAM role construct** (`infra-utils/agentcore_role.py`) for reusability - **Custom Lambda function** (`infra-utils/build_trigger_lambda.py`) for CodeBuild automation - **S3 asset-based source packaging** eliminating Docker dependency for users - **ARM64 CodeBuild integration** with automated container image building - **Comprehensive documentation** matching CloudFormation sample structure - Uses S3 assets instead of inline code for better maintainability - Separates infrastructure utilities into dedicated `infra-utils/` directory - Implements proper CDK patterns with construct separation - Provides cleaner deployment experience (~5-10 min vs ~10-15 min) - **Basic Strands agent** (`agent-code/basic_agent.py`) with simple Q&A functionality - **ARM64 Dockerfile** optimized for AgentCore runtime requirements - **Proper dependency management** with isolated requirements - Updated title to reflect both CloudFormation and CDK options - Added comprehensive CDK section with architecture highlights - Included CDK prerequisites with version requirements (CDK 2.218.0+) - Updated repository structure to show new CDK directory layout - Added installation commands for required CDK dependencies - Complete documentation following CloudFormation sample structure - Detailed prerequisites, deployment, testing, and cleanup instructions - Sample queries and troubleshooting sections - Architecture explanation and use case descriptions - **CDK 2.218.0+** required for BedrockAgentCore construct support - **Python 3.8+** and **constructs>=10.0.79** for proper CDK functionality - **S3 assets** for source code packaging without size limitations - ECR repository for container image storage - CodeBuild project with ARM64 support for automated builds - Lambda function for build orchestration and completion waiting - AgentCore Runtime with proper IAM permissions and networking - Custom resource for deployment automation - ✅ Successfully deployed and tested in AWS environment - ✅ Verified agent functionality with sample queries - ✅ Confirmed clean resource cleanup with `cdk destroy` - Added David Kaleko to CONTRIBUTORS.md This implementation provides a modern, maintainable alternative to CloudFormation while maintaining feature parity and following AWS CDK best practices. * fix: Resolve CDK Lambda import issues and reorganize infrastructure utilities This commit fixes critical Lambda function import errors that were preventing the CDK stack deployment from completing, and reorganizes the infrastructure utilities for better Python module compatibility. - **Root cause**: `cfnresponse` module is only available for inline CloudFormation Lambda code, not when using CDK's `Code.from_asset()` approach - **Solution**: Embedded the standard AWS-provided cfnresponse functionality directly into the Lambda function to eliminate import dependencies - **Impact**: Custom resource now properly signals CloudFormation completion/failure - **Renamed**: `infra-utils/` → `infra_utils/` for proper Python module imports - **Fixed**: Lambda handler path to use correct Python module notation - **Updated**: Import statements to use underscore-based directory name - Embedded cfnresponse class with SUCCESS/FAILED constants and send() method - Added comprehensive comments explaining why local cfnresponse is necessary - Maintains full compatibility with CloudFormation custom resource protocol - Proper error handling and CloudWatch logging integration - Updated Lambda handler path: `infra_utils.build_trigger_lambda.handler` - Fixed import statements for renamed directory structure - Removed conditional BedrockAgentCore imports (always available in CDK 2.218.0+) - Moved infrastructure utilities to properly named Python package - Added package `__init__.py` for proper module structure - Maintained clean separation between infrastructure and agent code - ✅ Resolves hanging CloudFormation deployments - ✅ Custom resource now properly waits for CodeBuild completion - ✅ Stack deployment completes successfully end-to-end - ✅ Maintains compatibility with existing CloudFormation approach - Verified Lambda function executes without import errors - Confirmed CodeBuild triggering and monitoring functionality - Validated complete stack deployment cycle This fix ensures the CDK implementation works reliably and follows Python packaging best practices while maintaining the same deployment behavior as the CloudFormation equivalent. * Minor README update * Dockerfile updates including a health check to fix all ASH security scan warnings * Readme updates in accordance with PR feedback --------- Signed-off-by: David Kaleko <[email protected]>
1 parent 74851e6 commit 301fb99

File tree

14 files changed

+867
-21
lines changed

14 files changed

+867
-21
lines changed

.gitignore

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -226,6 +226,8 @@ pyrightconfig.json
226226
lambda.zip
227227
.kiro/
228228

229+
### CDK artifacts
230+
cdk.out/
229231
### Bedrock AgentCore ###
230232
.bedrock_agentcore/
231233
.bedrock_agentcore.yaml

04-infrastructure-as-code/README.md

Lines changed: 75 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,20 @@
1-
# CloudFormation Samples for Amazon Bedrock AgentCore
1+
# Infrastructure as Code Samples for Amazon Bedrock AgentCore
22

3-
CloudFormation templates for deploying Amazon Bedrock AgentCore resources.
3+
CloudFormation templates and AWS CDK stacks for deploying Amazon Bedrock AgentCore resources.
44

55
## Overview
66

7-
These CloudFormation templates enable you to:
7+
These Infrastructure as Code samples enable you to:
88
- Deploy AgentCore resources consistently across environments
99
- Automate infrastructure provisioning with Infrastructure as Code
1010
- Maintain version control of your infrastructure
1111
- Implement AWS best practices for security and monitoring
1212

13-
## 📚 Available Samples
13+
Choose your preferred approach:
14+
- **[CloudFormation](./cloudformation/)** - YAML/JSON templates for declarative infrastructure
15+
- **[CDK](./cdk/)** - Python code for programmatic infrastructure
16+
17+
## 📚 CloudFormation Samples
1418

1519
### 01. [Hosting MCP Server on AgentCore Runtime](./cloudformation/mcp-server-agentcore-runtime/)
1620

@@ -133,6 +137,37 @@ aws cloudformation create-stack \
133137

134138
---
135139

140+
## 📚 CDK Samples
141+
142+
### 01. [Basic Agent Runtime](./cdk/basic-runtime/)
143+
144+
Deploy a basic AgentCore Runtime with a simple Strands agent using AWS CDK - no additional tools or memory.
145+
146+
**What it deploys:**
147+
- Docker image asset built from local code
148+
- IAM role with least-privilege policies for AgentCore
149+
- Basic AgentCore Runtime with simple agent
150+
151+
**Architecture highlights:**
152+
- Uses `DockerImageAsset` for container image building (no CodeBuild needed)
153+
- Separates IAM role into its own construct (`AgentCoreRole`)
154+
- Uses `CfnRuntime` directly from `aws_bedrockagentcore`
155+
- Much cleaner than the CloudFormation equivalent
156+
157+
**Use case:** Simple agent deployment without memory, code interpreter, or browser tools
158+
159+
**Deployment time:** ~5-10 minutes
160+
**Estimated cost:** ~$50-100/month
161+
162+
**Quick start:**
163+
```bash
164+
cd cdk/basic-runtime
165+
pip install -r requirements.txt
166+
cdk deploy
167+
```
168+
169+
---
170+
136171
## Prerequisites
137172

138173
Before deploying any CloudFormation template, ensure you have:
@@ -143,7 +178,12 @@ Before deploying any CloudFormation template, ensure you have:
143178
aws configure
144179
```
145180
3. **Access to Amazon Bedrock AgentCore** (preview)
146-
4. **IAM Permissions** to create:
181+
4. **For CDK samples**: Python 3.8+, AWS CDK v2 installed, and **CDK version 2.218.0 or later** (for BedrockAgentCore support)
182+
```bash
183+
npm install -g aws-cdk
184+
pip install aws-cdk-lib==2.218.0 constructs>=10.0.79
185+
```
186+
5. **IAM Permissions** to create:
147187
- CloudFormation stacks
148188
- IAM roles and policies
149189
- ECR repositories
@@ -184,22 +224,36 @@ Default values:
184224
```
185225
04-infrastructure-as-code/
186226
├── README.md # This file
187-
└── cloudformation/ # CloudFormation samples
188-
├── mcp-server-agentcore-runtime/ # MCP Server sample
189-
│ ├── deploy.sh # Deployment script
190-
│ ├── test.sh # Testing script
191-
│ ├── cleanup.sh # Cleanup script
192-
│ ├── mcp-server-template.yaml # CloudFormation template
193-
│ ├── get_token.py # Authentication helper
194-
│ ├── test_mcp_server.py # MCP client test
195-
│ ├── README.md # Sample documentation
196-
│ └── DETAILED_GUIDE.md # Technical deep-dive
197-
├── basic-runtime/ # Basic agent sample
198-
│ └── template.yaml # CloudFormation template
199-
├── multi-agent-runtime/ # Multi-agent sample
200-
│ └── template.yaml # CloudFormation template
201-
└── end-to-end-weather-agent/ # Weather agent sample
202-
└── end-to-end-weather-agent.yaml # CloudFormation template
227+
├── cloudformation/ # CloudFormation samples
228+
│ ├── mcp-server-agentcore-runtime/ # MCP Server sample
229+
│ │ ├── deploy.sh # Deployment script
230+
│ │ ├── test.sh # Testing script
231+
│ │ ├── cleanup.sh # Cleanup script
232+
│ │ ├── mcp-server-template.yaml # CloudFormation template
233+
│ │ ├── get_token.py # Authentication helper
234+
│ │ ├── test_mcp_server.py # MCP client test
235+
│ │ ├── README.md # Sample documentation
236+
│ │ └── DETAILED_GUIDE.md # Technical deep-dive
237+
│ ├── basic-runtime/ # Basic agent sample
238+
│ │ └── template.yaml # CloudFormation template
239+
│ ├── multi-agent-runtime/ # Multi-agent sample
240+
│ │ └── template.yaml # CloudFormation template
241+
│ └── end-to-end-weather-agent/ # Weather agent sample
242+
│ └── end-to-end-weather-agent.yaml # CloudFormation template
243+
└── cdk/ # CDK samples
244+
└── basic-runtime/ # Basic agent CDK sample
245+
├── app.py # CDK app entry point
246+
├── basic_runtime_stack.py # Stack definition
247+
├── requirements.txt # Python dependencies
248+
├── cdk.json # CDK configuration
249+
├── README.md # Sample documentation
250+
├── infra-utils/ # Infrastructure utilities
251+
│ ├── agentcore_role.py # Dedicated role construct
252+
│ └── build_trigger_lambda.py # Lambda function for CodeBuild trigger
253+
└── agent-code/ # Agent source code
254+
├── Dockerfile
255+
├── basic_agent.py
256+
└── requirements.txt
203257
```
204258

205259

Lines changed: 252 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,252 @@
1+
# Basic AgentCore Runtime - CDK
2+
3+
This CDK stack deploys a basic Amazon Bedrock AgentCore Runtime with a simple Strands agent. This is the simplest possible AgentCore deployment, perfect for getting started and understanding the core concepts without additional complexity.
4+
5+
## Table of Contents
6+
7+
- [Overview](#overview)
8+
- [Architecture](#architecture)
9+
- [Prerequisites](#prerequisites)
10+
- [Deployment](#deployment)
11+
- [Testing](#testing)
12+
- [Sample Queries](#sample-queries)
13+
- [Cleanup](#cleanup)
14+
- [Troubleshooting](#troubleshooting)
15+
16+
## Overview
17+
18+
This CDK stack creates a minimal AgentCore deployment that includes:
19+
20+
- **AgentCore Runtime**: Hosts a simple Strands agent
21+
- **ECR Repository**: Stores the Docker container image
22+
- **IAM Roles**: Provides necessary permissions
23+
- **CodeBuild Project**: Automatically builds the ARM64 Docker image
24+
- **Lambda Functions**: Custom resources for automation
25+
- **S3 Assets**: Source code packaging and deployment
26+
27+
This makes it ideal for:
28+
- Learning AgentCore basics
29+
- Quick prototyping
30+
- Understanding the core deployment pattern
31+
- Building a foundation before adding complexity
32+
33+
## Architecture
34+
35+
The architecture consists of:
36+
37+
- **User**: Sends questions to the agent and receives responses
38+
- **AWS CodeBuild**: Builds the ARM64 Docker container image with the agent code
39+
- **Amazon ECR Repository**: Stores the container image
40+
- **AgentCore Runtime**: Hosts the Basic Agent container
41+
- **Basic Agent**: Simple Strands agent that processes user queries
42+
- Invokes Amazon Bedrock LLMs to generate responses
43+
- **IAM Roles**:
44+
- IAM role for CodeBuild (builds and pushes images)
45+
- IAM role for Agent Execution (runtime permissions)
46+
- **Amazon Bedrock LLMs**: Provides the AI model capabilities for the agent
47+
48+
## Prerequisites
49+
50+
### AWS Account Setup
51+
52+
1. **AWS Account**: You need an active AWS account with appropriate permissions
53+
- [Create AWS Account](https://aws.amazon.com/account/)
54+
- [AWS Console Access](https://aws.amazon.com/console/)
55+
56+
2. **AWS CLI**: Install and configure AWS CLI with your credentials
57+
- [Install AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)
58+
- [Configure AWS CLI](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html)
59+
60+
```bash
61+
aws configure
62+
```
63+
64+
3. **Python 3.10+** and **AWS CDK v2** installed
65+
```bash
66+
# Install CDK
67+
npm install -g aws-cdk
68+
69+
# Verify installation
70+
cdk --version
71+
```
72+
73+
4. **CDK version 2.218.0 or later** (for BedrockAgentCore support)
74+
75+
5. **Bedrock Model Access**: Enable access to Amazon Bedrock models in your AWS region
76+
- [Bedrock Model Access Guide](https://docs.aws.amazon.com/bedrock/latest/userguide/model-access.html)
77+
78+
6. **Required Permissions**: Your AWS user/role needs permissions for:
79+
- CloudFormation stack operations
80+
- ECR repository management
81+
- IAM role creation
82+
- Lambda function creation
83+
- CodeBuild project creation
84+
- BedrockAgentCore resource creation
85+
- S3 bucket operations (for CDK assets)
86+
87+
## Deployment
88+
89+
### Option 1: Quick Deploy (Recommended)
90+
91+
```bash
92+
# Install dependencies
93+
pip install -r requirements.txt
94+
95+
# Bootstrap CDK (first time only)
96+
cdk bootstrap
97+
98+
# Deploy
99+
cdk deploy
100+
```
101+
102+
### Option 2: Step by Step
103+
104+
```bash
105+
# 1. Create and activate Python virtual environment
106+
python3 -m venv .venv
107+
source .venv/bin/activate # On Windows: .venv\Scripts\activate
108+
109+
# 2. Install Python dependencies
110+
pip install -r requirements.txt
111+
112+
# 2. Bootstrap CDK in your account/region (first time only)
113+
cdk bootstrap
114+
115+
# 3. Synthesize the CloudFormation template (optional)
116+
cdk synth
117+
118+
# 4. Deploy the stack
119+
cdk deploy --require-approval never
120+
121+
# 5. Get outputs
122+
cdk list
123+
```
124+
125+
### Deployment Time
126+
127+
- **Expected Duration**: 3-5 minutes
128+
129+
## Testing
130+
131+
### Using AWS CLI
132+
133+
```bash
134+
# Get the Runtime ARN from CDK outputs
135+
RUNTIME_ARN=$(aws cloudformation describe-stacks \
136+
--stack-name BasicAgentDemo \
137+
--region us-east-1 \
138+
--query 'Stacks[0].Outputs[?OutputKey==`AgentRuntimeArn`].OutputValue' \
139+
--output text)
140+
141+
# Invoke the agent
142+
aws bedrock-agentcore invoke-agent-runtime \
143+
--agent-runtime-arn $RUNTIME_ARN \
144+
--qualifier DEFAULT \
145+
--payload $(echo '{"prompt": "What is 2+2?"}' | base64) \
146+
response.json
147+
148+
# View the response
149+
cat response.json
150+
```
151+
152+
### Using AWS Console
153+
154+
1. Navigate to [Bedrock AgentCore Console](https://console.aws.amazon.com/bedrock-agentcore/)
155+
2. Go to "Runtimes" in the left navigation
156+
3. Find your runtime (name starts with `BasicAgentDemo_`)
157+
4. Click on the runtime name
158+
5. Click "Test" button
159+
6. Enter test payload:
160+
```json
161+
{
162+
"prompt": "What is 2+2?"
163+
}
164+
```
165+
7. Click "Invoke"
166+
167+
## Sample Queries
168+
169+
Try these queries to test your basic agent:
170+
171+
1. **Simple Math**:
172+
```json
173+
{"prompt": "What is 2+2?"}
174+
```
175+
176+
2. **General Knowledge**:
177+
```json
178+
{"prompt": "What is the capital of France?"}
179+
```
180+
181+
3. **Explanation Request**:
182+
```json
183+
{"prompt": "Explain what Amazon Bedrock is in simple terms"}
184+
```
185+
186+
4. **Creative Task**:
187+
```json
188+
{"prompt": "Write a haiku about cloud computing"}
189+
```
190+
191+
5. **Reasoning**:
192+
```json
193+
{"prompt": "If I have 5 apples and give away 2, how many do I have left?"}
194+
```
195+
196+
## Cleanup
197+
198+
### Using CDK (Recommended)
199+
200+
```bash
201+
cdk destroy
202+
```
203+
204+
### Using AWS CLI
205+
206+
```bash
207+
aws cloudformation delete-stack \
208+
--stack-name BasicAgentDemo \
209+
--region us-east-1
210+
211+
# Wait for deletion to complete
212+
aws cloudformation wait stack-delete-complete \
213+
--stack-name BasicAgentDemo \
214+
--region us-east-1
215+
```
216+
217+
### Using AWS Console
218+
219+
1. Navigate to [CloudFormation Console](https://console.aws.amazon.com/cloudformation/)
220+
2. Select the `BasicAgentDemo` stack
221+
3. Click "Delete"
222+
4. Confirm deletion
223+
224+
## Troubleshooting
225+
226+
### CDK Bootstrap Required
227+
228+
If you see bootstrap errors:
229+
```bash
230+
cdk bootstrap aws://ACCOUNT-NUMBER/REGION
231+
```
232+
233+
### Permission Issues
234+
235+
Ensure your IAM user/role has:
236+
- `CDKToolkit` permissions or equivalent
237+
- Permissions to create all resources in the stack
238+
- `iam:PassRole` for service roles
239+
240+
### Python Dependencies
241+
242+
Install dependencies in the project directory:
243+
```bash
244+
pip install -r requirements.txt
245+
```
246+
247+
### Build Failures
248+
249+
Check CodeBuild logs in the AWS Console:
250+
1. Go to CodeBuild console
251+
2. Find the build project (name contains "basic-agent-build")
252+
3. Check build history and logs

0 commit comments

Comments
 (0)