|
1 |
| -# Lesson 13 |
| 1 | +--- |
| 2 | +title: Занятие 13 |
| 3 | +description: CI/CD с GitHub Actions. Автоматизация разработки JS приложений с помощью GitHub Actions — настройка workflow, деплой, тестирование и лучшие практики |
| 4 | +--- |
| 5 | + |
| 6 | +## CI/CD с [GitHub Actions](https://docs.github.com/en/actions) |
| 7 | + |
| 8 | +**Автоматизация разработки для JavaScript проектов** |
| 9 | + |
| 10 | +<!--v--> |
| 11 | + |
| 12 | +### Что такое CI/CD и зачем это нужно? |
| 13 | + |
| 14 | +**Continuous Integration / Continuous Deployment** |
| 15 | + |
| 16 | +**CI (Continuous Integration)** — автоматическая интеграция и тестирование кода при каждом коммите ([Wikipedia](https://ru.wikipedia.org/wiki/Непрерывная_интеграция)) |
| 17 | + |
| 18 | +**CD (Continuous Deployment)** — автоматический деплой готового кода в продакшн ([Martin Fowler](https://martinfowler.com/bliki/ContinuousDelivery.html)) |
| 19 | + |
| 20 | +<!--v--> |
| 21 | + |
| 22 | +#### Зачем нужен CI/CD? |
| 23 | + |
| 24 | +- **Быстрые циклы разработки** — от идеи до продакшна за минуты ([GitHub Blog](https://github.blog/enterprise-software/ci-cd/build-ci-cd-pipeline-github-actions-four-steps/)) |
| 25 | +- **Меньше багов** — автоматическое тестирование на каждом этапе ([Spacelift Tutorial](https://spacelift.io/blog/github-actions-tutorial)) |
| 26 | +- **Надёжность** — стабильные и предсказуемые релизы ([Dev.to Guide](https://dev.to/vishnusatheesh/how-to-set-up-a-cicd-pipeline-with-github-actions-for-automated-deployments-j39)) |
| 27 | +- **Экономия времени** — никаких ручных операций ([GitHub Docs](https://docs.github.com/en/actions)) |
| 28 | + |
| 29 | +<!--v--> |
| 30 | + |
| 31 | +#### Вопросы? |
| 32 | + |
| 33 | +<!--s--> |
| 34 | + |
| 35 | +### [GitHub Actions](https://docs.github.com/en/actions) — встроенная CI/CD платформа |
| 36 | + |
| 37 | +- Запускается от событий в репозитории (push, PR, release) ([Workflow Syntax](https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions)) |
| 38 | +- Виртуальные машины на Linux, Windows, macOS ([Runner Types](https://docs.github.com/en/actions/using-github-hosted-runners/about-github-hosted-runners)) |
| 39 | +- Более **20 000 готовых Actions** в [Marketplace](https://github.com/marketplace?type=actions) |
| 40 | +- **Бесплатно**: 2000 минут в месяц для приватных репозиториев ([Free Tier Details](https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions)) |
| 41 | + |
| 42 | +<!--v--> |
| 43 | + |
| 44 | +### Плюсы конфигурации через файлы |
| 45 | + |
| 46 | +**Infrastructure as Code** для CI/CD |
| 47 | + |
| 48 | +- **Версионирование** — история изменений в pipeline ([Git Tutorial](https://git-scm.com/book/en/v2/Git-Branching-Rebasing)) |
| 49 | +- **Code Review** — коллеги проверяют не только код, но и CI/CD ([GitHub PR Guide](https://docs.github.com/en/pull-requests)) |
| 50 | +- **Переносимость** — легко скопировать конфигурацию между проектами ([Starter Workflows](https://github.com/actions/starter-workflows)) |
| 51 | +- **Прозрачность** — весь процесс виден в коде ([Open Source Example](https://github.com/torvalds/linux/tree/master/.github/workflows)) |
| 52 | + |
| 53 | +```yaml |
| 54 | +## .github/workflows/ci.yml |
| 55 | +name: CI Pipeline |
| 56 | +on: [push, pull_request] |
| 57 | +``` |
| 58 | +
|
| 59 | +<!--v--> |
| 60 | +
|
| 61 | +#### Вопросы? |
| 62 | +
|
| 63 | +<!--s--> |
| 64 | +
|
| 65 | +### Основные компоненты workflow файлов |
| 66 | +
|
| 67 | +**Анатомия GitHub Actions workflow** ([Workflow Syntax Docs](https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions)) |
| 68 | +
|
| 69 | +```yaml |
| 70 | +name: My Workflow # Название workflow |
| 71 | +run-name: ${{ github.actor }} тестирует код |
| 72 | + |
| 73 | +on: [push, pull_request] # Триггеры запуска |
| 74 | + |
| 75 | +jobs: # Группа заданий |
| 76 | + test: # Имя job'а |
| 77 | + runs-on: ubuntu-latest # Среда выполнения |
| 78 | + steps: # Шаги выполнения |
| 79 | + - uses: actions/checkout@v4 # Готовый Action |
| 80 | + - run: npm test # Команда shell |
| 81 | +``` |
| 82 | +
|
| 83 | +<!--v--> |
| 84 | +
|
| 85 | +#### Структура файлов |
| 86 | +
|
| 87 | +- **Расположение**: `.github/workflows/` ([Docs](https://docs.github.com/en/actions/using-workflows)) |
| 88 | +- **Формат**: YAML файлы |
| 89 | +- **Конвенция**: один файл — один workflow |
| 90 | + |
| 91 | +``` |
| 92 | +.github/ |
| 93 | + workflows/ |
| 94 | + ci.yml # Continuous Integration |
| 95 | + deploy.yml # Deployment |
| 96 | + release.yml # Release процесс |
| 97 | +``` |
| 98 | +
|
| 99 | +<!--v--> |
| 100 | +
|
| 101 | +#### Вопросы? |
| 102 | +
|
| 103 | +<!--s--> |
| 104 | +
|
| 105 | +### GitHub Actions vs конкуренты |
| 106 | +
|
| 107 | +| Параметр | GitHub Actions | GitLab CI | Travis CI | |
| 108 | +| --------------- | ------------------------------------------------------------------------------------------------------------------------------ | ---------------------------------------------------------------------------------------- | ---------------------------------------------------------- | |
| 109 | +| **Интеграция** | Встроена в [GitHub](https://github.com/features/actions) | Часть [GitLab](https://about.gitlab.com/stages-devops-lifecycle/continuous-integration/) | Внешний сервис [Travis](https://www.travis-ci.com/) | |
| 110 | +| **Marketplace** | 20 000+ Actions ([Marketplace](https://github.com/marketplace?type=actions)) | [GitLab Catalog](https://gitlab.com/explore) | Ограниченный каталог | |
| 111 | +| **Free Tier** | 2 000 мин ([Billing](https://docs.github.com/en/billing/managing-billing-for-github-actions/about-billing-for-github-actions)) | 400 мин ([GitLab Pricing](https://about.gitlab.com/pricing/)) | Ограничено ([Travis Pricing](https://travis-ci.com/plans)) | |
| 112 | +
|
| 113 | +<!--v--> |
| 114 | +
|
| 115 | +#### Преимущества GitHub Actions |
| 116 | +
|
| 117 | +- **Нативная интеграция** — webhook’и, PR, Issues из коробки |
| 118 | +- **Огромный Marketplace** — готовые решения для любых задач |
| 119 | +- **Простота входа** — настройка за 5 минут по [Quickstart](https://docs.github.com/en/actions/get-started/quickstart) |
| 120 | +- **Гибкая настройка окружений** — matrix builds, разные ОС ([Matrix Strategy](https://docs.github.com/en/actions/using-jobs/using-job-strategy)) |
| 121 | +
|
| 122 | +<!--v--> |
| 123 | +
|
| 124 | +#### Вопросы? |
| 125 | +
|
| 126 | +<!--s--> |
| 127 | +
|
| 128 | +### Основные Jobs для JS разработки |
| 129 | +
|
| 130 | +**Практические примеры для Node.js** ([Building & Testing Node](https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-nodejs)) |
| 131 | +
|
| 132 | +<!--v--> |
| 133 | +
|
| 134 | +#### 1. Сборка и тестирование |
| 135 | +
|
| 136 | +```yaml |
| 137 | +name: Build & Test |
| 138 | +on: [push, pull_request] |
| 139 | +
|
| 140 | +jobs: |
| 141 | + test: |
| 142 | + runs-on: ubuntu-latest |
| 143 | + strategy: |
| 144 | + matrix: |
| 145 | + node-version: ["18", "20"] # Тесты на разных Node |
| 146 | + steps: |
| 147 | + - uses: actions/checkout@v4 |
| 148 | + - uses: actions/setup-node@v4 |
| 149 | + with: |
| 150 | + node-version: ${{ matrix.node-version }} |
| 151 | + cache: "npm" |
| 152 | + - run: npm ci |
| 153 | + - run: npm run build --if-present |
| 154 | + - run: npm test |
| 155 | +``` |
| 156 | + |
| 157 | +<!--v--> |
| 158 | + |
| 159 | +#### 2. Линтинг и форматирование |
| 160 | + |
| 161 | +```yaml |
| 162 | +lint: |
| 163 | + runs-on: ubuntu-latest |
| 164 | + steps: |
| 165 | + - uses: actions/checkout@v4 |
| 166 | + - uses: actions/setup-node@v4 |
| 167 | + with: |
| 168 | + node-version: "20" |
| 169 | + cache: "npm" |
| 170 | + - run: npm ci |
| 171 | + - run: npm run lint |
| 172 | + - run: npm run format:check |
| 173 | +``` |
| 174 | +
|
| 175 | +<!--v--> |
| 176 | +
|
| 177 | +#### 3. Деплой на GitHub Pages |
| 178 | +
|
| 179 | +```yaml |
| 180 | +deploy: |
| 181 | + runs-on: ubuntu-latest |
| 182 | + needs: [test, lint] |
| 183 | + if: github.ref == 'refs/heads/main' |
| 184 | + steps: |
| 185 | + - uses: actions/checkout@v4 |
| 186 | + - uses: actions/setup-node@v4 |
| 187 | + with: |
| 188 | + node-version: "20" |
| 189 | + cache: "npm" |
| 190 | + - run: npm ci |
| 191 | + - run: npm run build |
| 192 | + - uses: peaceiris/actions-gh-pages@v3 |
| 193 | + with: |
| 194 | + github_token: ${{ secrets.GITHUB_TOKEN }} |
| 195 | + publish_dir: ./dist |
| 196 | +``` |
| 197 | +
|
| 198 | +Action **peaceiris/actions-gh-pages** в [Marketplace](https://github.com/marketplace/actions/deploy-to-github-pages). |
| 199 | +
|
| 200 | +<!--v--> |
| 201 | +
|
| 202 | +#### Вопросы? |
| 203 | +
|
| 204 | +<!--s--> |
| 205 | +
|
| 206 | +### Работа с артефактами |
| 207 | +
|
| 208 | +- **Концепция** — [Workflow Artifacts Docs](https://docs.github.com/en/actions/using-workflows/storing-workflow-data-as-artifacts) |
| 209 | +- **Блог Earthly** «[Uploading Artifacts](https://earthly.dev/blog/github-action-artifacts/)» |
| 210 | +- **v4 пакет** — [GitHub Blog](https://github.blog/news-insights/product-news/get-started-with-v4-of-github-actions-artifacts/) |
| 211 | +
|
| 212 | +<!--v--> |
| 213 | +
|
| 214 | +#### Пример загрузки артефактов |
| 215 | +
|
| 216 | +```yaml |
| 217 | +- uses: actions/upload-artifact@v4 |
| 218 | + with: |
| 219 | + name: dist-files |
| 220 | + path: dist/ |
| 221 | + retention-days: 30 |
| 222 | +``` |
| 223 | +
|
| 224 | +<!--v--> |
| 225 | +
|
| 226 | +#### Вопросы? |
| 227 | +
|
| 228 | +<!--s--> |
| 229 | +
|
| 230 | +### Секреты и переменные окружения |
| 231 | +
|
| 232 | +- **Типы секретов** — [Docs](https://docs.github.com/en/actions/security-guides/using-secrets-in-github-actions) |
| 233 | +- **Best Practices** — [StepSecurity Blog](https://www.stepsecurity.io/blog/github-actions-secrets-management-best-practices) |
| 234 | +
|
| 235 | +<!--v--> |
| 236 | +
|
| 237 | +#### Пример использования секретов |
| 238 | +
|
| 239 | +```yaml |
| 240 | +- name: Deploy |
| 241 | + run: curl -H "Authorization: Bearer ${{ secrets.DEPLOY_TOKEN }}" https://api.example.com/deploy |
| 242 | +``` |
| 243 | +
|
| 244 | +<!--v--> |
| 245 | +
|
| 246 | +#### Вопросы? |
| 247 | +
|
| 248 | +<!--s--> |
| 249 | +
|
| 250 | +### Триггеры запуска workflows |
| 251 | +
|
| 252 | +- **Полный список** — [Triggering a Workflow](https://docs.github.com/en/actions/using-workflows/triggering-a-workflow) |
| 253 | +
|
| 254 | +<!--v--> |
| 255 | +
|
| 256 | +#### Manual dispatch |
| 257 | +
|
| 258 | +Используйте `workflow_dispatch` для ручного запуска через UI или [GitHub CLI](https://cli.github.com/manual/gh_workflow_run). |
| 259 | + |
| 260 | +<!--v--> |
| 261 | + |
| 262 | +#### Cron расписание |
| 263 | + |
| 264 | +Генерировать выражения удобно на [crontab.guru](https://crontab.guru/). |
| 265 | + |
| 266 | +<!--v--> |
| 267 | + |
| 268 | +#### Webhooks |
| 269 | + |
| 270 | +Интеграция с внешними системами через `repository_dispatch` ([Example Guide](https://mattstauffer.com/blog/how-to-trigger-a-webhook-on-a-schedule-using-github-actions/)). |
| 271 | + |
| 272 | +<!--v--> |
| 273 | + |
| 274 | +#### Вопросы? |
| 275 | + |
| 276 | +<!--s--> |
| 277 | + |
| 278 | +### Полезные ресурсы |
| 279 | + |
| 280 | +- **Awesome Actions** — <https://github.com/sdras/awesome-actions> |
| 281 | +- **Awesome GitHub Actions** — <https://github.com/Alliedium/awesome-github-actions> |
| 282 | +- **GitHub Learning Lab** — <https://lab.github.com/> |
| 283 | +- **Nektos act** (запуск локально) — <https://github.com/nektos/act> |
| 284 | +- **Actionlint** (статический анализ) — <https://github.com/rhysd/actionlint> |
| 285 | +- [GitHub Discussions](https://github.com/orgs/community/discussions) |
| 286 | + |
| 287 | +<!--v--> |
| 288 | + |
| 289 | +### [Домашнее задание](https://github.com/JavaScript-Basic-OTUS/otus--jsbasic/blob/master/lessons/lesson13/task.md) |
| 290 | + |
| 291 | +<!--v--> |
| 292 | + |
| 293 | +### Спасибо за внимание! |
| 294 | + |
| 295 | +**Вопросы и обсуждение** |
0 commit comments