一,建立states文件java
在/srv/salt目錄下建立jdk目錄,並在jdk目錄建立init.sls文件,init.sls文件內容以下:bash
jdk-file:app
file.managed:less
- source: salt://jdk/files/jdk1.6.0_39.tar.gzide
- name: /usr/java/jdk1.6.0_39.tar.gz測試
- include_empty: Trueui
jdk-install:vagrant
cmd.run:ip
- name: '/bin/tar -zxf jdk1.6.0_39.tar.gz && /bin/ln -s jdk1.6.0_39 latest 'rem
- cwd: /usr/java
- unless: 'test -e jdk1.6.0_39'
- require:
- file: jdk-file
jdk-rmzip:
file.absent:
- name: /usr/java/jdk1.6.0_39.tar.gz
/root/.bashrc:
file.append:
- text:
- export JAVA_HOME=/usr/java/latest
- export PATH=$JAVA_HOME/bin:$PATH
上面sls文件須要引用jdk1.6.0_39.tar.gz文件,故須要下載jdk1.6.0_39.bin安裝以後將其打包成jdk1.6.0_39.tar.gz拷貝到/srv/salt/jdk/files目錄。
init.sls文件執行過程包括如下幾個步驟:
jdk-file,將salt://jdk/files/jdk1.6.0_39.tar.gz文件拷貝到/usr/java
jdk-install,解壓文件
jdk-rmzip,刪除壓縮包
/root/.bashrc,設置JAVA_HOME
修改top.sls文件(該步驟爲可選),添加jdk.init:
base:
'*':
- jdk.init
測試運行
在master上運行下面命令,並觀察運行結果:
[root@sk1 vagrant]# salt '*' state.sls jdk
sk2:
----------
ID: jdk-file
Function: file.managed
Name: /usr/java/jdk1.6.0_39.tar.gz
Result: True
Comment: File /usr/java/jdk1.6.0_39.tar.gz updated
Changes:
----------
diff:
New file
mode:
0644
----------
ID: jdk-install
Function: cmd.run
Name: /bin/tar -zxf jdk1.6.0_39.tar.gz && /bin/ln -s jdk1.6.0_39 latest
Result: True
Comment: unless execution succeeded
Changes:
----------
ID: jdk-rmzip
Function: file.absent
Name: /usr/java/jdk1.6.0_39.tar.gz
Result: True
Comment: Removed file /usr/java/jdk1.6.0_39.tar.gz
Changes:
----------
removed:
/usr/java/jdk1.6.0_39.tar.gz
----------
ID: /root/.bashrc
Function: file.append
Result: True
Comment: Appended 0 lines
Changes:
Summary
------------
Succeeded: 4
Failed: 0
------------
Total: 4
從上能夠看出成功了4個,失敗爲0。
安裝了jdk以後,須要重啓minion(還須要修改minion啓動腳本,讓minion加載上系統環境變量,詳細說明,見安裝SaltStack和halite)才能經過下面腳本運行java相關的命令,如java、jps等等:
salt '*' cmd.run 'jps'
不然,你須要經過下面腳原本執行:
salt '*' cmd.run 'source /root/.bashrc ;jps'
二,設置pillar
將上面的jdk/init.sls文件修改成經過pillar引用變量
a.首先在/srv/pillar目錄建立jdk目錄,並在jdk目錄下建立init.sls文件,內容以下:
jdk:
name: jdk1.6.0_39
srvpath: salt://jdk/files
homepath: /usr/java
b.在/srv/pillar/top.sls中添加jdk.init
base:
'*':
- jdk.init
c.修改/srv/salt/jdk/init.sls文件爲從pillar引入變量,內容以下:
jdk-file:
file.managed:
- source: {{pillar['jdk']['srvpath']}}/{{pillar['jdk']['name']}}.tar.gz
- name: {{pillar['jdk']['homepath']}}/{{pillar['jdk']['name']}}.tar.gz
- makedirs: True
jdk-install:
cmd.run:
- name: 'unzip -q {{pillar['jdk']['name']}}.tar.gz'
- cwd: {{pillar['jdk']['homepath']}}
- unless: 'test -e {{pillar['jdk']['name']}}'
- require:
- file: jdk-file
jdk-rmzip:
file.absent:
- name: {{pillar['jdk']['homepath']}}/{{pillar['jdk']['name']}}.tar.gz
{{pillar['userhome']}}/.bashrc:
file.append:
- text:
- export JAVA_HOME={{pillar['jdk']['homepath']}}/{{pillar['jdk']['name']}}
- export PATH=$JAVA_HOME/bin:$PATH
d.參考上面,再次測試一遍