Skip to content

PR for Strands audit agent with updated sandbox environment #63

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Jul 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
236 changes: 236 additions & 0 deletions 02-samples/13-aws-audit-assistant/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,236 @@
# AWS Audit Assistant: Automated Resource Compliance Checker

## ⚠️ Important Security Notice
This tool executes scripts that may affect your AWS environment. **Always run it from a sandbox environment with read-only permissions**. A Terraform script is provided in the `sandbox` folder to create an EC2 instance with the appropriate read-only IAM role for safe auditing.

## 🎯 Overview
AWS Audit Assistant is your AI-powered partner for ensuring AWS resource compliance with best practices. It provides intelligent insights and recommendations for security and efficiency improvements.

![Architecture Diagram](./architecture.png)

## 🏗️ Architecture

### Components
- **Multi-Agent System**: Coordinated agents working together for comprehensive auditing
- **Documentation Retriever**: Fetches and analyzes AWS best practices documentation
- **Boto3 Code Assistant**: Generates and executes AWS API calls safely
- **Resource Auditor**: Evaluates resources against compliance standards

### Technical Stack
| Component | Description |
|-----------|-------------|
| Model Provider | Amazon Bedrock (Claude 3.5 Sonnet) |
| Native Tools | boto3, file_read, shell, python_repl |
| Custom Agents | Documentation Retriever, Boto3 Code Assistant, Resource Auditor |

## 📋 Prerequisites

1. AWS Account with appropriate permissions
- [Create an AWS Account](https://aws.amazon.com/premiumsupport/knowledge-center/create-and-activate-aws-account/)
- [Understanding AWS IAM](https://docs.aws.amazon.com/IAM/latest/UserGuide/introduction.html)
- [AWS CLI Configuration Guide](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html)

Required Permissions:
- Create EC2 instances
- Create IAM roles
- Create Security Groups

Additional Resources:
- [Understanding EC2 Permissions](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/iam-policies-for-amazon-ec2.html)
- [IAM Roles Overview](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html)
- [Security Groups Guide](https://docs.aws.amazon.com/vpc/latest/userguide/VPC_SecurityGroups.html)

2. Python 3.11 or higher
- [Download Python](https://www.python.org/downloads/)
- [Python Installation Guide](https://docs.python.org/3/using/index.html)

3. [uv package manager](https://docs.astral.sh/uv/getting-started/installation/)
- Installation guides for different platforms:
- [Linux/macOS Installation](https://docs.astral.sh/uv/installation/#linux-and-macos)
- [Windows Installation](https://docs.astral.sh/uv/installation/#windows)

4. AWS credentials configured locally or appropriate IAM role
- [Configuring AWS Credentials](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-files.html)
- [IAM Roles Guide](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html)
- [AWS CLI Installation](https://docs.aws.amazon.com/cli/latest/userguide/getting-started-install.html)

5. Terraform (for sandbox environment)
- [Install Terraform](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/install-cli)
- [Terraform AWS Provider Setup](https://registry.terraform.io/providers/hashicorp/aws/latest/docs#authentication-and-configuration)
- [Terraform Basic Commands](https://developer.hashicorp.com/terraform/tutorials/aws-get-started/aws-build)

## 🚀 Installation & Setup

### Option 1: Local Installation (Development Only)

⚠️ **IMPORTANT**: This option is strictly for development and testing purposes only. DO NOT use this installation method in any production environment as it may not have the necessary security controls and could potentially impact your AWS resources. For production use, always use Option 2 (Sandbox Environment) which provides proper isolation and read-only permissions.

```bash
# Install dependencies using uv
uv pip install -r requirements.txt

# Run the assistant
uv run ai_assistant.py
```

### Option 2: Sandbox Environment (Recommended)

The sandbox environment provides a secure way to run the AWS Audit Assistant with appropriate read-only permissions. It includes Terraform configurations to create an EC2 instance with the necessary IAM roles and security settings.

#### 1. Deploy Infrastructure
```bash
# Navigate to sandbox directory
cd sandbox

# Initialize Terraform
terraform init

# Review the deployment plan
terraform plan

# Deploy the resources
terraform apply
```

Learn more:
- [Terraform AWS Provider](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)
- [EC2 Instance Types](https://aws.amazon.com/ec2/instance-types/)

#### 2. Copy Required Files
After the infrastructure is deployed, copy the necessary files to the EC2 instance:

```bash
scp -i ./audit-assistant-key.pem \
../ai_assistant.py \
../aws_document_agent.py \
../strands_boto_agent.py \
../requirements.txt \
ec2-user@<instance-public-ip>:/home/ec2-user/
```

Learn more:
- [Using SCP with EC2](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AccessingInstancesLinux.html#AccessingInstancesLinuxSCP)
- [EC2 Key Pairs](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-key-pairs.html)

#### 3. Install Dependencies
SSH into the EC2 instance and install the required packages:

```bash
# Connect to the instance
ssh -i ./audit-assistant-key.pem ec2-user@<instance-public-ip>

# Install dependencies
pip3 install -r requirements.txt
```

Learn more:
- [Connecting to EC2 Instances](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/AccessingInstances.html)
- [Python Package Installation](https://packaging.python.org/en/latest/tutorials/installing-packages/)

#### 4. Run the Assistant
```bash
python3 ai_assistant.py
```

#### Security Features
- EC2 instance is configured with read-only IAM role
- Security group limits inbound access
- All operations are performed with least-privilege permissions
- Terraform-managed infrastructure for consistency

Learn more:
- [EC2 Instance IAM Roles](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles_use_switch-role-ec2.html)
- [Security Best Practices](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-security.html)
- [Least Privilege Principle](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html#grant-least-privilege)

#### Cleanup
When you're done using the sandbox environment, destroy the resources to avoid unnecessary charges:

```bash
terraform destroy
```

Learn more:
- [Terraform Destroy Command](https://developer.hashicorp.com/terraform/cli/commands/destroy)
- [AWS Pricing](https://aws.amazon.com/pricing/)

## 💡 Usage Examples

The AWS Audit Assistant accepts natural language queries about your AWS resources. Here are some example commands:

```plaintext
> Check if my S3 bucket 'my-bucket' follows security best practices
> Audit EC2 instance 'i-1234567890abcdef0' in us-west-2 for security compliance
> Verify if my IAM policies follow the principle of least privilege
> Evaluate RDS database 'my-database' configuration against AWS recommendations
```

## 🔍 Features

- **Comprehensive Auditing**: Evaluates resources against AWS best practices
- **Natural Language Interface**: Simple English commands to perform complex audits
- **Safe Execution**: Read-only operations by default
- **Detailed Reports**: Clear findings and recommendations
- **Multi-Resource Support**: Covers S3, EC2, IAM, RDS, and more
- **Best Practice Updates**: Stays current with AWS recommendations

## 🛡️ Security Best Practices

1. Always use the sandbox environment for production audits
2. Review generated scripts before execution
3. Use read-only IAM roles when possible
4. Monitor AWS CloudTrail for audit activities
5. Regularly update dependencies for security patches

## ❗ Troubleshooting

### EC2 Connection Issues
If you can't connect to the EC2 instance:
- Verify your security group allows SSH access from your IP
- Ensure you're using the correct key pair
- Check that the instance is running

Resources:
- [EC2 Connection Issues](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/TroubleshootingInstancesConnecting.html)
- [Security Group Rules](https://docs.aws.amazon.com/vpc/latest/userguide/security-group-rules.html)

### Dependency Installation
If dependencies fail to install:
- Verify Python version (3.11+ required)
- Check internet connectivity
- Ensure pip is up to date

Resources:
- [Python Installation Guide](https://docs.python.org/3/using/index.html)
- [Pip Documentation](https://pip.pypa.io/en/stable/)

### Assistant Runtime Issues
If the assistant fails to run:
- Verify all required files were copied correctly
- Check AWS credentials are properly configured
- Review EC2 instance role permissions

Resources:
- [AWS Credentials Troubleshooting](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-quickstart.html)
- [IAM Troubleshooting](https://docs.aws.amazon.com/IAM/latest/UserGuide/troubleshoot.html)

## 📚 Additional Resources

- [AWS Security Best Practices](https://aws.amazon.com/security/security-learning/)
- [AWS Well-Architected Framework](https://aws.amazon.com/architecture/well-architected/)
- [IAM Security Best Practices](https://docs.aws.amazon.com/IAM/latest/UserGuide/best-practices.html)
- [AWS CLI User Guide](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)
- [Python AWS SDK (boto3) Documentation](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html)
- [Terraform AWS Provider Documentation](https://registry.terraform.io/providers/hashicorp/aws/latest/docs)

## 🆘 Support

For issues or questions:
1. Review the troubleshooting section above
2. Check [AWS Documentation](https://docs.aws.amazon.com/)
3. Visit the [AWS Support Center](https://console.aws.amazon.com/support/home)
4. Submit issues through the project's issue tracker

## ⚖️ License

This project is licensed under the Apache License 2.0 - see the LICENSE file for details.
41 changes: 41 additions & 0 deletions 02-samples/13-aws-audit-assistant/ai_assistant.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
## ⚠️⚠️ PLEASE READ : The script agent creates and executes the script that may perform changes to your environment, always execute it from a sandbox (sample attached in sandbox folder) with readonly permissions to avoid any issues ⚠️⚠️

from strands import Agent,tool
from strands.models.bedrock import BedrockModel
from strands_tools import calculator, file_read, shell,http_request,python_repl, editor, journal
from aws_document_agent import doc_retrieve as doc_agent
from strands_boto_agent import code_assistant
import os
os.environ["BYPASS_TOOL_CONSENT"] = "true"
os.environ["STRANDS_TOOL_CONSOLE_MODE"] = "disabled"


@tool
def report_generator(query: str) -> str:
"""
Report generator agent which is used to generate a report for the given output from the coding agent

Args:
output from coding agent's script
Returns:
str: A summary of results and recommendations for the specified AWS service, extracted from output of coding agent.
include summary at the start, details and recommendation after that, include resource names in details when possible.

"""




bedrock_model = BedrockModel(model_id="anthropic.claude-3-5-sonnet-20241022-v2:0", temperature=0.4)
agent = Agent(
system_prompt="You are a helpful assistant. Use the agents and tools to assist the user" \
" when user asks for auditing a resource, first gather the best practices for that service or resource using doc agent" \
"example : user asks to audit an s3 bucket, first get best practices for setting up s3 bucket" \
"Once you best practices, use the coding agent to create and execute necessary code to audit the service " \
"Finally generate a professional looking report from the output of the coding agents results",
tools=[doc_agent,code_assistant,report_generator],
model=bedrock_model
)

response = agent("audit my s3 bucket for best practice, bucket name is testingbucket101 in us-east-1 region")
print(response)
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
40 changes: 40 additions & 0 deletions 02-samples/13-aws-audit-assistant/aws_document_agent.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
from strands import Agent, tool
from strands.tools.mcp import MCPClient
from mcp import stdio_client, StdioServerParameters

@tool
def doc_retrieve(query:str) -> str:
"""
Documentation retrival agent which is used to gather information about best practices of the given service

Args:
query (str): The name of the AWS service to get best practices for. For example: "Amazon S3", "Amazon EC2", etc.

Returns:
str: A summary of best practices and recommendations for the specified AWS service, extracted from official documentation.

Example:
>>> doc_retrieve("audit my Amazon S3 bucket for best practices, bucket name is testbucket101")
"Best practices for Amazon S3:
1. Use bucket policies to control access
2. Enable versioning for data protection
3. Configure lifecycle policies
..." """


system_prompt = """
You are a helpful agent that is going to read the documentation and provide summary of the best practices for a service.

"""
aws_client = MCPClient(
lambda: stdio_client(StdioServerParameters(command="uvx", args=["awslabs.aws-documentation-mcp-server@latest"]))
)

with aws_client:
try:
agent = Agent(tools=aws_client.list_tools_sync(), system_prompt=system_prompt)
response = agent(query)


except Exception as e:
print(f"An error occurred: {e}")
6 changes: 6 additions & 0 deletions 02-samples/13-aws-audit-assistant/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
strands-agents>=0.1.0
boto3>=1.28.0
botocore>=1.31.0
mcp>=0.1.0
uv
strands-agents-tools>=0.1.0
Loading