2016年6月14日 星期二

Auto deployment with gitlab

Purpose

主要是希望可以在 git push 時,去觸發遠端伺服器的repo做更新。

Environment

Local machine: OS X 10.11.5
Remote machine: CentOS Linux release 7.2.1511 (Core)

Requirement tools:

Setting

由於 Git-Auto-Deploy 這個沒有 yum repo 可以使用,所以就按照原作者的建議,使用 repository 的方式來做安裝。
Remote machine:
git clone https://github.com/olipo186/Git-Auto-Deploy.git
cd Git-Auto-Deploy
使用 pip 來安裝相依性套件
sudo pip install -r requirements.txt
複製設定檔,並做修改,確認 pidfilepath 路徑是可以被寫入的
cp config.json.sample config.json
下列是可以用的參數表,請依照自已的需求做設定
Command line optionEnvironment variableConfig attributeDescription
–daemon-mode (-d)GAD_DAEMON_MODERun in background (daemon mode)
–quiet (-q)GAD_QUIETSupress console output
–config (-c) GAD_CONFIGCustom configuration file
–pid-file GAD_PID_FILEpidfilepathSpecify a custom pid file
–log-file GAD_LOG_FILElogfilepathSpecify a log file
–host GAD_HOSThostAddress to bind to
–port GAD_PORTportPort to bind to

Sample config

使用json格式來撰寫設定檔
{
  "pidfilepath": "~/.gitautodeploy.pid",  # 預設在家目錄,可自行定義
  "logfilepath": "~/gitautodeploy.log",   # 預設在家目錄,可自行定義,並且要有寫入的權限
  "host": "0.0.0.0",                      # 綁定主機IP,也是listen IP
  "port": 8001,                           # 要開的Port
  # 定義所有repo可輸出的訊息,可以是二個特別的指令或是可被執行的script
  # [0] = The pre-deploy script.
  # [1] = The post-deploy script.
  "global_deploy": [
    "echo Deploy started!",               
    "echo Deploy completed!"
  ],
  # 預設是NOSET(all detail),建議用INFO
  "log-level": "INFO",
  # 要設定的repositories
  "repositories": [
    {
      # Git Repo的連結網址
      "url": "http://xxx.xxx.xxx/9527.git",
      # 要 check out 的分支,通常會是master
      "branch": "master",
      # 遠端使用的名稱,可用 git remote 查詢
      "remote": "origin",
      # 要部署的路徑,第一次執行時,會自動幫你clone下來,如果repo被刪除時,就無法正常去做更新,只執行deploy script,修複的方法是重新再執行一次程式就可以解決了。
      "path": "/path/to/repo",
      # 要執行的指令,如果 path 有設定,就只會執行pull
      "deploy": "echo deploying"
    }
  ]
}
還有二個參數我還沒用到, filters 和 secret-token

Start Git-Auto-Deploy manually using

啟用 Git-Auto-Deploy 有三種方法
  • command-line
python gitautodeploy --config config.json
  • crontab
@reboot /usr/bin/python /path/to/Git-Auto-Deploy/gitautodeploy --daemon-mode --quiet --config /path/to/git-auto-deploy.conf.json
  • daemon
cp platforms/linux/initfiles/systemd/git-auto-deploy.service /etc/systemd/system
編輯 git-auto-deploy.service,以下是我的範本
[Unit]
Description=GitAutoDeploy

[Service]
User=root
Group=root
WorkingDirectory=/opt/Git-Auto-Deploy/
ExecStart=/usr/bin/python /opt/Git-Auto-Deploy/gitautodeploy --daemon-mode --config config.json

[Install]
WantedBy=multi-user.target
接下來就把 Git-Auto-Deploy 複製到 /opt 下,並修改資料夾權限
cp -Rp ~/Git-Auto-Deploy  /opt
chown -R root:root /opt/Git-Auto-Deploy
Reload Daemons
systemctl daemon-reload
systemctl start git-auto-deploy
systemctl enable gitautodeploy

Gitlab webhook

  1. Go to your repository -> Settings -> Web hooks
  2. In “URL”, enter your hostname and port (your-host:8001)
  3. Hit “Add Web Hook”
參考資料: