每次部署博客时都需要在本地完成编译和上传,维护工具链成为一件很繁琐的事情,有什么办法能够将这一步自动化,为将来随时随地写博客打下基础呢?
现在来一起学(白)习(嫖)Github Action吧!
PS.阅读本文,你需要提前了解一些sh和yaml相关的知识。
CI实现
为了从源码构建Hexo博客,我们需要进行如下几步:
- clone源码
- clone主题(可选)
- 安装依赖
- 构建
那么如果使用Github Action实现如上几步呢?
下面直接上配置
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: Auto Deploy
on: push: branches: [ master ] pull_request: branches: [ master ]
workflow_dispatch: env: THEME_REPO: theme-next/hexo-theme-next THEME_BRANCH: master jobs: build: runs-on: ubuntu-latest steps: - name: Set TimeZone run: sudo timedatectl set-timezone "Asia/Shanghai" - uses: actions/checkout@v2 with: path: Blog - name: Setup Node.js uses: actions/[email protected] - name: Clear old theme run: | cd Blog rm -rf themes/next - name: Checkout theme repo uses: actions/checkout@v2 with: repository: ${{ env.THEME_REPO }} ref: ${{ env.THEME_BRANCH }} path: Blog/themes/next - name: Install deps env: DEPLOY_GIT_REMOTE: ${{env.DEPLOY_GIT_REMOTE}} run: | cd Blog cp theme_config.yml themes/next/_config.yml npm install - name: Build env: DEPLOY_GIT_REMOTE: ${{env.DEPLOY_GIT_REMOTE}} run: | cd Blog npm run build
|
CD实现
部署方式因人而异,我选择了最方便的Github Pages方式部署。以这种方式部署时,构建好的项目需要被上传到pages项目中。
创建pages项目的教程请参考 https://pages.github.com/。
创建完成后,我们需要在pages项目的Settings->Deploy keys中增加一个公钥。
在博客源码项目中的Settings->Secrets->Actions secrets中增加一个私钥。此处我命名为了MAPLE_BLOG,并在步骤Set up git中使用。
密钥对的生成可以使用ssh-keygen(linux/mac)或puttygen(win),此处不再赘述。
之后在上述流程中增加如下几个env和steps。
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
| env: GIT_USER: Casxt GIT_EMAIL: 774714620@qq.com DEPLOY_REPO: casxt/casxt.github.io DEPLOY_BRANCH: main DEPLOY_GIT_REMOTE: [email protected]:casxt/blog.github.io.git jobs: build: runs-on: ubuntu-latest steps: - name: Checkout blog repo uses: actions/checkout@v2 with: repository: ${{env.DEPLOY_REPO}} ref: ${{env.DEPLOY_BRANCH}} path: public
- name: Set up git env: DEPLOY_KEY: ${{secrets.MAPLE_BLOG}} run: | mkdir -p ~/.ssh/ echo "$DEPLOY_KEY" > ~/.ssh/id_rsa chmod 600 ~/.ssh/id_rsa ssh-keyscan github.com >> ~/.ssh/known_hosts git config --global user.name $GIT_USER git config --global user.email $GIT_EMAIL
- name: Deploy to git env: DEPLOY_GIT_REMOTE: ${{env.DEPLOY_GIT_REMOTE}} run: | cd Blog cp -R public/* ../public/ cd ../public/ git remote set-url origin $DEPLOY_GIT_REMOTE git add . git commit -m "auto deploy" git push
|