目录

Github Actions自动发布博客

目录

偶然发现github actions可以执行一些命令,这下可以把我的crontab停掉了,也不用占用一台机器专门用来发布博客了,并且完全免费!!

首先我的GitHub pages和hugo博客代码是分为两个仓库的,在GitHub Pages仓库里添加了一个Actions用来钉钉发通知:

name: dingtalk_notify

on:
  push:                                 # 在收到push的时候触发
    branches:
      - main                            # 监控main分支

jobs:
  dingtalk_notify:
    runs-on: ubuntu-latest              # 用ubuntu系统来执行
    steps:
      - name: dingtalk_notify
        run: |
          python <<END
          import time
          import hmac
          import hashlib
          import base64
          import urllib.parse
          import requests

          now = str(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))

          secret = "${{ secrets.dingtalk_secret }}"                         # 这里是GitHub Secret, 需要在仓库设置里创建对应的键值对
          webhook_url = "${{ secrets.dingtalk_url }}"

          # 根据时间戳生成签名
          timestamp = str(round(time.time() * 1000))
          secret_enc = secret.encode('utf-8')
          string_to_sign = '{}\n{}'.format(timestamp, secret)
          string_to_sign_enc = string_to_sign.encode('utf-8')
          hmac_code = hmac.new(secret_enc, string_to_sign_enc, digestmod=hashlib.sha256).digest()
          sign = urllib.parse.quote_plus(base64.b64encode(hmac_code))

          # 要发送的数据
          data = """
          {
              "msgtype":"text",
              "text": {
                  "content": "%s %s"
              }
          }
          """ %(now, "博客自动发布成功")

          # url参数
          params={
              'timestamp': timestamp,
              'sign': sign
          }

          # header
          header = {'Content-Type': 'application/json'}

          # post消息出去
          r = requests.post(webhook_url, headers=header, params=params, data=data.encode('utf-8'))
          print(r.text)
          END          

然后是hugo仓库,我创建了两个workflow,一个是推送到百度用于加快搜索引擎收录, 一个是自动发布到GitHub Pages:

baidu_push.yml

name: Baidu push

on:
  push:
    branches:
      - master
  schedule:
    - cron:  '0 0 * * *'                            # 使用crontab定时执行,0点实际执行时间是9点,可能是时区问题

jobs:
  baidu-push:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2                   # 拉取代码,并拉取git submodule
        with:
          submodules: recursive

      - name: Setup Hugo
        uses: peaceiris/actions-hugo@v2             # hugo环境,用的是别人写好的actions
        with:
          hugo-version: '0.80.0'
          extended: true

      - name: Build
        run: |
          git config core.quotePath false
          hugo                                      # 使用hugo命令生成静态文件          

      - name: Install requests
        run: pip install requests

      - name: Push
        run: |
          python <<END
          import requests
          import re
          with open('public/sitemap.xml', 'r') as sitemap:
            pattern = re.compile(r'(?<=<loc>).+?(?=</loc>)')
            result = pattern.findall(sitemap.read())
            req = requests.post('http://data.zz.baidu.com/urls?site=https://zahui.fan&token=${{ secrets.BAIDU_PUSH_TOKEN }}', '\n'.join(result))
            print(req.text)
          END          

deploy_github_pages.yml

name: Deploy GitHub Pages

on:
  push:
    branches:
      - master
  schedule:
    - cron:  '0 0 * * *'

jobs:
  deploy_github_pages:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
        with:
          submodules: recursive

      - name: Setup Hugo
        uses: peaceiris/actions-hugo@v2
        with:
          hugo-version: '0.80.0'
          extended: true

      - name: Build
        run: |
          git config core.quotePath false
          hugo          

      - name: Deploy 🚀
        uses: JamesIves/github-pages-deploy-action@4.1.4
        with:
          BRANCH: main                                          # 你要发布到哪个分支(GitHub Pages的仓库分支,不是你hugo代码的分支)
          FOLDER: public                                        # 发布的文件夹,默认就是public
          ssh-key: ${{ secrets.DEPLOY_SSH_KEY }}                # 我发布到不同的仓库,需要用到私钥,私钥用GitHub Secret来管理,发布同仓库可以去掉这个配置
          repository-name: iuxt/iuxt.github.io                  # 发布到同仓库的不同分支要去掉这个配置

      - name: Use Node.js 10.x
        uses: actions/setup-node@v1
        with:
          node-version: 10.x
      - name: algolia upload
        run: |
          npm install
          npm run algolia          
        env:
          ALGOLIA_APP_ID: ${{ secrets.ALGOLIA_APP_ID }}         # 一样的,需要在GitHub Secret里面创建键值对。
          ALGOLIA_INDEX_NAME: blog
          ALGOLIA_INDEX_FILE: public/index.json
          ALGOLIA_ADMIN_KEY: ${{ secrets.ALGOLIA_ADMIN_KEY }}