當前正在開發的項目中,須要部署vue前端代碼。可是給了一臺不能連外網的服務器。綜合考慮下,採起的方案是先從一臺能夠連外網的服務器上下載好代碼並打包好,而後將打包好的dist文件夾傳給不能連外網的服務器。這其中有幾個難點是之前沒有作過的,特記錄以下。前端
(1)如何實現兩臺服務器間的免密ssh傳輸?
(2)如何實現git的免密ssh方式下載代碼?
(3)shell腳本如何編寫?vue
cd ~/.ssh ssh-keygen -t rsa //生成密鑰和公鑰 ssh-copy-id root@10.*.*,* //將公鑰(名爲id\_rsa.pub文件)追加到認證文件(名爲authorized\_keys文件) ssh root@10.*.*.* //測試是否鏈接成功
cd ~/.ssh ssh-keygen -q -f water-client-dev -P '' //再生成一堆密鑰和公鑰,公鑰配到gitlab用戶對應的設置。 //將公鑰賦值到SSH keys裏面。而後點擊"Add key"生成print cd 代碼目錄 eval "$(ssh-agent -s)" ssh-add ~/.ssh/water-client-dev //加載密鑰,就能夠clone代碼了~~
#!/bin/bash # # desc:前端構建腳本,從已有nodejs環境的服務器構建,並上傳前端服務器。因前端服務器沒法從依賴庫下載所需依賴,需經過構建機中轉。 # preDefine: # 一、private key put in ~/.ssh/water-client-dev for passWord free remote login # 二、mkdir local and remote build path # 腳本位置:與前端項目同級根目錄 eval "$(ssh-agent -s)" >>/dev/nul ssh-add ~/.ssh/water-client-dev 2>>/dev/nul origin_dictionary='/DATA/water/client/ui' build_file_path="dist" generated_tar_file_name="build.tar" target_host="10.*.*.*" target_dictionary="/DATA/water/client/" target_host_user='root' branch_name=$2 # 進入構建目錄,即package.json所在目錄 #cd tip update_src(){ echo "一、start update>>>>>>>" cd $origin_dictionary git pull # 若是設置branch參數,檢查是否須要checkout if [[ -n "$branch_name" ]]; then git branch|grep "\* $branch_name" if [ $? -ne 0 ]; then echo "checkout new branch"; git checkout $branch_name;git pull; fi fi # git checkout . # git pull ssh-agent -k >>/dev/nul echo ">>>>>>>>update complete" } build_prj(){ echo "二、start build>>>>>>>>" echo "check whether package.json updated" modified=$(find $origin_dictionary/package.json -mmin -1) if [ -n "$modified" ] then echo "modified, run npm install" npm install --unsafe-perm if [ $? -ne 0 ] then exit 1; fi else echo "not modified" fi npm run build if [ $? -ne 0 ] then exit 1; fi echo ">>>>>>>>build complete" } update_src build_prj echo "三、start tar>>>>>>>>" # remove old and tar new if [ -e $generated_tar_file_name ] then echo "file exist" echo "start remove file" rm -f $generated_tar_file_name else echo "file not exist" fi echo "creating tar file" tar -cf $generated_tar_file_name $build_file_path echo "created succeed" echo ">>>>>>>>tar complete" echo "四、start upload to Remote server>>>>>>>>" # scp -i $generated_tar_file_name root@$target_host:$target_dictionary scp $generated_tar_file_name root@$target_host:$target_dictionary echo ">>>>>>>>upload complete" echo "五、start untar at Remote server>>>>>>>>" # remove old and untar new ssh root@$target_host "cd $target_dictionary;rm -rf $build_file_path;tar -xf $generated_tar_file_name ;exit;" echo ">>>>>>>>update complete"
配置jenkins設置爲,git代碼已提交,就自動執行該腳本。
配置jenkins:
將紅框中的連接複製到gitlab中的webhook頁面中,gitlab調用Jenkins的url觸發構建
在jenkins構建頁面輸入調用該腳本的命令
node
配置完後,就能夠直接代碼一更新,jenkins就自動調用腳本,完成代碼的更新、打包和傳輸工做啦~~git