* 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>
Terraform Samples
Deploy Amazon Bedrock AgentCore resources using Terraform.
Prerequisites
- 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
- Python 3.11+ (for testing scripts)
- Docker (optional, for local testing)
- Access to Amazon Bedrock AgentCore (preview)
State Management Options
Terraform tracks deployed resources in a state file. Choose the approach that fits your needs:
Option A: Local State (Quickstart)
Perfect for testing, learning, and solo development:
cd <sample-directory>
terraform init
Characteristics:
- State stored in local
terraform.tfstatefile - Simple setup, no additional configuration
- Best for individual experimentation
- Not suitable for team collaboration
Option B: Remote State (Teams/Production)
Recommended for team collaboration and production environments:
cd <sample-directory>
# 1. Setup (one-time per pattern)
cp backend.tf.example backend.tf
# Edit backend.tf with your S3 bucket and DynamoDB table
# 2. Initialize with backend
terraform init
Characteristics:
- State stored in S3 with DynamoDB locking
- Enables team collaboration
- Provides state versioning and backup
- Prevents concurrent modifications
Setup Requirements:
- S3 bucket for state storage
- DynamoDB table for state locking
- See
backend.tf.examplein each pattern for details
💡 Note: You must create the S3 bucket and DynamoDB table before running terraform init with remote state. See backend.tf.example in each pattern directory for setup instructions.
General Deployment Pattern
Option 1: Using Automation Scripts (Recommended)
cd <sample-directory>
chmod +x deploy.sh
./deploy.sh
The deployment script will:
- Validate your environment
- Initialize Terraform
- Create and review the plan
- Deploy all resources
- Display outputs and next steps
Option 2: Manual Terraform Commands
cd <sample-directory>
# 1. Configure variables
cp terraform.tfvars.example terraform.tfvars
# Edit terraform.tfvars with your values
# 2. Choose state management (see State Management Options above)
terraform init
# 3. Review the plan
terraform plan
# 4. Deploy
terraform apply
# 5. View outputs
terraform output
Testing
All patterns include Python test scripts to verify your deployment.
Setup Test Environment
Option 1: Using uv (Recommended)
# Install uv if not already installed
curl -LsSf https://astral.sh/uv/install.sh | sh
# Create virtual environment
uv venv
# Activate virtual environment
source .venv/bin/activate # On macOS/Linux
# .venv\Scripts\activate # On Windows
# Install boto3
uv pip install boto3
Option 2: Using pip
# Create virtual environment
python3 -m venv .venv
# Activate virtual environment
source .venv/bin/activate # On macOS/Linux
# .venv\Scripts\activate # On Windows
# Install boto3
pip install boto3
Run Tests
# Get the agent ARN from Terraform outputs
AGENT_ARN=$(terraform output -raw agent_runtime_arn)
# Run the test script
python test_*.py $AGENT_ARN
Cleanup
# Using automation script
./destroy.sh
# Or using Terraform directly
terraform destroy
Samples
- basic-runtime/ - Simple agent deployment with container runtime
- mcp-server-agentcore-runtime/ - MCP Server with JWT authentication and API Gateway
- multi-agent-runtime/ - Multi-agent system with Agent-to-Agent (A2A) communication
- end-to-end-weather-agent/ - Weather agent with Browser, Code Interpreter, and Memory tools
Terraform Advantages
- Infrastructure as Code: Define resources declaratively with HCL
- State Management: Track and manage infrastructure state
- Module Reusability: Create reusable infrastructure components
- Plan Before Apply: Preview changes before deployment
- Automated Image Building: Uses CodeBuild for Docker image creation
- Provider Ecosystem: Access to thousands of providers and resources
- Automation Scripts: Included deploy.sh and destroy.sh for easy deployment
Pattern Comparison
| Pattern | Agent Runtimes | Tools | A2A | MCP Server | Use Case |
|---|---|---|---|---|---|
| basic-runtime | 1 | - | ❌ | ❌ | Simple agent deployment |
| mcp-server | 1 | - | ❌ | ✅ | API integration with JWT auth |
| multi-agent | 2 | - | ✅ | ❌ | Orchestrator + Specialist pattern |
| weather-agent | 1 | Browser, Code Interpreter, Memory | ❌ | ❌ | Full-featured agent with tools |
Troubleshooting
Terraform Version Issues
If you encounter provider compatibility issues:
# Install specific Terraform version with tfenv
tfenv install 1.6.0
tfenv use 1.6.0
State Management
# View current state
terraform show
# List all resources in state
terraform state list
# Remove a resource from state (if needed)
terraform state rm <resource_address>
Provider Errors
If you see provider version conflicts:
# Upgrade providers to latest compatible versions
terraform init -upgrade
# Lock provider versions
terraform providers lock
CodeBuild Failures
Check build logs:
# Get project name from outputs
PROJECT_NAME=$(terraform output -raw codebuild_project_name)
# View recent build logs
aws codebuild list-builds-for-project \
--project-name $PROJECT_NAME \
--region <region>
# Get specific build details
aws codebuild batch-get-builds \
--ids <build-id> \
--region <region>
Deployment Stuck
If deployment appears stuck:
# Check CloudWatch Logs for the agent runtime
aws logs tail /aws/bedrock-agentcore/<runtime-name> --follow
# Check CodeBuild progress
aws codebuild list-builds-for-project \
--project-name <project-name> \
--max-items 5
Resource Already Exists
If you encounter "resource already exists" errors:
# Import existing resource into state
terraform import <resource_type>.<resource_name> <resource_id>
# Example for S3 bucket
terraform import aws_s3_bucket.example my-bucket-name
Cleanup Issues
If terraform destroy fails:
# Manually empty S3 buckets first
aws s3 rm s3://<bucket-name> --recursive
# Force destroy (use with caution)
terraform destroy -auto-approve
# Check for remaining resources
aws resourcegroupstaggingapi get-resources \
--tag-filters Key=ManagedBy,Values=Terraform
Key Features
State Management
Terraform tracks all deployed resources in a state file. For team collaboration:
# Setup remote state (example with S3)
cp backend.tf.example backend.tf
# Edit backend.tf with your S3 bucket details
terraform init -migrate-state
Automated Docker Builds
Each pattern uses AWS CodeBuild to automatically build ARM64 Docker images:
- Triggered on source code changes (MD5 hash detection)
- No local Docker daemon required
- Optimized for AWS Graviton processors
Testing Scripts
All patterns include infrastructure-agnostic Python test scripts:
# Get the agent ARN from Terraform outputs
AGENT_ARN=$(terraform output -raw agent_runtime_arn)
# Run tests
python test_*.py $AGENT_ARN
Additional Resources
- Terraform Documentation
- AWS Provider Documentation
- Amazon Bedrock AgentCore Documentation
- Terraform Best Practices
Contributing
Contributions are welcome! Please see our Contributing Guide for details.
License
This project is licensed under the MIT-0 license. See the LICENSE file for details.