使用Travis-CI自动化部署Hexo博客

使用 Travis-CI 自动化部署 Hexo 博客

Travis CI 是开源的持续集成构建项目,用来构建托管在GitHub上的代码。

架构图如下:

整个流程就是本地编辑*.md文件,然后push到github中source分支,Travis-CI检测到分支更新从而根据配置文件建立虚拟机进行测试/构建,并将结果部署到github中master分支,实现github pages访问。

1. 配置Hexo+GitHub

配置方法省略,参见"使用Hexo+Github搭建个人网站"。

GitHub 仓库分支架构:
  master分支:提供Pages服务
    存放 Hexo 生成的静态文件
  source分支:建议私有仓库
    存放 Hexo 项目文件以及构建配置文件{blog/source/.travis.yml}

更改本地环境配置

cd blog #进入Hexo项目/博客目录
git init #初始化为git仓库
git checkout -b source #创建并切换到 source 分支
git add .
git commit -m "xxx"
git remote add origin git@github.com:yourname/yourname.github.io.git #关联远程仓库
git push origin source:source #提交本地source分支到远程仓库source分支

2. Travis CI配置

使用GitHub账户登陆Travis CI,它会自动发现GitHub上的已有仓,选择需要执行持续集成的仓库。

本教程为:yourname/yourname.github.io

A. General设置

进入设置选项,开启以下服务:

Build only if .travis.yml is present 表示“只有当 .travis.yml 存在时才构建”
Build branch updates 表示“当分支更新时构建” 两个选项

B. 配置 Acess Token

还是设置选项,增加一条环境变量{Enviroment Variables}:

name:与github开发者设置中 Personal access tokens 设置一致。

value:在github开发者设置中 Personal access tokens 页面,新建token,并勾选相应权限。

权限:{这里只需要 repo 下全部和 user 下的 user:email 即可}。

不勾选后面的 Display value in build log。

Travis可通过调用此变量获得github的权限,从而将构建后的静态文件push到github。

3. 配置 .travis.yml

在本地环境的源码分支{这里是source分支}的根目录下新增一个 .travis.yml 配置文件,内容如下:

language: node_js
node_js: stable

cache:
    directories:
        - node_modules

before_install:
  - npm install -g hexo-cli

install:
  - npm install
  - npm install hexo-deployer-git --save

before_script:
  - git config --global user.name "user_name" 
  - git config --global user.email "user_email"

script:
  - hexo clean
  - hexo generate

after_script:
  - sed -i "s/gh_token/${token_name}/g" ./_config.yml
  # token_name 为上一步中Travis环境变量中设置的name
  - hexo deploy

branches:
  only:
    - source

修改_config.yml

deploy:
  type: git
  repo: https://gh_token@github.com/yourname/yourname.github.io.git
  branch: master

4. 日常使用

A.使用 hexo new 新建并编辑文章,或者手动编写md文档放入 source/_post 文件夹

B.使用命令:git push origin source:source 提交

特别说明:

可以使用两个不同仓库进行部署,如:将source部署在一个私有仓库中确保源码安全。

如果使用Coding Pages服务,其自带集成功能,配置方法类似。

如果使用VPS自建Pages服务,可搭建Jenkins实现。

posted @ 2020-03-30 15:27  Beavan  阅读(333)  评论(0编辑  收藏  举报