数据项目如何实施CI/CD?
中等
答题要点
# .github/workflows/data-pipeline-ci.yml
name: Data Pipeline CI/CD
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:14
env:
POSTGRES_PASSWORD: test
ports:
- 5432:5432
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.11'
- name: Install dependencies
run: |
pip install -r requirements.txt
pip install -r requirements-dev.txt
- name: Run linting
run: |
black --check .
ruff check .
mypy src/
- name: Run unit tests
run: pytest tests/unit -v --cov=src
- name: Run integration tests
run: pytest tests/integration -v
env:
DATABASE_URL: postgresql://postgres:test@localhost:5432/test
- name: Upload coverage
uses: codecov/codecov-action@v3
deploy-staging:
needs: test
if: github.ref == 'refs/heads/develop'
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Deploy to staging
run: |
# 部署DAG到Airflow staging
aws s3 sync dags/ s3://airflow-staging/dags/
# 触发DAG测试
curl -X POST "https://airflow-staging.example.com/api/v1/dags/test_dag/dagRuns"
deploy-production:
needs: test
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v3
- name: Deploy to production
run: |
aws s3 sync dags/ s3://airflow-prod/dags/
# 通知
curl -X POST -H 'Content-type: application/json' \
--data '{"text":"Data pipeline deployed to production"}' \
$SLACK_WEBHOOK
# 部署脚本
import subprocess
import sys
def run_checks():
"""运行所有检查"""
checks = [
("Format check", "black --check ."),
("Lint", "ruff check ."),
("Type check", "mypy src/"),
("Unit tests", "pytest tests/unit -v"),
]
for name, cmd in checks:
print(f"Running: {name}")
result = subprocess.run(cmd, shell=True)
if result.returncode != 0:
print(f"❌ {name} failed")
sys.exit(1)
print(f"✅ {name} passed")
def deploy(environment: str):
"""部署到指定环境"""
if environment == 'staging':
bucket = 's3://airflow-staging/dags/'
elif environment == 'production':
bucket = 's3://airflow-prod/dags/'
else:
raise ValueError(f"Unknown environment: {environment}")
subprocess.run(f"aws s3 sync dags/ {bucket}", shell=True, check=True)
print(f"✅ Deployed to {environment}")
if __name__ == '__main__':
run_checks()
if len(sys.argv) > 1:
deploy(sys.argv[1])
完整解析在题库里看
核心知识点、易错点和面试官想听到什么;练过的题会进入记录,答错的进错题本。
去练这道题