About the article

This article is the original content, first in my personal blog and language finch, please indicate reprint, thank you.

Author: 1874

Personal blog post link: Hexo+Github Actions+COS continuous integration

Hexo+Github Actions+COS continuous integration

The introduction


Before I encountered Yuque-Hexo, here’s how Hexo+Github Pages is deployed:

  • Configure the Hexo source code locally
  • Use your local Markdown editor to write your article
  • Hexo is deployed on Github Pages/Coding Pages

The disadvantages are also obvious:

  • Local editors are a jumble, and it’s hard to say how to use them
  • It is not convenient to store code locally
  • The speed of GitHub Pages in China is worrying (I also deployed Coding Pages in dual mode for some time, but it was too unstable)

I picked out the local editor again and again, and finally found a good Typora, but still limited to the limitations and inconvenience of local editing, lazy to write a blog in the local. After trying the language finch, I found that the language Finch editor is too easy to use, fully functional and fast. Since then, I have been recording various articles on Wordfinch, but it has not been synchronized to the blog. The company team also uses birds to record various technical solutions and other documents. So I almost stopped blogging for a year.


It wasn’t until I met Yuque-Hexo that I was suddenly intrigued. After several days of working around the clock on the recommended best practice articles, I finally built my new blog.

start

My new blog is based on

Hexo + Wordfinch + Yuque – Hexo + Web hook + Severless + Github Actions

The hosting platform I chose is

Tencent Cloud COS static website + custom CDN acceleration

As for why I choose Tencent Cloud COS, it is because my cloud server, domain name and graph all use Tencent cloud services. Plus COS static website +CDN acceleration of the ultimate experience, let me move. And the number of visits to my lame personal blog isn’t that much money for a paid COS, so I’m just going to test it out, in case the blog hits (and runs out of money).

Deployment process

Initialize Hexo

You first need to initialize the Hexo repository locally

npx hexo-cli init blog
Copy the code

NPX can use the hexo-CLI command without global installation dependencies

After successfully initializing Hexo, you can install your favorite themes and other configurations, which will not be covered here.

Install the yuque-hexo plugin

Official documentation: Yuque-hexo

Install dependencies

npm i yuque-hexo
Copy the code

The configuration language finches

  1. Access the workbench => Account Settings =Token=> Create a Token and configure permissions. The Access Token is the YUQUE_TOKEN

  1. Access the workbench => Account Settings => Account Settings => Personal path, set the simple personal path of the finch (suggested), get the personal path.

  1. Create a new knowledge base for your blog (Internet visible)
  2. Enter the blog knowledge base, set the blog knowledge base path (recommended), get the path of the knowledge base.

Configuration hexo

Take the above personal path and knowledge base path and configure hexo.

package.json

{
  "scripts": {
    "hexo:build": "hexo generate"."hexo:clean": "hexo clean"."deploy": "hexo deploy"."server": "hexo server"."hexo": "npm run hexo:clean && npm run hexo:build && npm run server"."yuque:clean": "yuque-hexo clean"."yuque:sync": "yuque-hexo sync"."yuque": "npm run yuque:clean && npm run yuque:sync"
  },
  "yuqueConfig": {
    "postPath": "source/_posts"."baseUrl": "https://www.yuque.com/api/v2"."login": "Personal Path of The Whisperer"."repo": "Knowledge base path"."onlyPublished": true."onlyPublic": true}}Copy the code

Configure Tencent Cloud COS

When we start we need to prepare as follows:

  • Domain name (registration is required, if not, the temporary domain name provided by COS can be used temporarily)
  • Tencent cloud account to open COS service (IT is recommended to use COS console version V5, if version V4, you can submit work order to upgrade the background to VERSION V5)

Resources: One-click deployment of Hexo blog to Cloud COS object storage

Start a static website

accessTencent Cloud object Storage console=> Basic configuration => Static website,Enable the static website function

The customized CDN accelerated domain name was configured

accessTencent Cloud object Storage console=> Domain name and Transmission Management => User-defined CDN accelerated domain name,The customized accelerated domain name was configured

Parsing the domain name

accessMy domain name managementAdd domain name resolution records => Make the domain name point to the CNAM domain name

Getting configuration parameters

Firstly, we need to obtain the following configuration parameters from Tencent Cloud Console:

The name of the describe
SecretId The project identification ID owned by the developer for identity authentication
SecretKey The project identity key owned by the developer
Bucket The name of the container used to store data in COS
Region Information about the region where the Bucket resides.

Obtain the SecretId and SecretKey

Access Access Management => Key Management => [Add Key] => Obtain SecretId and SecretKey

You are advised to add subusers, set permissions, and obtain the keys of subusers.

Obtain bucket and region

Access the Tencent Cloud Object Storage Console => Obtain the bucket name and location

Configuration making Actions

First, we need to create a private blog repository on Github (blog Repository) to store the hexo source code and associate it with the local Hexo. Required configuration parameters:

The name of the describe
SECRET_ID SecretId of Tencent Cloud
SECRET_KEY SecretKey of Tencent Cloud
YUQUE_TOKEN Language finch Access Token
BUCKET Tencent cloud COS static website bucket name
REGION Tencent cloud COS static site name

Configuration making

Obtain the Github access Token

Access the GIthub Token configuration =>Generate new Token => Select necessary parameters to Generate a Token

Note: this Token only appears once, so it is best to copy it. If you forget it, you can only create a new one

Github Token Uses:

  • Used to upload articles to the blog repository while working on the assembly line.
  • This token will be used externally to call Github Actions in the following section

Configure warehouse Actions secrets

Enter the blog warehouse Settings, configure secrets. Get the Tencent cloud beforeSECRET_ID and SECRET_KEYAnd birdsYUQUE_TOKENConfiguration here.

SECRET_ID, SECRET_KEY, BUCKET, and REGION are used to upload static website files to COS YUQUE_TOKEN. GITHUB_TOKEN is not required and can be obtained directly from Github Actions

Configuring the blog Repository

In the root directory. New lot/workflows/main yaml files Here directly on the code:

name: Deplo To COS

on:
   # This can be enabled for local testing, but is not recommended after deployment, as it will involve some configuration changes and will trigger frequent builds many times
   Allow manual push trigger
  # push:
  # branches:
  # - master
  Allow external warehouse events to be triggered
  repository_dispatch:
    types:
       The value here needs to be consistent with the event_type of the cloud function below
      - start

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - name: Check branch
        uses: actions/checkout@master

      - name: Installing the Node Environment
        uses: actions/setup-node@master
        with:
          node-version: "12.x"

      - name: Cache depend on
        uses: actions/cache@v1
        id: cache
        with:
          path: node_modules
          key: ${{runner.OS}}-${{hashFiles('**/package-lock.json')}}

      - name: Install dependencies
        if: steps.cache.outputs.cache-hit ! = 'true'
        run: | export TZ='Asia/Shanghai' npm install
      - name: Install COS dependencies
        run: | sudo pip install coscmd sudo pip install tccli
      - name: Configuration COS
        env:
          SECRET_ID: The ${{ secrets.SECRET_ID }}
          SECRET_KEY: The ${{ secrets.SECRET_KEY }}
          BUCKET: The ${{ secrets.BUCKET }}
          REGION: The ${{ secrets.REGION }}
        run: | coscmd config -a $SECRET_ID -s $SECRET_KEY -b $BUCKET -r $REGION tccli configure set secretId $SECRET_ID tccli configure set secretKey $SECRET_KEY tccli configure set region $REGION
      - name: The article of the Latori whisperer
        env:
          YUQUE_TOKEN: The ${{ secrets.YUQUE_TOKEN }}
        run: | npm run yuque:clean npm run yuque:sync
      - name: Configure Git username email
        run: | git config --global user.name "1874" git config --global user.email "[email protected]"
      - name: Submit yuque pulled articles to GitHub repository
        run: | echo `date +"%Y-%m-%d %H:%M:%S"` begin > time.txt git add . git commit -m "Refresh yuque json" -a
      - name: Push articles to the repository
        uses: ad-m/github-push-action@master
        with:
           # GITHUB_TOKEN does not need to be configured in secrets
          github_token: The ${{ secrets.GITHUB_TOKEN }}

      - name: Generating static files
        run: | npm run hexo:clean npm run hexo:build
      - name: Upload articles to COS and refresh CDN
        run: | coscmd upload -rfs --delete ./public/ / tccli cdn PurgePathCache --cli-unfold-argument --Paths https://1874.cool/ --FlushType flush
Copy the code

Configure Tencent cloud function

  1. If you access the cloud number console, create a cloud function
  2. The template is chosen from scratch, the function type is chosen as event function, and the runtime environment is chosen as PYTHon2.7
  3. Write function code online
# -*- coding: utf8 -*-
import requests
def main_handler(event, context) :
    r = requests.post("https://api.github.com/repos/LetTTGACO/1874/dispatches",
    json = {"event_type": "start"},
    headers = {"User-Agent":'the curl / 7.52.1'.'Content-Type': 'application/json'.'Accept': 'application/vnd.github.everest-preview+json'.'Authorization': 'Token Github access token'})
    if r.status_code == 204:
        return "This's OK!"
    else:
        return r.status_code
Copy the code

Event_type The value of event_type must be consistent with the types value of repository_dispatch in Github Actions. Authorization The value is String “token + Github access token”, don’t forget to add token

  1. Trigger configuration => Custom configuration => The following figure shows the configuration

  1. After the deployment is complete, the cloud function address is at the bottom of the trigger management

Configuration finch Webhook

Visit blog knowledge base => Settings => Message push, select other channels, set the robot name and cloud function address obtained above, and select trigger conditions

Release documents and update documents, you need to select a large update of the document, push to the followers, will trigger the Webhook. But after my test, once a certain article selected ** document has a major update, push to the followers. Subsequent updates, whether or not the selected document has a major update, are pushed to followers, ** will trigger webhook. If errors occur due to frequent deployment, the review phase is recommended. It can also be triggered manually each time through the test button.

Done! Published articles

Whether it is publishing new articles or updating and deleting operations, as long as the document has a major update, push to followers can be triggered automatically.

Q&A

Finch picture display abnormality (anti – theft chain) solution

Because the bird pictures by the anti-theft chain restrictions, will lead to deployment, the blog site display abnormal pictures. There are two ways to deal with it:

  1. When using images on a finch, avoid copying images directly to the finch. After uploading the image to your chart, use Markdown’s image syntax directly:! [](https://xxxx.com/a.jpg)Insert the image in the appropriate position, for example:

  1. In order not to ruin the sparrow editor experience, I modified the yuque-hexo source code and released the yuqe-hexo-with-CDN plug-in. After uploading the pictures in The language finch to Tencent Cloud COS picture bed, the original language Finch picture link was replaced.

Yuqe hexo – with – the CDN plug-in

Replace the dependency yuque-hexo with yuqe-hexo-with-cDN

npm i yuqe-hexo-with-cdn
Copy the code

X-code has now incorporated my scheme into the main branch and can be configured directly using Yuque-hexo

Modify package.json for the blog repository

{
  "scripts": {
    "hexo:build": "hexo generate"."hexo:clean": "hexo clean"."deploy": "hexo deploy"."server": "hexo server"."hexo": "npm run hexo:clean && npm run hexo:build && npm run server"."yuque:clean": "yuque-hexo clean"."yuque:sync": "yuque-hexo sync"."yuque": "npm run yuque:clean && npm run yuque:sync"
  },
  "yuqueConfig": {
    "postPath": "source/_posts"."baseUrl": "https://www.yuque.com/api/v2"."login": "Personal Path of The Whisperer"."repo": "Knowledge base path"."onlyPublished": true."onlyPublic": true."imgCdn": {
      "enabled": true."bucket": "COS bucket name"."region": "COS domain name"."prefixKey": "blog-images"}}}Copy the code

Note: After this function is enabled, all matched pictures will be uploaded to COS

Parameter names meaning The default value
enabled Whether open false
bucket Bucket name of Tencent COS
region Region of Tencent COS
prefixKey File prefix

PrefixKey note: If you need to upload images to the COS root directory, prefixKey is not configured. If you want to upload the image file to the blog/image directory, set prefixKey to “prefixKey”: “blog/image”. Directory names do not need to be preceded by slashes

Uploading to COS chart bed also requires the SECRET_ID and SECRET_KEY of Tencent Cloud to be injected as environment variables, but in the previous process, we have already injected secrets in the blog warehouse, so there is no need for additional injection here. Yuqe-hexo-with-cDN