DevOps: 持续集成 [Continuous Integration]

2,349 阅读3分钟

您将收获

  • 对持续集成有基本的了解
  • 回顾一些持续集成工具
  • 了解如何使用 GitHub Actions 进行持续集成
  • 将代码覆盖率集成到您的持续集成工作流程中

持续集成 CI VS 持续交付 CD

Continuous Integration

  • 在一组测试通过后,将开发人员的每项变更持续集成到主分支,从而产生潜在的可部署代码的过程

Continuous Delivery

  • 一系列实践旨在通过将每次更改交付到类似生产的环境来确保代码可以快速、安全地部署到生产中

image.png

每个 Pull Request 都应该被构建(build)和测试(tested)

持续集成工具

image.png Jenkins、Travis CI、Circle CI 和 GitHub Actions 等工具可以在合并到主版本之前为您构建每个Pull Request

Github Actions

  • GitHub Actions 是一款 CI/CD 工具,可在每个版本库中使用
  • 作为服务集成到 GitHub 中
  • 它允许您将 CI 管道视为代码
  • 它使用 .github/workflows/ 文件夹将工作流定义存储为 .yaml 文件

1 如何工作的?

  • 您在项目的根目录中创建一个名为 .github/workflows/ 的文件夹

  • 将 yaml 文件放入该文件夹中

  • 取决于您配置 GitHub Actions 的方式

    • 每当您推送到 master 时,都会执行build
    • 每当您发出Pull Request时,都会执行build
  • build在隔离环境(虚拟机或 Docker)中运行

2 基本概念

Workflow:

  • 工作流是一系列类似于管道的自动化过程
  • 允许开发人员配置一系列可以在每次触发特定事件时执行的阶段
  • 每个资源库可以有任意数量的工作流

每个工作流程由以下组件组成:

image.png

2.1 Event

For instance: image.png

2.2 Jobs

由在同一Runner上执行的Steps组成 Each Job contains:

  • A Runner
  • Services (optional)
  • Steps

image.png

2.3 Runner

在特定平台或操作系统上执行Jobs的服务器

image.png

2.4 Services

服务是应用程序所需的任何服务器(数据库、消息传递等)

image.png 在上面的例子中,服务名称为 postgres

2.5 Steps

一项任务包含一个或多个 shell 命令或操作

image.png

2.6 Actions

可以在步骤内执行的过程

image.png

3 实例

name: CI Build
on:
  push:
    branches:
      - master
  pull_request:
    branches:
      - master

jobs:
  build:
    runs-on: ubuntu-latest
    container: python:3.11-slim

    # Required services    
    services:
      # Label used to access the service container
      redis:
        # Docker Hub image
        image: redis
        # Set health checks to wait until redis has started
        options: >-
          --health-cmd "redis-cli ping"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    # Steps for the build
    steps:
      - name: Checkout
        uses: actions/checkout@v3
            
      - name: Install dependencies
        run: |
          python -m pip install --upgrade pip wheel
          pip install -r requirements.txt

      - name: Linting
        run: |
          # stop the build if there are Python syntax errors or undefined names
          flake8 service tests --count --select=E9,F63,F7,F82 --show-source --statistics
          # test for complexity. The GitHub editor is 127 chars wide
          flake8 service tests --count --max-complexity=10 --max-line-length=127 --statistics
          # Run pylint to catch other PEP8 errors
          pylint service tests --max-line-length=127

      - name: Run unit tests with green
        run: green
        env:
          DATABASE_URI: "redis://redis:6379"

      # Uncomment the following 2 lines during hands-on lab
      
      # - name: Upload code coverage
      #   uses: codecov/codecov-action@v3.1.4
  

代码库徽章

  • 徽章为您提供了一种让开发人员了解代码状态的方法
  • Build徽章将显示构建或测试用例是否失败

测试覆盖率

借用 codecov.io

image.png

image.png