正式开始之前,你需要掌握 GitHub Action 的基础语法:
为了方便运行GitHub Actions时登录GitHub账号,我们使用SSH方式登录。就是要把设备的私钥交给GitHub Actions,公钥交给GitHub,需要去Settings里去配置。
使用ssh-keygen生成一组公私秘钥对
ssh-keygen -t rsa -C "Github 的邮箱地址"
如 ssh-keygen -t rsa -C "123@gmail.com"
在仓库的Actions选项卡下点击新建.github/workflow/blank.yml
,名称默认或者自定义修改,配置如下:
# This is a basic workflow to help you get started with Actions
name: Deploy My Server
on:
push:
branches: [ master ]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job called "build"
build:
# The type of runner that the job will run on
runs-on: ubuntu-latest
# Steps represent a sequence of tasks that will be executed as part of the job
steps:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v2
- name: use Node.js
# 使用action库 actions/setup-node安装node
uses: actions/setup-node@v1
with:
node-version: 16.x
# 安装依赖
- name: npm install
run: npm install
# 打包
- name: npm build
run: npm run build
# 部署到服务器
- name: deploy
uses: easingthemes/ssh-deploy@v2.1.1
env:
# 本地.ssh文件下的私钥id_rsa,存在secrets的PRIVATE_KEY中
SSH_PRIVATE_KEY: ${{ secrets.PRIVATE_KEY }}
# 复制操作的参数。"-avzr --delete"意味部署时清空服务器目标目录下的文件
ARGS: "-avzr --delete"
# 源目录,相对于$GITHUB_WORKSPACE根目录的路径
SOURCE: "./public/"
# 服务器域名/IP
REMOTE_HOST: ${{ secrets.HOST }}
# 服务器默认用户名为root
REMOTE_USER: "root"
# 目标目录
TARGET: '/usr/local/xxx/dist'
# 排除目录
EXCLUDE: "/node_modules/"
参数项:
文件同步原理请参考rsync教程
push内容到仓库后,Action会自动执行工作流,此时你再看看你配置的TARGET服务器目录,就会发现文件dist
被拷贝过去了