Use Github Action to automatic deploy
使用 Github Action 自动部署
1. 生成 SSH 私钥
1
| ssh-keygen -m PEM -t rsa -b 4096
|
2. 将生成的 SSH 私钥导出并填入指项目仓库
复制全部内容。
打开仓库页面,点击 Settings -> Secrets and variables -> actions -> New repository secret,填入 Name 为 SERVER_SSH_KEY
,Value 为刚刚复制的内容。
3. 编写 Github Action
在项目仓库中创建 .github/workflows/deploy.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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
| name: Deploy
on: push: branches: - master
jobs: build: runs-on: ubuntu-latest
steps: - name: Check out uses: actions/checkout@v3
- name: Set up Node uses: actions/setup-node@v3 with: node-version: 18
- id: cache name: Yarn Cache Dir run: echo "value=$(yarn cache dir)" >> $GITHUB_OUTPUT
- name: Restore Lockfile uses: actions/cache@v3 with: path: yarn.lock key: yarn-lock-${{ github.sha }} restore-keys: yarn-lock-
- name: Restore Cache uses: actions/cache@v3 with: path: ${{ steps.cache.outputs.value }} key: yarn-cache-${{ github.sha }} restore-keys: yarn-cache-
- name: Install run: yarn
- name: 服务器验证 env: ACTION_DEPLOY_KEY: ${{ secrets.SERVER_SSH_KEY }} REMOTE_ADDR: ${{ secrets.SERVER_ADDR }} USER_NAME: ${{ secrets.USERNAME }} USER_EMAIL: ${{ secrets.USEREMAIL }} run: | sudo timedatectl set-timezone "Asia/Shanghai" mkdir -p ~/.ssh/ echo "$ACTION_DEPLOY_KEY" > ~/.ssh/id_rsa chmod 600 ~/.ssh/id_rsa ssh-keyscan $REMOTE_ADDR >> ~/.ssh/known_hosts git config --global user.name $USER_NAME git config --global user.email $USER_EMAIL git config --global auto.crlf input
- name: 部署 run: yarn update
|
4. 配置环境
在项目仓库中点击 Settings -> Secrets and variables -> actions -> New repository secret,填入 Name 为 SERVER_ADDR
,Value 为服务器地址。
在项目仓库中点击 Settings -> Secrets and variables -> actions -> New repository secret,填入 Name 为 USERNAME
,Value 为 Github 用户名。
在项目仓库中点击 Settings -> Secrets and variables -> actions -> New repository secret,填入 Name 为 USEREMAIL
,Value 为 Github 邮箱。