使用GitLab Ci 自动部署Hexo到GitHub

使用GitLab Ci 自动部署Hexo到GitHub

也许这个操作有点傻(sao),为啥有GitLab Pages了,还要在GitHub 上搭建Hexo呢?好吧,不管那么多了,反正就是可以。

前言

GitHub 提供pages 功能,具体参见 What is GitHub Pages?,可以让你搭建自己的网站,当然只能是静态的。但是可以利用第三方博客框架自动生成静态网站。Hexo就是其中一个,至于如何使用,网上搜索一大堆,这里不赘述。

但是Hexo是基于NodeJs的,那么问题来了,每次写完文章,都需要Hexo g编译一次,还要上传编译好的文件到GitHub上面,这就限制了随时随地写文章的冲动。

Gitlab是个好东西,不但提供了Private Repository, 还提供了GitLab CI持续集成部署环境。

基本思路

随时随地任意终端写MarkDown文章 –> 到GitLab的“_posts”目录添加文件 –> 自动触发GitLab CI Pipeline –> 自动编译并部署到GitHub

具体实现

  1. 首先在GitHub上面创建一个repo,开启Pages
  2. 在GitLab上面创建一个Private的repo用来放博客的源代码
  3. 在GitLab添加一个SSH Private Key 文件,用于push到GitHub
  4. 在GitLab上添加 .gitlab-ci.yml 文件用户自动部署

准备就绪,下面是.gitlab-ci.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
variables:
BUILD_IMAGE: node:9.8.0
stages:
- build
##############
# build job
##############
build_job:
stage: build
image: $BUILD_IMAGE
cache:
paths:
- node_modules/
script:
- npm install hexo -g
- npm install
- npm install hexo-deployer-git --save
- npm install hexo-wordcount --save
- eval $(ssh-agent -s)
- chmod 700 cctgrsa
- ssh-add cctgrsa
- git config --global user.email "damoshushu@cctg2010.com"
- git config --global user.name "CCTG2010GitLab"
- echo StrictHostKeyChecking no >> /etc/ssh/ssh_config
- hexo d -g
- echo "Deploy succssed!"

可以直接Clone https://gitlab.com/damoshushu/github-pages-auto-deployer.git

注解一下:

  • cctgrsa 文件是 GitHub 的private ssh key,push操作的时候会用到,由于我们放在GitLab的private 项目里面,所以不用担心被人看到
  • “echo StrictHostKeyChecking no >> /etc/ssh/ssh_config” 是为了运行git push的时候不弹出是否继续的提示
  • “npm install hexo-deployer-git” 插件可以直接push到git

结果展示

GitLab 私有仓库目录结构如下:

Pipeline 自动触发如下:

我的博客地址:

大漠叔叔的博客

据说打赏我的人工资涨的比别人多~~~