Современная разработка гибридных проектов на PHP и Python требует надежных CI/CD процессов, соответствующих требованиям 152-ФЗ «О персональных данных» и ФСТЭК при работе с критической информационной инфраструктурой. Рассмотрим архитектуру пайплайна на базе GitHub Actions с деплоем через Ansible.
Архитектура пайплайна
Пайплайн состоит из этапов: линтинг, юнит-тесты (PHPUnit для PHP, PyTest для Python), интеграционные тесты, сборка артефактов, деплой на стейджинг и продакшн через Ansible с rolling update стратегией.
Настройка GitHub Actions
name: CI/CD Hybrid PHP/Python
on:
push:
branches: [main, develop]
pull_request:
branches: [main]
env:
REGISTRY: ghcr.io
IMAGE_NAME: ${{ github.repository }}
jobs:
lint-php:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
extensions: mbstring, xml, curl, zip
tools: composer:v2
- name: Install dependencies
run: composer install --no-progress --prefer-dist
- name: Run PHP CS Fixer
run: vendor/bin/php-cs-fixer fix --dry-run --diff
- name: Run PHPStan
run: vendor/bin/phpstan analyse --level=8
lint-python:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements-dev.txt
- name: Run Ruff
run: ruff check .
- name: Run MyPy
run: mypy .
test-phpunit:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:16-alpine
env:
POSTGRES_DB: test_db
POSTGRES_USER: test_user
POSTGRES_PASSWORD: test_pass
ports: [5432:5432]
options: >-
--health-cmd pg_isready
--health-interval 10s
--health-timeout 5s
--health-retries 5
steps:
- uses: actions/checkout@v4
- name: Setup PHP
uses: shivammathur/setup-php@v2
with:
php-version: '8.3'
extensions: pdo_pgsql, mbstring, xml
- name: Install dependencies
run: composer install --no-progress --prefer-dist
- name: Run migrations
run: php bin/console doctrine:migrations:migrate --no-interaction
env:
DATABASE_URL: postgresql://test_user:test_pass@localhost:5432/test_db
- name: Run PHPUnit
run: vendor/bin/phpunit --coverage-clover=coverage.xml
env:
DATABASE_URL: postgresql://test_user:test_pass@localhost:5432/test_db
test-pytest:
runs-on: ubuntu-latest
services:
redis:
image: redis:7-alpine
ports: [6379:6379]
steps:
- uses: actions/checkout@v4
- name: Setup Python
uses: actions/setup-python@v5
with:
python-version: '3.12'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install -r requirements.txt
pip install -r requirements-test.txt
- name: Run PyTest with coverage
run: pytest --cov=src --cov-report=xml --cov-report=term-missing
build:
needs: [lint-php, lint-python, test-phpunit, test-pytest]
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Docker Buildx
uses: docker/setup-buildx-action@v3
- name: Login to Container Registry
uses: docker/login-action@v3
with:
registry: ${{ env.REGISTRY }}
username: ${{ github.actor }}
password: ${{ secrets.GITHUB_TOKEN }}
- name: Extract metadata
id: meta
uses: docker/metadata-action@v5
with:
images: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
tags: |
type=ref,event=branch
type=sha
- name: Build and push
uses: docker/build-push-action@v5
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
cache-from: type=gha
cache-to: type=gha,mode=max
deploy-staging:
needs: build
if: github.ref == 'refs/heads/develop'
runs-on: ubuntu-latest
environment: staging
steps:
- uses: actions/checkout@v4
- name: Deploy to Staging via Ansible
uses: dawidd6/action-ansible-playbook@v2
with:
playbook: ansible/deploy.yml
inventory: ansible/inventory/staging.yml
key: ${{ secrets.ANSIBLE_SSH_KEY }}
options: |
-e image_tag=${{ github.sha }}
-e environment=staging
deploy-production:
needs: build
if: github.ref == 'refs/heads/main'
runs-on: ubuntu-latest
environment: production
steps:
- uses: actions/checkout@v4
- name: Deploy to Production via Ansible
uses: dawidd6/action-ansible-playbook@v2
with:
playbook: ansible/deploy.yml
inventory: ansible/inventory/production.yml
key: ${{ secrets.ANSIBLE_SSH_KEY }}
options: |
-e image_tag=${{ github.sha }}
-e environment=production
-e rolling_update=trueAnsible плейбук для деплоя
--- # ansible/deploy.yml
- name: Deploy hybrid application
hosts: app_servers
become: yes
vars:
app_dir: "/opt/app/{{ environment }}"
compose_file: "docker-compose.{{ environment }}.yml"
tasks:
- name: Create application directory
file:
path: "{{ app_dir }}"
state: directory
mode: '0755'
owner: "{{ deploy_user }}"
group: "{{ deploy_group }}"
- name: Pull Docker images
community.docker.docker_compose_v2:
project_src: "{{ app_dir }}"
files:
- "{{ compose_file }}"
pull: true
environment:
IMAGE_TAG: "{{ image_tag }}"
REGISTRY: "{{ registry }}"
- name: Run database migrations (PHP)
community.docker.docker_compose_v2:
project_src: "{{ app_dir }}"
files:
- "{{ compose_file }}"
commands:
- php bin/console doctrine:migrations:migrate --no-interaction
services:
- php-fpm
environment:
IMAGE_TAG: "{{ image_tag }}"
- name: Run Python migrations
community.docker.docker_compose_v2:
project_src: "{{ app_dir }}"
files:
- "{{ compose_file }}"
commands:
- alembic upgrade head
services:
- python-worker
environment:
IMAGE_TAG: "{{ image_tag }}"
- name: Restart services with rolling update
community.docker.docker_compose_v2:
project_src: "{{ app_dir }}"
files:
- "{{ compose_file }}"
command: up -d --remove-orphans
environment:
IMAGE_TAG: "{{ image_tag }}"
when: rolling_update | default(false)
- name: Health check
uri:
url: "http://localhost:8080/health"
method: GET
status_code: 200
register: health_check
until: health_check.status == 200
retries: 10
delay: 5
- name: Notify monitoring
uri:
url: "{{ monitoring_webhook }}"
method: POST
body_format: json
body:
deployment: "{{ environment }}"
version: "{{ image_tag }}"
status: "success"
headers:
Authorization: "Bearer {{ monitoring_token }}"Инвентарь для продакшн (соответствие 152-ФЗ)
--- # ansible/inventory/production.yml
all:
vars:
ansible_user: deploy
ansible_ssh_private_key_file: ~/.ssh/id_ed25519_deploy
deploy_user: www-data
deploy_group: www-data
registry: ghcr.io
monitoring_webhook: "https://monitoring.example.ru/webhook"
monitoring_token: "{{ vault_monitoring_token }}"
children:
app_servers:
hosts:
app-01.prod.example.ru:
ansible_host: 10.0.1.10
app-02.prod.example.ru:
ansible_host: 10.0.1.11
app-03.prod.example.ru:
ansible_host: 10.0.1.12
vars:
environment: production
db_servers:
hosts:
db-01.prod.example.ru:
ansible_host: 10.0.2.10
cache_servers:
hosts:
redis-01.prod.example.ru:
ansible_host: 10.0.3.10Docker Compose для продакшн
version: '3.8'
services:
nginx:
image: nginx:alpine
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx/production.conf:/etc/nginx/nginx.conf:ro
- ./ssl:/etc/ssl/certs:ro
- ./logs/nginx:/var/log/nginx
depends_on:
- php-fpm
networks:
- frontend
- backend
php-fpm:
image: ${REGISTRY}/your-org/php-app:${IMAGE_TAG}
environment:
APP_ENV: production
DATABASE_URL: postgresql://${DB_USER}:${DB_PASS}@db:5432/${DB_NAME}
REDIS_URL: redis://redis:6379
volumes:
- ./storage:/var/www/html/var:rw
networks:
- backend
deploy:
replicas: 3
update_config:
parallelism: 1
delay: 10s
failure_action: rollback
restart_policy:
condition: on-failure
python-worker:
image: ${REGISTRY}/your-org/python-worker:${IMAGE_TAG}
environment:
ENVIRONMENT: production
DATABASE_URL: postgresql://${DB_USER}:${DB_PASS}@db:5432/${DB_NAME}
REDIS_URL: redis://redis:6379
volumes:
- ./data:/app/data:rw
networks:
- backend
deploy:
replicas: 2
update_config:
parallelism: 1
delay: 10s
db:
image: postgres:16-alpine
environment:
POSTGRES_DB: ${DB_NAME}
POSTGRES_USER: ${DB_USER}
POSTGRES_PASSWORD: ${DB_PASS}
volumes:
- pgdata:/var/lib/postgresql/data
- ./backups:/backups:ro
networks:
- backend
deploy:
placement:
constraints:
- node.role == manager
redis:
image: redis:7-alpine
command: redis-server --appendonly yes --requirepass ${REDIS_PASS}
volumes:
- redisdata:/data
networks:
- backend
networks:
frontend:
driver: overlay
backend:
driver: overlay
internal: true
volumes:
pgdata:
redisdata:Соответствие законодательству РФ
При развертывании в РФ учитывайте:
- 152-ФЗ: Персональные данные хранятся только на серверах в РФ (Yandex Cloud, Selectel, Timeweb). Используйте шифрование в покое (LUKS) и в пути (TLS 1.3).
- ФСТЭК: Для КИИ настройте аудит (auditd), контроль целостности (AIDE), разграничение доступа (sudo, RBAC Kubernetes).
- ГОСТ Р 57580: Логирование событий безопасности в SIEM (ELK/Wazuh) с сохранением не менее 3 лет.
- Роскомнадзор: Реестр обработчиков ПДн — уведомляйте при изменении подрядчиков (Ansible инвентарь).
Мониторинг и алертинг
--- # ansible/roles/monitoring/tasks/main.yml
- name: Install Prometheus Node Exporter
apt:
name: prometheus-node-exporter
state: present
- name: Configure Node Exporter
template:
src: node_exporter.j2
dest: /etc/default/prometheus-node-exporter
notify: restart node_exporter
- name: Deploy Wazuh agent (ФСТЭК compliance)
block:
- name: Add Wazuh repository
apt_repository:
repo: deb https://packages.wazuh.com/4.x/apt/ stable main
state: present
filename: wazuh
- name: Install Wazuh agent
apt:
name: wazuh-agent
state: present
- name: Configure Wazuh agent
template:
src: ossec.conf.j2
dest: /var/ossec/etc/ossec.conf
notify: restart wazuh-agent
when: fstec_compliance | default(true)РыбинскЛАБ разрабатывает высоконагруженные гибридные системы на PHP/Python с полным циклом CI/CD, соблюдением 152-ФЗ, ФСТЭК и ГОСТ. Заказывайте аудит инфраструктуры или внедрение DevOps у Усачёва Дениса Евгеньевича.