我们公司正从 Jenkins 迁移到 GitHub Actions 来执行 CI/CD。本文介绍一些基础知识。

什么是 GitHub Actions?

根据 GitHub 的定义:

GitHub Actions 是一个持续集成和持续交付(CI/CD)平台,可以自动化构建、测试和部署流程。你可以创建工作流,在向仓库推送更改时运行测试,或在合并拉取请求后将代码部署到生产环境。

如果你使用过 Jenkins 等 CI/CD 工具,可以把 GitHub Actions 看成自动化同类工作流的另一种方式。

GitHub Actions 还可以用于:

  1. 构建和测试
  2. 部署
  3. 发布软件包
  4. 管理 GitHub Issues 和标签

一个简单示例

1. 创建 GitHub Actions 工作流 YAML 文件

在 GitHub 仓库的 .github/workflows 目录下,创建一个名为 github-actions-hello-world.yml 的工作流文件。

2. 添加 Hello World 工作流

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
name: GitHub Actions Hello World
run-name: ${{ github.actor }} is testing out GitHub Actions 🚀
on: [push]
jobs:
  Explore-GitHub-Actions:
    runs-on: ubuntu-latest
    steps:
      - run: echo "🎉 The job was automatically triggered by a ${{ github.event_name }} event."
      - run: echo "🐧 This job is now running on a ${{ runner.os }} server hosted by GitHub!"
      - run: echo "🔎 The name of your branch is ${{ github.ref }} and your repository is ${{ github.repository }}."
      - name: Check out repository code
        uses: actions/checkout@v4
      - run: echo "💡 The ${{ github.repository }} repository has been cloned to the runner."
      - run: echo "🖥️ The workflow is now ready to test your code on the runner."
      - name: List files in the repository
        run: |
          ls ${{ github.workspace }}
      - run: echo "🍏 This job's status is ${{ job.status }}."

提交工作流文件

将工作流文件提交到你的分支。

查看工作流结果

  1. 在 GitHub 上打开仓库主页。
  2. 在仓库名称下方点击 Actions。
  3. 在左侧边栏中点击要查看的工作流。

GitHub Actions 工作流列表

GitHub Actions 工作流运行记录

GitHub Actions 工作流

对比 GitHub Actions 与 Jenkins

我喜欢 GitHub Actions 的原因

  1. 容易学习和上手。
  2. 与 GitHub 集成良好,对开发者友好。
  3. 它是 SaaS 解决方案,因此团队不必自行维护 CI/CD 服务器。
  4. 提供一个用于分享和复用工作流的市场。

Jenkins

  1. 开源软件,可以通过插件扩展功能。
  2. 团队需要维护 Jenkins 服务器和代理节点。
  3. 不依赖某一个代码托管平台;仓库可以托管在 GitHub、GitLab、Bitbucket 等平台上。
  4. 学习曲线更陡。