基于githubtravis自动部署vue项目到远端服务器

34次阅读

共计 1863 个字符,预计需要花费 5 分钟才能阅读完成。

前期准备

  • github账号一个
  • 一个 vue 的项目
  • 一台 linux 服务器

travis 中添加项目

travis是基于 github 的,所有只有 github 的账号可以登录 travis,开发者必须有一个github 的账号,登录后,点击加号,开始添加项目

点击Manage repositories on GitHub,前往 github 中选择项目

这里 github 提供的两种模式,第一种添加所有项目,第二种添加指定项目,一般我们选择第二种添加需要添加的项目

Github 生成访问令牌 (添加授权)

github 的个人中心,在 https://github.com/settings/tokens/ 路径下,生成一个访问令牌,添加到 travis 中,给 travis 操作仓库的权限

复制令牌内容,进入 travis 中的中,找到 SSH key 的菜单,将令牌内容贴入,点击Add

travis 配置文件

在项目根目录下,新建 .travis.yml 文件。travis 要执行的自动化步骤,都需要在该文件中配置, 这里是一个最简单的配置文件,当 travis 检测到 master 分支代码发生变化时,自动执行 npm install 和 npm run build

language: node_js
node_js:
- 10.16.0
cache:
  directories:
  - node_modules
install:
- npm install
before_script: 

script:
- npm run build

after_script: 

branches:
  only:
  - master

关于 travis 的更多配置,参考阮老师的教程:

http://www.ruanyifeng.com/blo…

travis 免密登录远端服务器

部署 dist 目录到服务器

开发者在本地执行 npm run build,编译后生成 dist 目录,服务器需要的也是 dist 目录。travis 要做的就是把 dist 目录自动发送到服务器

先说思路,当 travis 执行 build 生成目标文件后,travis 把 dist 目录提交到仓库的指定分支,比如叫 deploy 分支,通过 ssh 自动登录服务器,执行 git pull,把 deploy 分支拉下来

after_script: 
  - cd ./dist
  - git init
  - git config user.name "your name"
  - git config user.email "your email"
  - git add .
  - git commit -m "Travis CI Auto Builder"
  - git push --force --quiet "https://${GH_TOKEN}@${GH_REF}" master:deploy
  - ssh your-name@xx.xx.xx.xx 'cd /your-path && git fetch --all && git reset --hard origin/deploy && git pull'

部署成功

配置文件上的操作执行成功后,你的项目就多了这个高大上的标志

一些报错

Travis-CI 解密证书时报错

报错提示一般是这样的:

openssl aes-256-cbc -K $encrypted_d3c25c1810a6_key -iv $encrypted_d3c25c1810a6_iv -in id_rsa.enc -out ~\/.ssh/id_rsa -d
~/.ssh/id_rsa: No such file or directory
The command "openssl aes-256-cbc -K $encrypted_d3c25c1810a6_key -iv $encrypted_d3c25c1810a6_iv -in id_rsa.enc -out ~\/.ssh/id_rsa -d" failed and exited with 1 during .

这个报错情况的出现,有可能是因为在使用 travis encrypt-file ~/.ssh/id_rsa --add 命令生成加密密钥时,自动增加了转义字符串,需要手动删除转义字符

生成的密钥是这样的:

- openssl aes-256-cbc -K $encrypted_d3c25c1810a6_key -iv $encrypted_d3c25c1810a6_iv -in id_rsa.enc -out ~\/.ssh/id_rsa -d

删除转义字符后是这样的:

- openssl aes-256-cbc -K $encrypted_d3c25c1810a6_key -iv $encrypted_d3c25c1810a6_iv -in id_rsa.enc -out ~/.ssh/id_rsa -d

正文完
 0