github actions: 利用 gh-actions 向 aliyun oss 发布项目

将前端项目放在 aliyun oss,利用 gh-actions 来发布
更新于: 2023-12-10 22:23:39

一图胜千言

现在的期望是将前端项目的代码,通过 aliyun cli 上传到 OSS 上,然后通过 nginx 的配置,完成项目的部署,展示。

原理示意图

方案说明

  • 可以缓存 node_modules,这样可以优化编译打包速度
  • 可以利用 ailyun 的sdk 或者 cli 工具上传 build 好的文件到目标位置
  • 可以利用 git message 来触发打包上传动作,即可以直接使用 gtc 命令来触发 deploy 行为
  • xmind 在这个项目里: https://github.com/aric-notes/cra-ailyun-notes

新建 github actions

cd cra-ailyun-notes
mkdir -p .github/workflows
cd .github/workflows && touch main.yml

简版代码

  • 缓存利用cache: 'yarn'
name: Cra-aliyun-notes workflow for AliyunOSS
on: [push]

jobs:
  install_dependencies:
    name: Install Dependencies
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - name: Use Node.js 16.18.0
        uses: actions/setup-node@v2
        with:
          node-version: '16.18.0'
          cache: 'yarn'

      - name: Install Dependencies
        run: yarn

  build_project:
    name: Build Project
    runs-on: ubuntu-latest
    needs: install_dependencies
    steps:
      - uses: actions/checkout@v2
      - name: Use Node.js 16.18.0
        uses: actions/setup-node@v2
        with:
          node-version: '16.18.0'
          cache: 'yarn'

      - name: Build Project
        run: yarn build

  deploy_to_aliyun_oss:
    name: Deploy to Aliyun OSS
    runs-on: ubuntu-latest
    needs: build_project
    if: contains(github.event.head_commit.message, '__@production__')
    steps:
      - uses: actions/checkout@v2
      - name: Config AliyunCli
        uses: jerray/setup-aliyun-cli-action@v1.0.0
        env:
          ACTIONS_ALLOW_UNSECURE_COMMANDS: true
        with:
          aliyun-cli-version: '3.0.121'
          mode: AK
          access-key-id: ${{ secrets.ACCESS_KEY_ID }}
          access-key-secret: ${{ secrets.ACCESS_KEY_SECRET }}
          region: <REPLACE_WITH_YOUR_REGION>

      - name: Deploy by aliyun-cli
        run: |
          aliyun oss sync dist <REPLACE_WITH_YOUR_OSS_BUCKET> --force --delete

在上面的示例中,您需要将以下占位符替换为实际的值:

<REPLACE_WITH_YOUR_REGION>:替换为您的阿里云 OSS 区域,例如 cn-beijing。
<REPLACE_WITH_YOUR_OSS_BUCKET>:替换为您的阿里云 OSS 存储桶名称,如 "my-oss-bucket"。
请注意,这只是一种示例。在实际情况中,您可能需要将更多的敏感信息替换为占位符,以确保您的代码安全。

利用 gh 配置 ACCESS_KEY_IDACCESS_KEY_SECRET

# 安装 gh
brew install gh
# 登录<我本地有GITHUB_TOKEN,所以可以不用登录>
gh auth login
# 设置
gh secret set ALIBABACLOUD_ACCESS_KEY_SECRET --body "YOUR_SECRET" --app actions

关于 node_modules 的缓存问题

  • 利用 setup/nodejs 的 action 缓存
    • 优点: 设置简单,只要加 yarn/npm 这种字符串即可设置完成
    • 缺点: 如果我想一个 cache 是否命令的状态,这里就没有
  • 利用 cache 的 action 缓存
    • 优点: 有 hit cache的状态
    • 缺点: 设置略为麻烦一点

配置 aliyun cli 报错

# 解决方案,添加如下:
env:
	ACTIONS_ALLOW_UNSECURE_COMMANDS: true
配置报错

参考