github actions 上传commits到VPS并自动部署

前言

最近利用Python FastAPI 写了一个RSS 生成器, 本质上是一个爬虫。 因为经常需要上传代码至github 和 部署到 VPS 上运行,这过程反反复复非常好痛苦。 最后,终于忍不住了,还是学了如何使用github actions, 这样就可以commit代码到github后自动上传代码至VPS并自动部署。

过程

设置 workflow 文件

  1. 在github repo 上(或本地上,然后再psuh到github)新建.github/workflow 文件夹, 然后新建yml文件 deploy.yml
mkdir .github && mkdir ./github/workflow && touch ./github/workflows/deploy.yml

打开deploy.yml后写入以下代码:

#这个action的名称,任意
name: RSSinn Deploy CD
on:
  push:
    branches: [main]
jobs:
  deploy:
    #指定运行的VPS 系统
    runs-on: ubuntu-20.04
    steps:
      #这个steps的名称,任意
      - name: Deploy to VPS
        #这个是指定用于操作VPS SSH的插件,不能改
        uses: appleboy/ssh-action@master
        with:
          #具体配置:https://opensourcelibs.com/lib/ssh-action, 可以设ssh_key
          host: ${{ secrets.LIVE_SERVER_IP }}
          username: ${{ secrets.SERVER_USERNAME }}
          password: ${{ secrets.SERVER_USER_PASSWORD }}
          port: ${{ secrets.DEPLOY_PORT }}
          #登录SSH后需要执行的代码
          script: |
            cd ${{ secrets.PROJECT_PATH }}
            git fetch ${{secrets.REPO_URL}}
            git reset --hard
            git pull ${{secrets.REPO_URL}}
            #sed是用于替代操作,这里是用environment设置的secrets中的REDIS_URL字段替代settings.yaml文件中的_redis_url_字段
            sed -i 's~_redis_url_~${{ secrets.REDIS_URL }}~g' settings.yaml
            #首先终止运行端口为28085的程序
            fuser -n tcp -k 28085
            fuser -n tcp -k 28085
            #将目录下的pdm设置为环境变量
            export PATH=/root/.local/bin:$PATH
            #后台执行运行命令
            nohup pdm run uvicorn run:app --host 0.0.0.0 --port 28085 > log.txt 2>&1 &

设置 secrets 变量

Repository secrets are specific to a single repository (and all environments used in there), while organisation secrets are specific to an entire organisation and all repositories under it.
You can use environment secrets if you have secrets which are specific to an environment.

这里设置了两种secret, 一种是Repository secrets, 一种是Environment secrets。 后来想了想,其实可以将全部secrets设置为Repository secrets,但之前误打误撞居然运行成功了,所以就没有更改。

就这么简单的事情,居然摸索了整整一天。

参考

阅读量: | 柯西君_BingWong | 2023-02-16