和Java自動部署的思路一樣,通過在/usr/bin下建立mvn鏈接,指向/etc/alternatives/mvn鏈接,/etc/alternatives/mvn指向/usr/mvn3鏈接,/usr/mvn3鏈接指向/usr/apache-maven-3.0.4目錄。
由於maven運行是要檢查JAVA_HOME環境變量,而JAVA_HOME環境變量的設置可以放在安裝Java的腳本中執行。
現在看一下maven的安裝腳本install.sh
- #!/bin/bash
-
- source check.sh
- source ../common/tool.sh
-
- hasMaven
- r=$?
-
- SRC_MAVEN_FILES=./apache-maven-3.0.4
- DST_MAVEN_FILES=/usr/apache-maven-3.0.4
- #!/bin/bash
-
- source /etc/environment
-
- if [ $r -eq 1 ]
- then
- echo "maven was installed"
- else
- echo "maven was not installed"
- copyFolder $SRC_MAVEN_FILES $DST_MAVEN_FILES
- createLink $DST_MAVEN_FILES /usr/mvn3
- createLink '/usr/mvn3/bin/mvn' '/etc/alternatives/mvn'
-
- createLink /etc/alternatives/mvn /usr/bin/mvn
- fi
tool.sh腳本位於common目錄裡面。整個自動化部署的目錄結構如下:
- chenshu@sloop2:~/work/189/appengine/deploy$ tree -L 2
- .
- ├── common
- │ └── tool.sh
- ├── java
- │ ├── check.sh
- │ ├── install.sh
- │ ├── jdk1.6.0_35
- │ └── readme
- ├── maven
- │ ├── apache-maven-3.0.4
- │ ├── check.sh
- │ └── install.sh
- └── readme
以後還會增加其他的子項目,比如mysql, glassfish, mongodb, nginx,或許有天我會將之建立一個開源項目。 :)
tool.sh腳本如下:
- #!/bin/bash
-
- function copyFolder {
-
- if [ -d "$2" ]
- then
- echo "$2 folder exists already, stop copying."
- else
- echo "$2 folder doesn't exists, start copying..."
- cp -r $1 $2
- fi
- }
-
- #create a link($2) to file($1)
- function createLink {
-
- if [ -f "$2" ]
- then
- echo "$2 link exists already, removing it..."
- rm $2
- else
- echo "$2 link doesn't exists, creating it..."
- fi
- echo "creating link: $2 to $1"
- ln -s $1 $2
- }
-
- # $1 variable name
- # $2 expected value
- # put this into /etc/environment if not found
- function setEnv {
- source /etc/environment
- if [ "${!1}" = "$2" ]
- then
- echo "$1 is correct: $2"
- else
- echo "$1 is wrong: ${!1} != $2"
-
- h=`grep "$1=\"$2\"" /etc/environment`
- if [ -n "$h" ]
- then
- echo "/etc/environment has $1 already"
- else
- echo "Adding $1 into /etc/environment..."
- echo "$1=\"$2\"" >> /etc/environment
- fi
- source /etc/environment
- fi
- }
maven目錄下還有一個check.sh腳本:
- #!/bin/bash
-
- #check java is available in this session
- function hasMaven {
- v=`mvn -version 2>&1`
-
- echo 'check maven ...'
-
- pos=`expr match "$v" 'Apache Maven 3.0.4'`
- if [ $pos -gt 0 ]
- then
- return 1
- else
- return 0
- fi
- }
到現在為止,用模塊化的方式編寫bash,讓後面的工作可以復用前面的腳本。感覺輕松多了。