创建hosts文件
创建ansible-playbook执行时所用到的hosts文件,例如 /etc/redis/hosts
利用shell命令根据传入的host名和地址写入hosts文件:
#sethosts.sh echo [$1] >>/etc/redis/hosts count=2 while [ $# -ge 2 ];do sudo echo $2 >>/etc/redis/hosts let count=count+1 shift done
调用命令:
sh sethosts.sh webservers 10.11.12.13 10.11.12.14
hosts文件:
[webservers] 10.11.12.13 10.11.12.14
playbook编写
编写设置redis参数的playbook,host以变量传入,就是上一步写入的host名:
#setRedisParam.yml
--- - hosts: "{{hostname}}" vars: http_port: 80 max_clients: 200 remote_user: root tasks: - redis: command: config name: "{{paraname}}" value: "{{paravalue}}" - name: redis config rewrite command: /home/admin/redis-4.0.7/src/redis-cli config rewrite
调用playbook的脚本:
#setvar.sh
ansible-playbook -i /etc/redis/hosts /setRedisParam.yml --extra-vars "hostname=$1 paraname=$2 paravalue=$3"
调用命令:
sh setvar.sh webservers maxclients 777
java关键代码
利用org.apache.commons.cli.CommandLine进行命令调用
String cmd = "sh"; ExecResult resultAnsibleHosts = shellExecCommand.exec(cmd, setHostsArgs); ExecResult resultAnsible = shellExecCommand.exec(cmd, ansibleArgs); if(!resultHosts.isSuccess() ||!resultAnsibleHosts.isSuccess() || !resultAnsible.isSuccess()){ return null; }