最近在研究自动化构建和部署 ,突然有个主意,能不能把代码提交之后自动同步到ftp

选型

开始选型的时候找到了lftpgit-ftp两种方案,比较后发现lftp在比较文件差异的时候会遍历文件比较差异(文件大小、时间等),再进行上传,在文件比较多或结构复杂的时候会比较慢,而git-ftp则会在远程ftp读取最近同步的commit id(如果不存在记录则全部同步)和当前版本的commit id进行比较差异,对差异部分进行同步,同步完成后记录当前提交的id。对比下来,后者会更加有效率,本次采用后者。

git-ftp原理

title=>asdasd

st=>start: 准备同步
e=>end: 开始同步

op=>operation: 比较commit id间的差异,确定同步文件
op1=>operation: 同步全部文件

cond=>condition: 询问ftp存在commit|request

st->cond->op1->e
cond(yes,right)->op
cond(no)->op1

搭建

本次部署使用宝塔面板(安装好ftp、nginx)方便展示效果,通过GITHUB&GitHub Actions部署

Title: 大致流程
本地->github: 推送
Note right of github: 触发github actions
github->ftp: 同步

宝塔环境

  1. 安装宝塔面板
  2. 使用面板安装环境
  3. 创建网站&ftp
  4. 打开网站,确认网站可访问

github

  1. 创建github仓库
  2. 创建actions

    1. 切换到actions选项卡创建workflow
    2. 编辑框替换为下面的代码后提交

      name: deploy to ftp
      
      on:
        push:
      paths-ignore: 
      - '.github/**'
      jobs:
        build:
      
      runs-on: ubuntu-latest
      
      container: 
        image: debian:stable-slim
      
      steps:
      - name: 初始化环境
        run: |
      apt-get update
      apt-get install -y git 
      apt-get install -y git-ftp
      - name: 克隆github项目
        uses: actions/checkout@master
        with:
        fetch-depth: 2   
      - name: 开始ftp同步
        run: |        
      #替换你的ip或域名
      git config git-ftp.url "ftp://139.199.213.12/"
      #替换你的ftp账户
      git config git-ftp.user "ftp_139_199_213_12"       
      #替换你的ftp密码        
      git config git-ftp.password "RneX8bMZ5ZT6ZAFk"
      #--disable-epsv可选,因为我的服务器不支持epsv
      git ftp push --auto-init -vv --disable-epsv
      
  3. 在主分支上创建index.html文件写入hello world并提交,在actions选项里面查看状态,等完成后刷新你的网站,会看到内容已经替换hello world

写在最后

如果你的项目是公开项目,请将ftp地址、账户名、密码用github secret代替

example

git config git-ftp.password ${{ secrets.FTP_PASSWORD }}

git-ftp支持更多参数,更多用法可参考
最后修改:2020-01-27
如果覺得我的文章對你有用,請隨意讚賞