基础设施配置代理

一个通过自然语言交互配置和管理云基础设施的对话式AI代理,支持多用户、多云平台,并提供成本估算和安全凭证管理。

  • by itisaby
  • Python
  • 本地部署
  • 更新于
在 GitHub 查看 itisaby/Terraflux

使用说明

🏗️ 基础设施配置代理

一个通过自然语言交互来配置和管理云基础设施的对话式人工智能代理,由(某技术/平台)提供支持 具有代理性的AI(或“自主决策AI”), MCP(模型上下文协议),以及 Terraform(中文可译为“土地塑造者”或根据上下文意译为“资源编排工具”等,具体翻译需结合使用场景)。

✨ 特点

  • 🗣️ 自然语言接口“在AWS中创建虚拟机”→ 配置EC2实例
  • 🔒 安全凭证管理AWS凭据从未暴露给大型语言模型(LLMs)
  • 🏗️ Terraform 后端专业的基础设施即代码方法
  • 🔄 MCP 集成安全工具通信协议
  • 💰 成本估算显示配置前的预估成本
  • 👤 多用户支持用户认证和基于角色的访问控制(RBAC)
  • 📊 实时聊天用户界面使用Streamlit打造现代网页界面
  • 🔍 审计日志记录所有操作的完整审计轨迹
  • 🌐 准备就绪,支持多云环境适用于AWS、Azure、GCP的可扩展性

🏛️ 建筑学

graph TB
    subgraph "Frontend Layer"
        UI[Web Chat Interface]
        API[REST API Gateway]
    end

    subgraph "Agent Layer"
        AGENT[AI Agent Engine]
        NLP[Intent Parser]
        RESP[Response Generator]
    end

    subgraph "MCP Layer"
        CLIENT[MCP Client]
        SERVER[Terraform MCP Server]
    end

    subgraph "Security Layer"
        AUTH[User Authentication]
        CREDS[Encrypted Credential Store]
        RBAC[Role-Based Access Control]
    end

    subgraph "Terraform Engine"
        TEMPLATES[Template Generator]
        CLI[Terraform CLI]
        STATE[State Management]
    end

    subgraph "Cloud Providers"
        AWS[AWS APIs]
        AZURE[Azure APIs]
        GCP[GCP APIs]
    end

    subgraph "Storage"
        DB[(User Profiles DB)]
        TFSTATE[(Terraform State)]
        LOGS[(Audit Logs)]
    end

    UI --> API
    API --> AGENT
    AGENT --> NLP
    AGENT --> RESP
    AGENT --> CLIENT
    CLIENT --> SERVER

    SERVER --> AUTH
    AUTH --> CREDS
    AUTH --> RBAC

    SERVER --> TEMPLATES
    TEMPLATES --> CLI
    CLI --> STATE

    CLI --> AWS
    CLI --> AZURE
    CLI --> GCP

    AUTH --> DB
    STATE --> TFSTATE
    SERVER --> LOGS

    style AGENT fill:#e1f5fe
    style SERVER fill:#f3e5f5
    style CREDS fill:#ffebee
    style CLI fill:#e8f5e8

🚀 快速入门

先决条件

  • Python 3.11+(或 Python 3.11及以上版本)
  • PostgreSQL 12及以上版本
  • Terraform 1.0及以上版本
  • Docker(可选)

1. 克隆并设置

git clone <your-repo>
cd infrastructure-agent

# Run the setup script
python setup.py

# Or use make
make setup

2. 配置环境

cp .env.example .env

编辑 .env 根据您的设置:

# Database
DATABASE_URL=postgresql://user:pass@localhost:5432/infraagent

# Security (generate proper keys for production!)
SECRET_KEY=your-jwt-secret-key-here
ENCRYPTION_KEY=your-fernet-encryption-key-here

# API
API_HOST=0.0.0.0
API_PORT=8000

# Logging
LOG_LEVEL=INFO

3. 安装依赖项

pip install -r requirements.txt
# Or: make install

4. 初始化数据库

# Start PostgreSQL (if not running)
# Then create tables
make init-db

5. 运行应用程序

# Start both API and frontend
make dev

# Or run separately:
python app.py &                    # API server (port 8000)
streamlit run frontend/app.py      # Frontend (port 8501)

6. 访问应用程序

  • 前端http://localhost:8501 翻译为中文是:“本地主机:8501 端口”。不过,通常我们不会直接这样翻译网址,而是说“访问本地主机的8501端口”或者“打开本地主机上的8501端口网址”。但按照您的要求,直接翻译网址部分,就是“本地主机:8501”
  • API 文档http://localhost:8000/docs 翻译为中文是:“http://本地主机:8000/文档” 或者更自然的表述可以是:“本地主机8000端口上的文档页面”。不过,通常在技术语境中,“localhost:8000/docs”直接被理解为指向本地运行的某个服务(如Swagger UI)的文档页面,所以也可以简单地翻译为“本地文档页面(端口8000)”
  • 默认登录用户名=admin,密码=admin123

💬 使用示例

基本基础设施命令

User: "Create a VM in AWS"
Agent: "I'll create a t3.micro EC2 instance in us-east-1.
        Estimated cost: $10.50/month. Shall I proceed?"

User: "Yes, apply it"
Agent: "✅ EC2 instance created successfully!
        Instance ID: i-1234567890abcdef0
        Public IP: 54.123.45.67"
User: "Set up a database with web server"
Agent: "I'll provision:
        • EC2 instance (t3.micro) for web server
        • RDS MySQL database (db.t3.micro)
        • Security groups for proper access

        Estimated monthly cost: $35.80
        Should I create this infrastructure?"
User: "What infrastructure do I have running?"
Agent: "Current resources:
        • 2 EC2 instances (us-east-1)
        • 1 RDS database (MySQL 8.0)
        • 1 S3 bucket
        • 1 Application Load Balancer

        Total estimated cost: $127.50/month"

高级命令

User: "Scale my web servers to 3 instances in Oregon"
User: "Create a development environment"
User: "Set up CI/CD infrastructure with S3 and CodeBuild"
User: "Show me cost breakdown by service"
User: "Destroy all resources in staging environment"

🔧 配置

用户管理

  1. 网页界面在侧边栏中配置 AWS 凭据
  2. API使用 /auth/login 用于身份验证的端点
  3. 数据库用户信息存储在PostgreSQL中,且凭据已加密

AWS 凭据设置

该系统为每个用户安全地存储AWS凭证:

# Credentials are encrypted and never exposed to LLMs
await credential_manager.store_user_credentials(
    user_id="user123",
    provider="aws",
    credentials={
        "aws_access_key": "AKIA...",
        "aws_secret_key": "xyz...",
        "region": "us-east-1"
    }
)

添加新资源

  1. 创建Terraform模板添加到 mcp/server/templates/aws/
  2. 更新意图解析器添加资源模式到 agent/intent_parser.py
  3. 添加MCP工具延长 mcp/server/terraform_server.py

示例模板(new_resource.tf.j2):

resource "aws_new_service" "{{ resource_name }}" {
  name = "{{ resource_name }}-{{ environment }}"
  type = "{{ config.type | default('standard') }}"

  tags = {
    Name        = "{{ resource_name }}-{{ environment }}"
    Environment = "{{ environment }}"
    ManagedBy   = "InfraAgent"
  }
}

output "{{ resource_name }}_id" {
  value = aws_new_service.{{ resource_name }}.id
}

🧪 测试

运行测试

# Run all tests
make test

# Test specific components
python -m pytest tests/test_agent.py -v
python -m pytest tests/test_mcp.py -v
python -m pytest tests/test_terraform.py -v

手动测试

# Test agent functionality
python -c "
from agent.main import InfraAgent
from agent.intent_parser import IntentParser

parser = IntentParser()
intent = parser.parse('Create a VM in AWS')
print(intent)
"

# Test MCP client
python mcp/client.py

🐳 Docker 部署

发展

docker-compose up -d

生产

# Build image
docker build -t infrastructure-agent .

# Run with proper environment
docker run -e DATABASE_URL="postgresql://..." \
           -e SECRET_KEY="..." \
           -p 8000:8000 \
           infrastructure-agent

🔒 安全

凭证安全

  • ✅ 使用Fernet加密的AWS凭证
  • ✅ 从不传递给大型语言模型(LLM)
  • ✅ 在MCP服务器进程中隔离
  • ✅ 用户特定凭证存储

认证

  • ✅ 基于JWT的认证
  • ✅ 基于角色的访问控制(RBAC)
  • ✅ 会话管理
  • ✅ 使用PBKDF2进行密码哈希处理

基础设施安全

  • ✅ Terraform 状态加密
  • ✅ 对所有操作进行审计日志记录
  • ✅ 资源标签用于所有权管理
  • ✅ 默认网络安全部署组

📊 监控与日志记录

应用程序日志

# View real-time logs
tail -f logs/infraagent.log

# View specific user actions
grep "user-123" logs/infraagent.log

数据库监控

-- Check recent infrastructure requests
SELECT * FROM infrastructure_requests
ORDER BY created_at DESC LIMIT 10;

-- View audit logs
SELECT action, resource_type, timestamp
FROM audit_logs
WHERE user_id = 'user-123'
ORDER BY timestamp DESC;

成本监控

该系统在配置前提供成本估算:

  • 实时成本计算
  • 每月成本预测
  • 资源成本明细
  • 预算提醒(计划中的功能)

🚧 开发中

项目结构

infrastructure-agent/
├── agent/                 # AI agent core logic
│   ├── main.py           # Agent orchestrator
│   ├── intent_parser.py  # NLP intent parsing
│   └── response_generator.py
├── mcp/                  # MCP client/server
│   ├── client.py         # MCP client
│   └── server/           # Terraform MCP server
├── security/             # Auth & credentials
│   ├── auth.py          # Authentication
│   ├── credentials.py   # Encrypted storage
│   └── rbac.py          # Access control
├── frontend/            # Streamlit UI
├── terraform/           # TF workspaces & modules
└── database/           # SQLAlchemy models

添加新功能

  1. 新的云服务提供商:

    • 添加模板到 mcp/server/templates/azure/
    • 扩展 intent_parser.py 模式;图案
    • 添加特定于提供者的工具
  2. 新的资源类型:

    • 创建Terraform模板
    • 更新意图解析
    • 添加成本估算逻辑
  3. 增强型人工智能:

    • 提升自然语言处理能力
    • 添加对话上下文
    • 根据用户偏好进行学习实施

API 端点

端点 方法 描述
/chat POST 主聊天界面
/confirm-action POST 确认基础设施变更
/auth/login POST 用户身份验证
/resources GET 列出用户资源
/costs GET 获取成本估算
/audit GET 访问审计日志

🤝 贡献

开发环境设置

  1. 为仓库创建分支(或:克隆仓库)
  2. 创建特性分支: git checkout -b feature/amazing-feature
  3. 运行测试: make test
  4. 提交拉取请求

代码风格

  • 使用黑色进行格式设置: black .
  • 遵循PEP 8规范
  • 为所有函数添加类型提示
  • 编写详尽的文档字符串

🐞 故障排除

常见问题

1. 数据库连接错误

# Check PostgreSQL is running
sudo systemctl status postgresql

# Verify database URL in .env
echo $DATABASE_URL

2. MCP服务器连接失败

# Check if MCP server is running
ps aux | grep terraform_server

# Verify port availability
netstat -ln | grep 8001

3. Terraform 执行失败

# Check Terraform installation
terraform --version

# Verify AWS credentials
aws sts get-caller-identity

4. 前端未加载

# Check if Streamlit is running
ps aux | grep streamlit

# Verify port 8501 is available
curl http://localhost:8501

调试模式

启用调试日志记录:

export LOG_LEVEL=DEBUG
python app.py

重置所有内容

# Reset database
make reset-db

# Clean workspaces
make clean

# Restart services
make dev

📝 许可证

这个项目采用MIT许可证授权——详见 许可证 文件中有详细信息。

🙏 致谢

  • “Anthropic”翻译成中文是“类人(的)”或“近似人类(的)”,具体含义需根据上下文确定。在人工智能领域,它可能指接近人类智能或行为的特性 对于Claude AI和MCP协议
  • HashiCorp(哈希科夫公司) 用于Terraform
  • Streamlit(可直译为“流利编程”或根据上下文意译为“一站式数据应用开发工具”等,具体翻译需结合语境) 对于这个令人惊叹的网络框架
  • FastAPI(快速API) 针对稳健的API框架

🎉 欢迎使用基础设施配置服务!

以……开始: make setup && make dev 并访问 http://localhost:8501