* feat(cdk): reorganize CDK samples into python/ and typescript/ folders - Move existing Python CDK samples to cdk/python/ - Add TypeScript CDK samples folder with knowledge-base-rag-agent - Update cdk/README.md with language comparison table - Update parent README with new paths and TypeScript mention - Add cdk/python/README.md for Python-specific guidance 🤖 Assisted by Amazon Q Developer * docs: add Jerad Engebreth to CONTRIBUTORS.md 🤖 Assisted by Amazon Q Developer * fix(cdk/typescript): document known vulnerabilities and fix npm workspaces build - Add Known Dependency Vulnerabilities section to README documenting upstream issues in aws-amplify (fast-xml-parser, lodash) - Add build/test scripts to Lambda layer package.json to fix npm workspaces build command 🤖 Assisted by Amazon Q Developer * fix(security): add HEALTHCHECK and non-root USER to Dockerfile - Add HEALTHCHECK instruction for container orchestration - Create non-root appuser for security best practices - Addresses CKV_DOCKER_2, CKV_DOCKER_3 security findings * fix(security): address CodeQL findings for insecure randomness and HTML sanitization - Replace Math.random() with crypto.randomBytes() for session ID generation - Use iterative sanitization loop to handle nested/obfuscated HTML tags - Addresses CodeQL insecure randomness and incomplete sanitization findings * fix(security): improve HTML sanitization to address CodeQL findings - Handle closing tags with spaces like </script > - Add data: and vbscript: URL scheme blocking - Use tag-based approach instead of content-matching regex - Add more dangerous tags (form, input, button, etc.) * remove unused import * fix(lint): fix import ordering and remove extra blank lines - Sort imports alphabetically (logging before os) - Remove extra blank line in knowledge_base.py - Consistent import grouping (stdlib, then third-party) * fix(security): use HTML entity encoding instead of regex-based sanitization - Replace regex-based tag stripping with HTML entity encoding - Encode all special characters (&, <, >, ", ', /, `, =) - This approach is CodeQL-compliant and more secure - Regex-based HTML filtering is inherently flawed * fix(lint): add __all__ to fix F401 unused import warnings - Add __all__ exports to infra_utils/__init__.py files - Explicitly declares AgentCoreRole as public API * style: apply ruff formatting to all Python files in 04-infrastructure-as-code - Format 32 Python files with ruff - Includes CDK Python samples, Terraform samples, and TypeScript agent code * refactor: rename project from bedrock-agentcore-template to knowledge-base-rag-agent - Update package.json names for root and infrastructure packages - Update README and docs with new project name and paths - Update CloudWatch, SNS, KMS, and Cognito resource names - Regenerate package-lock.json with new package names * refactor: complete project rename to knowledge-base-rag-agent - Update README title and all documentation headers - Update TypeScript stack descriptions and resource names - Update Python agent module docstrings - Update Dockerfile header comment - Update Lambda function package description - Rename runtime to knowledge_base_rag_agent - Rename memory to knowledge_base_rag_agent_memory - Rename API to Knowledge Base RAG Agent API - Update Secrets Manager secret name * fix: correct Docker references and fix Lambda bundling - Update README and docs to clarify Docker is for AgentCore Runtime container, not Lambda bundling - Add @aws-lambda-powertools/logger dependency for Lambda function - Add esbuild as dev dependency for NodejsFunction bundling - Fix S3 bucket deployment to use single deployment with auto content-type detection - Deploy config.json separately with prune:false to preserve other files --------- Co-authored-by: Jerad Engebreth <awsjerad@amazon.com>
Basic AgentCore Runtime - Terraform
This pattern demonstrates the simplest deployment of an AgentCore Runtime using Terraform. It creates a basic agent without additional tools like Memory, Code Interpreter, or Browser.
Table of Contents
- Overview
- Architecture
- Prerequisites
- Quick Start
- Testing the Agent
- Sample Queries
- Customization
- File Structure
- Troubleshooting
- Cleanup
- Pricing
- Next Steps
- Resources
- 🤝 Contributing
- 📄 License
Overview
This Terraform configuration creates a minimal AgentCore deployment that includes:
- AgentCore Runtime: Hosts a simple Strands agent
- ECR Repository: Stores the Docker container image
- IAM Roles: Provides necessary permissions
- CodeBuild Project: Automatically builds the ARM64 Docker image
This makes it ideal for:
- Learning AgentCore basics with Terraform
- Quick prototyping and experimentation
- Understanding the core deployment pattern
- Building a foundation before adding complexity
Architecture
What's Included
This Terraform configuration creates:
- S3 Bucket: Stores agent source code for version-controlled builds
- ECR Repository: Container registry for the agent Docker image
- CodeBuild Project: Automated Docker image building and pushing
- IAM Roles: Execution roles for the agent and CodeBuild
- AgentCore Runtime: Serverless agent runtime with the deployed container
Agent Code Management
The agent-code/ directory contains your agent's source files:
basic_agent.py- Agent implementationDockerfile- Container configurationrequirements.txt- Python dependencies
Automatic Change Detection:
- Terraform archives the
agent-code/directory - Uploads to S3 with MD5-based versioning
- CodeBuild pulls from S3 and builds the Docker image
- Any changes to files trigger automatic rebuild (new files, modifications, deletions)
Prerequisites
Required Tools
-
Terraform (>= 1.6)
- Recommended: tfenv for version management
- Or download directly: terraform.io/downloads
Note:
brew install terraformprovides v1.5.7 (deprecated). Use tfenv or direct download for >= 1.6. -
AWS CLI (configured with credentials)
aws configure -
Python 3.11+ (for testing scripts)
python --version # Verify Python 3.11 or later pip install boto3 -
Docker (for local testing, optional)
AWS Account Requirements
- AWS Account with appropriate permissions
- Access to Amazon Bedrock models
Quick Start
1. Configure Variables
Copy the example variables file and customize:
cp terraform.tfvars.example terraform.tfvars
Edit terraform.tfvars with your preferred values.
2. Initialize Terraform
See State Management Options in the main README for detailed guidance on local vs. remote state.
Quick start with local state:
terraform init
For team collaboration, use remote state - see the main README for setup instructions.
3. Review the Plan
terraform plan
4. Deploy
Method 1: Using Deploy Script (Recommended)
Make the script executable (first-time only):
chmod +x deploy.sh
Then deploy:
./deploy.sh
The deploy script:
- Validates Terraform configuration
- Shows deployment plan
- Prompts for confirmation
- Applies changes
Method 2: Direct Terraform Commands
terraform apply
When prompted, type yes to confirm the deployment.
Note: The deployment process includes:
- Creating ECR repository
- Building Docker image via CodeBuild
- Creating AgentCore Runtime
Total deployment time: ~3-5 minutes
5. Get Outputs
After deployment completes:
terraform output
Example output:
agent_runtime_id = "AGENT1234567890"
agent_runtime_arn = "arn:aws:bedrock-agentcore:<us-west-2>:123456789012:agent-runtime/AGENT1234567890"
ecr_repository_url = "123456789012.dkr.ecr.us-west-2.amazonaws.com/agentcore-basic-basic-agent"
Testing the Agent
Prerequisites for Testing
Before testing, ensure you have the required packages installed:
Option A: Using uv (Recommended)
uv venv
source .venv/bin/activate # On Windows: .venv\Scripts\activate
uv pip install boto3 # Required for agent invocation
Option B: System-wide installation
pip install boto3 # Required for agent invocation
Note: boto3 is required for the test script to invoke the agent runtime via AWS API.
Option 1: Using Test Script (Recommended)
# Run the test suite
python test_basic_agent.py $(terraform output -raw agent_runtime_arn)
Option 2: Using AWS CLI
# Get the runtime ARN from outputs
RUNTIME_ARN=$(terraform output -raw agent_runtime_arn)
# Invoke the agent
aws bedrock-agentcore invoke-agent-runtime \
--agent-runtime-arn $RUNTIME_ARN \
--qualifier DEFAULT \
--payload $(echo '{"prompt": "Hello, introduce yourself"}' | base64) \
response.json
# View the response
cat response.json | jq -r '.response'
Option 3: Using AWS Console
- Navigate to Amazon Bedrock console
- Go to AgentCore → Runtimes
- Select your runtime
- Use the "Test" feature to send queries
Sample Queries
Try these queries to test your basic agent:
-
Simple Math:
{"prompt": "What is 2+2?"} -
General Knowledge:
{"prompt": "What is the capital of France?"} -
Explanation Request:
{"prompt": "Explain what Amazon Bedrock is in simple terms"} -
Creative Task:
{"prompt": "Write a haiku about cloud computing"}
Customization
Modify Agent Code
Edit files in agent-code/ and deploy:
basic_agent.py- Agent logic and system promptDockerfile- Container configurationrequirements.txt- Python dependencies
Changes are automatically detected and trigger rebuild. Run terraform apply to deploy.
Environment Variables
Add to terraform.tfvars:
environment_variables = {
LOG_LEVEL = "DEBUG"
}
Network Mode
Set network_mode = "PRIVATE" for VPC deployment (requires additional VPC configuration).
File Structure
basic-runtime/
├── main.tf # AgentCore runtime resource
├── variables.tf # Input variables
├── outputs.tf # Output values
├── versions.tf # Provider configuration
├── iam.tf # IAM roles and policies
├── s3.tf # S3 bucket for source code
├── ecr.tf # ECR repository
├── codebuild.tf # Docker build automation
├── buildspec.yml # CodeBuild build specification
├── terraform.tfvars.example # Example configuration
├── backend.tf.example # Remote state example
├── test_basic_agent.py # Automated test script
├── agent-code/ # Agent source code
│ ├── basic_agent.py # Agent implementation
│ ├── Dockerfile # Container configuration
│ └── requirements.txt # Python dependencies
├── scripts/ # Build automation scripts
│ └── build-image.sh # CodeBuild trigger & verification
├── deploy.sh # Deployment helper script
├── destroy.sh # Cleanup helper script
├── .gitignore # Git ignore patterns
└── README.md # This file
Troubleshooting
CodeBuild Fails
If the Docker build fails:
-
Check CodeBuild logs:
aws codebuild batch-get-builds \ --ids $(terraform output -raw codebuild_project_name) \ --region us-west-2 -
Common issues:
- Network connectivity issues
- ECR authentication problems
- Python dependency conflicts
Runtime Creation Fails
If the runtime creation fails:
-
Verify the Docker image exists:
aws ecr describe-images \ --repository-name $(terraform output -raw ecr_repository_url | cut -d'/' -f2) \ --region us-west-2 -
Check IAM role permissions
-
Verify Bedrock AgentCore service quotas
Agent Invocation Fails
If invoking the agent fails:
- Check runtime status in AWS Console
- Review CloudWatch Logs for the runtime
- Verify Bedrock model access permissions
Cleanup
Destroy All Resources
Make the script executable (first-time only):
chmod +x destroy.sh
Then cleanup:
./destroy.sh
Or use Terraform directly:
terraform destroy
Verify Cleanup
Confirm all resources are deleted:
# Check ECR repositories
aws ecr describe-repositories --region us-west-2 | grep agentcore-basic
# Check AgentCore runtimes
aws bedrock-agentcore list-agent-runtimes --region us-west-2
Pricing
For current pricing information, please refer to:
- Amazon Bedrock Pricing
- Amazon ECR Pricing
- AWS CodeBuild Pricing
- Amazon S3 Pricing
- Amazon CloudWatch Pricing
Note: Actual costs depend on your usage patterns, AWS region, and specific services consumed.
Next Steps
Explore Other Patterns
- MCP Server Runtime - Add MCP protocol support
- Multi-Agent Runtime - Deploy multiple coordinating agents
- End-to-End Weather Agent - Full-featured agent with tools
Resources
- Terraform AWS Provider Documentation
- AWS Bedrock AgentCore Documentation
- Strands Agents Documentation
- AgentCore Samples Repository
🤝 Contributing
We welcome contributions! Please see our Contributing Guide for details.
📄 License
This project is licensed under the MIT License - see the LICENSE file for details.
