devops-deploy
Compare original and translation side by side
🇺🇸
Original
English🇨🇳
Translation
ChineseDEVOPS-DEPLOY — Da Ideia para Producao
DEVOPS-DEPLOY — 从想法到生产环境
Overview
概述
DevOps e deploy de aplicacoes — Docker, CI/CD com GitHub Actions, AWS Lambda, SAM, Terraform, infraestrutura como codigo e monitoramento. Ativar para: dockerizar aplicacao, configurar pipeline CI/CD, deploy na AWS, Lambda, ECS, configurar GitHub Actions, Terraform, rollback, blue-green deploy, health checks, alertas.
应用程序的DevOps与部署——Docker、基于GitHub Actions的CI/CD、AWS Lambda、SAM、Terraform、基础设施即代码以及监控。适用于:应用容器化、配置CI/CD流水线、AWS部署、Lambda、ECS、配置GitHub Actions、Terraform、回滚、蓝绿部署、健康检查、告警。
When to Use This Skill
何时使用此技能
- When you need specialized assistance with this domain
- 当您需要该领域的专业协助时
Do Not Use This Skill When
何时不使用此技能
- The task is unrelated to devops deploy
- A simpler, more specific tool can handle the request
- The user needs general-purpose assistance without domain expertise
- 任务与DevOps部署无关
- 更简单、更专用的工具可以处理请求
- 用户需要无领域专业知识的通用协助
How It Works
工作原理
"Move fast and don't break things." — Engenharia de elite nao e lenta. E rapida e confiavel ao mesmo tempo.
"快速行动,不破坏现有系统。" — 精英工程不是缓慢的,而是既快速又可靠。
Dockerfile Otimizado (Python)
优化的Dockerfile(Python)
dockerfile
FROM python:3.11-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir --user -r requirements.txt
FROM python:3.11-slim
WORKDIR /app
COPY /root/.local /root/.local
COPY . .
ENV PATH=/root/.local/bin:$PATH
ENV PYTHONUNBUFFERED=1
EXPOSE 8000
HEALTHCHECK CMD curl -f http://localhost:8000/health || exit 1
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]dockerfile
FROM python:3.11-slim AS builder
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir --user -r requirements.txt
FROM python:3.11-slim
WORKDIR /app
COPY /root/.local /root/.local
COPY . .
ENV PATH=/root/.local/bin:$PATH
ENV PYTHONUNBUFFERED=1
EXPOSE 8000
HEALTHCHECK CMD curl -f http://localhost:8000/health || exit 1
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]Docker Compose (Dev Local)
Docker Compose(本地开发)
yaml
version: "3.9"
services:
app:
build: .
ports: ["8000:8000"]
environment:
- ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
volumes:
- .:/app
depends_on: [db, redis]
db:
image: postgres:15
environment:
POSTGRES_DB: auri
POSTGRES_USER: auri
POSTGRES_PASSWORD: ${DB_PASSWORD}
volumes:
- pgdata:/var/lib/postgresql/data
redis:
image: redis:7-alpine
volumes:
pgdata:yaml
version: "3.9"
services:
app:
build: .
ports: ["8000:8000"]
environment:
- ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
volumes:
- .:/app
depends_on: [db, redis]
db:
image: postgres:15
environment:
POSTGRES_DB: auri
POSTGRES_USER: auri
POSTGRES_PASSWORD: ${DB_PASSWORD}
volumes:
- pgdata:/var/lib/postgresql/data
redis:
image: redis:7-alpine
volumes:
pgdata:Sam Template (Serverless)
Sam模板(无服务器)
yaml
undefinedyaml
undefinedTemplate.Yaml
Template.Yaml
AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Globals:
Function:
Timeout: 30
Runtime: python3.11
Environment:
Variables:
ANTHROPIC_API_KEY: !Ref AnthropicApiKey
DYNAMODB_TABLE: !Ref AuriTable
Resources:
AuriFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: src/
Handler: lambda_function.handler
MemorySize: 512
Policies:
- DynamoDBCrudPolicy:
TableName: !Ref AuriTable
AuriTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: auri-users
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: userId
AttributeType: S
KeySchema:
- AttributeName: userId
KeyType: HASH
TimeToLiveSpecification:
AttributeName: ttl
Enabled: true
undefinedAWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Globals:
Function:
Timeout: 30
Runtime: python3.11
Environment:
Variables:
ANTHROPIC_API_KEY: !Ref AnthropicApiKey
DYNAMODB_TABLE: !Ref AuriTable
Resources:
AuriFunction:
Type: AWS::Serverless::Function
Properties:
CodeUri: src/
Handler: lambda_function.handler
MemorySize: 512
Policies:
- DynamoDBCrudPolicy:
TableName: !Ref AuriTable
AuriTable:
Type: AWS::DynamoDB::Table
Properties:
TableName: auri-users
BillingMode: PAY_PER_REQUEST
AttributeDefinitions:
- AttributeName: userId
AttributeType: S
KeySchema:
- AttributeName: userId
KeyType: HASH
TimeToLiveSpecification:
AttributeName: ttl
Enabled: true
undefinedDeploy Commands
部署命令
bash
undefinedbash
undefinedBuild E Deploy
构建与部署
sam build
sam deploy --guided # primeira vez
sam deploy # deploys seguintes
sam build
sam deploy --guided # 首次部署
sam deploy # 后续部署
Deploy Rapido (Sem Confirmacao)
快速部署(无需确认)
sam deploy --no-confirm-changeset --no-fail-on-empty-changeset
sam deploy --no-confirm-changeset --no-fail-on-empty-changeset
Ver Logs Em Tempo Real
查看实时日志
sam logs -n AuriFunction --tail
sam logs -n AuriFunction --tail
Deletar Stack
删除堆栈
sam delete
---sam delete
---.Github/Workflows/Deploy.Yml
.Github/Workflows/Deploy.Yml
name: Deploy Auri
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with: { python-version: "3.11" }
- run: pip install -r requirements.txt
- run: pytest tests/ -v --cov=src --cov-report=xml
- uses: codecov/codecov-action@v4
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: pip install bandit safety
- run: bandit -r src/ -ll
- run: safety check -r requirements.txt
deploy:
needs: [test, security]
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: aws-actions/setup-sam@v2
- uses: aws-actions/configure-aws-credentials@v4
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: us-east-1
- run: sam build
- run: sam deploy --no-confirm-changeset
- name: Notify Telegram on Success
run: |
curl -s -X POST "https://api.telegram.org/bot${{ secrets.TELEGRAM_BOT_TOKEN }}/sendMessage"
-d "chat_id=${{ secrets.TELEGRAM_CHAT_ID }}"
-d "text=Auri deployed successfully! Commit: ${{ github.sha }}"
-d "chat_id=${{ secrets.TELEGRAM_CHAT_ID }}"
-d "text=Auri deployed successfully! Commit: ${{ github.sha }}"
---name: Deploy Auri
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v5
with: { python-version: "3.11" }
- run: pip install -r requirements.txt
- run: pytest tests/ -v --cov=src --cov-report=xml
- uses: codecov/codecov-action@v4
security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: pip install bandit safety
- run: bandit -r src/ -ll
- run: safety check -r requirements.txt
deploy:
needs: [test, security]
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: aws-actions/setup-sam@v2
- uses: aws-actions/configure-aws-credentials@v4
with:
aws-access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
aws-secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
aws-region: us-east-1
- run: sam build
- run: sam deploy --no-confirm-changeset
- name: Notify Telegram on Success
run: |
curl -s -X POST "https://api.telegram.org/bot${{ secrets.TELEGRAM_BOT_TOKEN }}/sendMessage"
-d "chat_id=${{ secrets.TELEGRAM_CHAT_ID }}"
-d "text=Auri deployed successfully! Commit: ${{ github.sha }}"
-d "chat_id=${{ secrets.TELEGRAM_CHAT_ID }}"
-d "text=Auri deployed successfully! Commit: ${{ github.sha }}"
---Health Check Endpoint
健康检查端点
python
from fastapi import FastAPI
import time, os
app = FastAPI()
START_TIME = time.time()
@app.get("/health")
async def health():
return {
"status": "healthy",
"uptime_seconds": time.time() - START_TIME,
"version": os.environ.get("APP_VERSION", "unknown"),
"environment": os.environ.get("ENV", "production")
}python
from fastapi import FastAPI
import time, os
app = FastAPI()
START_TIME = time.time()
@app.get("/health")
async def health():
return {
"status": "healthy",
"uptime_seconds": time.time() - START_TIME,
"version": os.environ.get("APP_VERSION", "unknown"),
"environment": os.environ.get("ENV", "production")
}Alertas Cloudwatch
CloudWatch告警
python
import boto3
def create_error_alarm(function_name: str, sns_topic_arn: str):
cw = boto3.client("cloudwatch")
cw.put_metric_alarm(
AlarmName=f"{function_name}-errors",
MetricName="Errors",
Namespace="AWS/Lambda",
Dimensions=[{"Name": "FunctionName", "Value": function_name}],
Period=300,
EvaluationPeriods=1,
Threshold=5,
ComparisonOperator="GreaterThanThreshold",
AlarmActions=[sns_topic_arn],
TreatMissingData="notBreaching"
)python
import boto3
def create_error_alarm(function_name: str, sns_topic_arn: str):
cw = boto3.client("cloudwatch")
cw.put_metric_alarm(
AlarmName=f"{function_name}-errors",
MetricName="Errors",
Namespace="AWS/Lambda",
Dimensions=[{"Name": "FunctionName", "Value": function_name}],
Period=300,
EvaluationPeriods=1,
Threshold=5,
ComparisonOperator="GreaterThanThreshold",
AlarmActions=[sns_topic_arn],
TreatMissingData="notBreaching"
)5. Checklist De Producao
5. 生产环境检查清单
- Variaveis de ambiente via Secrets Manager (nunca hardcoded)
- Health check endpoint respondendo
- Logs estruturados (JSON) com request_id
- Rate limiting configurado
- CORS restrito a dominios autorizados
- DynamoDB com backup automatico ativado
- Lambda com timeout adequado (10-30s)
- CloudWatch alarmes para erros e latencia
- Rollback plan documentado
- Load test antes do lancamento
- 通过Secrets Manager管理环境变量(绝不硬编码)
- 健康检查端点正常响应
- 结构化日志(JSON格式)包含request_id
- 已配置速率限制
- CORS限制为授权域名
- DynamoDB已启用自动备份
- Lambda设置了合适的超时时间(10-30秒)
- CloudWatch已配置错误和延迟告警
- 已记录回滚计划
- 发布前已进行负载测试
6. Comandos
6. 命令
| Comando | Acao |
|---|---|
| Dockeriza a aplicacao |
| Deploy completo na AWS Lambda |
| Configura GitHub Actions pipeline |
| Configura CloudWatch e alertas |
| Roda checklist pre-lancamento |
| Plano de rollback para versao anterior |
| 命令 | 操作 |
|---|---|
| 将应用容器化 |
| 在AWS Lambda完成完整部署 |
| 配置GitHub Actions流水线 |
| 配置CloudWatch和告警 |
| 运行发布前检查清单 |
| 回滚到上一版本的计划 |
Best Practices
最佳实践
- Provide clear, specific context about your project and requirements
- Review all suggestions before applying them to production code
- Combine with other complementary skills for comprehensive analysis
- 提供关于项目和需求的清晰、具体的上下文
- 在应用到生产代码前审查所有建议
- 结合其他互补技能进行全面分析
Common Pitfalls
常见陷阱
- Using this skill for tasks outside its domain expertise
- Applying recommendations without understanding your specific context
- Not providing enough project context for accurate analysis
- 将此技能用于其领域专业知识之外的任务
- 在不了解具体上下文的情况下应用建议
- 未提供足够的项目上下文以进行准确分析
Limitations
局限性
- Use this skill only when the task clearly matches the scope described above.
- Do not treat the output as a substitute for environment-specific validation, testing, or expert review.
- Stop and ask for clarification if required inputs, permissions, safety boundaries, or success criteria are missing.
- 仅当任务明确符合上述描述的范围时使用此技能。
- 不要将输出视为特定环境验证、测试或专家评审的替代品。
- 如果缺少所需的输入、权限、安全边界或成功标准,请停止并请求澄清。