使用 GitHub Actions 自动化构建、测试和部署流程

王林
发布: 2024-09-10 06:38:12
原创
990 人浏览过

该项目是一个快速示例项目,演示了应用程序在推送到主分支时自动构建、测试和部署到暂存环境的过程。

为了充分演示 CI/CD 管道,我们将使用最少的代码创建一个简单的 Python 项目,然后将其集成到 GitHub Actions 中。

创建一个简单的 Python 项目

就像我之前所说的,我们将创建一个将在管道中使用的简单项目。我选择在 python 中执行此操作没有特殊原因,您可以使用您选择的任何其他编程语言,这个项目的主要目的是演示管道。

创建项目文件夹

所以继续创建项目文件夹并导航到该文件夹​​:

mkdir automated-testing
cd automated-testing
登录后复制

编写申请文件

现在我们将编写简单的Python应用程序。在项目文件夹中创建一个新文件app.py。

touch app.py
登录后复制

将以下代码块添加到文件中:

def hello():
  return "Hello, World!"

if __name__ == "__main__":
  print(hello())
登录后复制

这是一个非常简单的 Python“Hello world”函数,作为可以在 CI 管道中测试的基本功能的示例。

def hello() 定义了一个名为 hello 的函数,它不带任何参数。调用此函数时,它返回字符串“Hello, World!”。

if __name__ == "__main__" 是一个标准的 Python 构造,用于确保某些代码仅在直接执行文件时运行(而不是作为模块导入时)。它充当脚本的入口点。

直接运行 app.py 时(例如,通过运行 python app.py),脚本将调用 hello() 函数并打印结果,即“Hello, World!”。

创建需求文件。

典型的项目会有依赖项,在 python 项目中,它们通常在requirements.txt 文件中定义。

创建新文件requirements.txt

touch requirements.txt
登录后复制

将其添加到文件中:

pytest
登录后复制

创建单元测试

现在我们将添加一个基本测试文件test_app.py来测试app.py中的功能。将以下内容添加到文件中:

from app import hello

def test_hello():
  assert hello() == "Hello, World!"
登录后复制

现在我们已准备好创建管道。

为 CI/CD 设置 GitHub 操作

要配置 GitHub 操作,我们需要在存储库中创建一个 .github/workflows 文件夹,这是我们向 GitHub 通知存储库中的 CI/CD 管道的方式。

创建一个新文件:

mkdir -p .github/workflows
登录后复制

您可以在一个存储库中拥有多个管道,因此请在 .github/workflows 文件夹中创建一个文件 proj.yml。我们将在这里定义构建、测试和部署 Python 项目的步骤。

将以下代码添加到您的文件中:

name: Build, Test and Deploy

# Trigger the workflow on pushes to the main branch
on:
  push:
    branches:
      - main

jobs:
  build-and-test:
    runs-on: ubuntu-latest

    steps:
    # Checkout the code from the repository
    - name: Checkout repo
      uses: actions/checkout@v4

    # Set up Python environment
    - name: Setup Python
      uses: actions/setup-python@v5
      with:
        python-version: '3.x'

    # Install dependencies
    - name: Install Dependecies
      run: |
        python -m pip install --upgrade pip
        pip install -r requirements.txt

    # Build (this project deosn't require a build but we will simulate a build by creating a file)
    - name: Build Project
      run: |
        mkdir -p build
        # Simulate build output by creating a file
        touch build/output_file.txt

    # Run tests using pytest
    - name: Run tests
      run: 
        pytest

    # Upload the build output as an artifact (we created a file in the build step to simulate an artifact)
    - name: Upload build artifact
      uses: actions/upload-artifact@v4
      with:
        name: build-artifact
        path: build/

  deploy:
    runs-on: ubuntu-latest
    needs: build-and-test
    if: success()

    steps:
    # Download the artifact from the build stage
    - name: Download build artifact
      uses: actions/download-artifact@v4
      with:
        name: build-artifact
        path: build/

    - name: Simulate Deployment
      run: |
        echo "Deploying to staging..."
        ls build/
登录后复制

Breakdown of the CI/CD Pipeline Steps

  • Trigger on Push to main: The pipeline is triggered whenever there is a push to the main branch.
  • Checkout Code: This step uses GitHub’s checkout action to pull our code from the repository.
  • Set Up Python: The pipeline sets up a Python environment on the CI runner (GitHub's virtual machine), ensuring that the correct Python version is used.
  • Install Dependencies: It installs the required dependencies for our Python project (pytest in this case). This dependency was just added as an example of when a project has dependencies as this particular sample python application does not require any.
  • Build: This stage was also just added for demonstration purposes, supposing this was a JavaScript/Node.js project this is where we would run the npm run build command and this will create an artifact we can upload and use in the deploy stage. Since this is a python project and it doesn't really require a build, we will create a file and folder in this stage. The file will serve as our artifact for the deploy stage.
  • Run Tests: It runs the tests using pytest to validate the code.
  • Upload Build Artifact: After running the tests, the build-and-test stage creates and saves a build artifact (in this case, a simulated output_file.txt in the build folder from the build step). The action upload-artifact is used to store this artifact. You can replace this with whatever actual build output your project creates.
  • Deploy Stage: Our application will only be deployed if the test was successful which is why I have added the conditionals needs and if. Using “needs” we can require that the deploy job won’t even run unless the test job is successful. The download-artifact action retrieves the build artifact and the last step "Simulate Deployment" simulates deployment by printing a message and lists the artifact. If this was a live project we would have the actual deployment commands to deploy to a real staging environment here. You can replace the echo and ls commands with actual deployment commands (e.g., deploying to a cloud platform). This approach ensures that the output from the build-and-test stage is properly passed to the deploy stage, simulating how a real deployment would work with build artifacts.

Push to GitHub

If you haven't already, you need to initialize a git repository using the commands below:

git init
git add .
git commit -m "Create project as well as CI/CD pipeline"
登录后复制

Now we push to GitHub. Create a GitHub repository and push your code using the below commands:

git remote add origin <your-repo-url>
git push -u origin main
登录后复制

Verify the Pipeline

After pushing the code, you can visit the Actions tab in your GitHub repository. You should see the pipeline triggered, running the steps defined in your proj.yml file.

If everything is set up correctly, the pipeline will build, test, and simulate deployment. You can changes things around in your project and make new pushes to see the the pipeline works, create errors intentional so you can see how the pipeline works when the tests fail.

On a successful run this is how your Actions tab should look.

Automate Build, Test & Deploy Processes with GitHub Actions

And that's it, this setup provides a working example of a CI/CD pipeline for a very basic Python project. If you found this helpful, please share with your connection and if you have any questions, do not hesitate to drop the question in the comments.

以上是使用 GitHub Actions 自动化构建、测试和部署流程的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:dev.to
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!