GitHub Action前端项目自动部署至阿里云服务器

本文最后更新于:2022年9月6日 晚上

生成密匙对

在阿里云创建密匙对

创建成功后会下载一个xxx.pem文件

选择绑定密匙对,绑定服务器实例

绑定后重启服务器

此时使用ssh name@xx.xx.xx.xx应会提示拒绝密码登录

1
2
3
ssh -i <xx.pem路径> <name>@xx.x.xx.x   # 使用密匙登录

ssh -i ./test.pem test@1.2.3.4

GitHub Action

github/workflows/test.yml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
name: Build app and deploy to aliyun
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: use Node.js 14
uses: actions/setup-node@v3
with:
node-version: '14'
- name: Add pnpm
run: npm install pnpm -g && pnpm -v
- name: Pnpm install
run: pnpm i
- name: Pnpm build
run: pnpm build
- name: Deploy to Aliyun
uses: easingthemes/ssh-deploy@v2.1.1
env:
SSH_PRIVATE_KEY: ${{ secrets.PRIVATE_KEY }}
REMOTE_HOST: 'xxxx.xx.xx.xx'
REMOTE_USER: '用户名'
ARGS: '-avzr --delete'
SOURCE: 'dist/'
TARGET: '/usr/share/nginx/modules/test'

编辑器打开test.pem文件,复制所有

到项目仓库,设置New repository secret

namePRIVATE_KEY

secrettest.pem内容

提交至仓库即可自动部署

添加node_modules缓存加速

核心代码:

1
2
3
4
5
6
7
8
9
10
11
- name: Cache node_modules
id: cache-node-modules
uses: actions/cache@v2
with:
path: node_modules
key: ${{ runner.os }}-${{ matrix.node-version }}-nodeModules-${{ hashFiles('package-lock.json') }}-${{ hashFiles('package.json') }}
restore-keys: |
${{ runner.os }}-${{ matrix.node-version }}-nodeModules-
- name: Pnpm install
if: steps.cache-node-modules.outputs.cache-hit != 'true'
run: pnpm i

如改造为如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
name: Build app and deploy to aliyun
on: [push]
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: use Node.js 14
uses: actions/setup-node@v3
with:
node-version: '14'
- name: Add pnpm
run: npm install pnpm -g && pnpm -v
- name: Cache node_modules
id: cache-node-modules
uses: actions/cache@v2
with:
path: node_modules
key: ${{ runner.os }}-${{ matrix.node-version }}-nodeModules-${{ hashFiles('package-lock.json') }}-${{ hashFiles('package.json') }}
restore-keys: |
${{ runner.os }}-${{ matrix.node-version }}-nodeModules-
- name: Pnpm install
if: steps.cache-node-modules.outputs.cache-hit != 'true'
run: pnpm i
- name: Pnpm build
run: pnpm build
- name: Deploy to Aliyun
uses: easingthemes/ssh-deploy@v2.1.1
env:
SSH_PRIVATE_KEY: ${{ secrets.PRIVATE_KEY }}
REMOTE_HOST: 'xxxx.xx.xx.xx'
REMOTE_USER: '用户名'
ARGS: '-avzr --delete'
SOURCE: 'dist/'
TARGET: '/usr/share/nginx/modules/test'

GitHub Action前端项目自动部署至阿里云服务器
https://qingshaner.com/Action自动部署至阿里云服务器/
作者
清山
发布于
2022年9月4日
许可协议