Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> 關於Linux

用 Shell 腳本自動化部署 gitosis 代碼庫管理環境

gitosis 的安裝步驟其實固定,寫成腳本可以省下每次重複的力氣。整套流程分成兩支腳本:bootstrap.sh 負責建立 Python 虛擬環境並安裝 gitosis,gitosis-install.sh 則負責建使用者、同步環境與初始化管理庫。

先安裝 git

wget https://www.codemonkey.org.uk/projects/git-snapshots/git/git-latest.tar.gz
tar xzvf git-latest.tar.gz
cd git-{date}
autoconf
./configure --with-curl=/usr/local
make
sudo make install

bootstrap.sh:建立獨立環境

#!/bin/sh
#
mkdir -p bin
curl https://raw.github.com/pypa/virtualenv/master/virtualenv.py > bin/virtualenv.py
python ./bin/virtualenv.py --distribute gitosis-env
. gitosis-env/bin/activate
mkdir src
cd src
git clone https://github.com/tv42/gitosis.git
cd gitosis
python ./setup.py install
cd ../..

這裡用 virtualenv 把 gitosis 裝進獨立環境,好處是不污染系統 Python,移除時直接刪掉整個 gitosis-env 目錄即可。

gitosis-install.sh:初始化服務端

#!/bin/sh
#
# Create gitosis env
LOCAL_DIR=$( cd $(dirname $0) && pwd)
GITOSIS_USER=git
GITOSIS_SERVER=efate
GITOSIS_HOMEDIR=/srv/${GITOSIS_SERVER}/git

git_user=$(getent passwd ${GITOSIS_USER})
if [ -z "${git_user}" ]
then
    sudo adduser \
        --system \
        --shell /bin/sh \
        --gecos 'git version control' \
        --group \
        --disabled-password \
        --home ${GITOSIS_HOMEDIR} \
        ${GITOSIS_USER}
else
    GITOSIS_HOMEDIR=$(echo ${git_user} | cut -d: -f6)
fi

#TODO: check env if exists ... (update ?)
sudo rsync -av ${LOCAL_DIR}/gitosis-env ${GITOSIS_HOMEDIR}
sudo python ${LOCAL_DIR}/bin/virtualenv.py --relocatable ${GITOSIS_HOMEDIR}/gitosis-env

[ ! -f ~/.ssh/gitosis.pub ] && ssh-keygen -t rsa -f ~/.ssh/gitosis
sudo -H -u ${GITOSIS_USER} ${GITOSIS_HOMEDIR}/gitosis-env/bin/gitosis-init < ~/.ssh/gitosis.pub
sudo sh -c "printf '. \${HOME}/gitosis-env/bin/activate' > ${GITOSIS_HOMEDIR}/.profile"
sudo chown -R git:git ${GITOSIS_HOMEDIR}

幾個設計細節

腳本先用 getent passwd 判斷 git 使用者是否存在,若已存在就從 passwd 資料中取出家目錄,避免重複建立而報錯。接著用 rsync 把虛擬環境同步到 git 使用者的家目錄,再以 --relocatable 重建環境中的絕對路徑,讓搬移後的環境仍可使用。ssh-keygen 只在公鑰不存在時才產生,最後用管理員公鑰執行 gitosis-init 建立管理庫,並把 activate 寫入 .profile 讓登入時自動進入環境。

執行方式:先跑 bootstrap.sh,再跑 gitosis-install.sh。實際部署時,記得把 GITOSIS_SERVER 與 GITOSIS_HOMEDIR 改成符合自身環境的值,並確認 sudo 權限可用。

Copyright © Linux教程網 All Rights Reserved