文章目录
1.个人环境
(1)Centos 7.0
(2)apache-tomcat-8.0.36
(3)jdk-7u79-linux-x64
老规矩,时空穿梭器:https://pan.baidu.com/s/1eozMB-pwrJi17GU98zr_rA
提取码:9eo3
2.配置服务器
这里,ftp、http服务器都行,我配置的http服务器,该服务可以在单独的服务器上(本人如此),也可以在ansible机器上,配置如下:
[root@tomcat ~]# systemctl stop firewalld
[root@tomcat ~]# systemctl disable firewalld
[root@tomcat ~]# sed -i 's/SELINUX=enforcing/SELINUX=disabled/g' /etc/selinux/config
[root@tomcat ~]# setenforce 0
[root@tomcat ~]# yum install httpd -y
[root@tomcat ~]# systemctel start httpd
[root@tomcat ~]# mkdir - p /var/www/html/software
3.创建ansible-playbook的目录结构
注意:将该目录创建在/etc/ansible/下 ,因为有触发handle的条件,建立在其他目录下触发handle不生效。
3.1 定义hosts文件
3.2 定义入口文件tomcat_install.yaml
3.3 定义全局变量
注意:变量文件名称要和主机组名称相同。
[root@tomcat ~]# vim group_vars/tomcat
# Here are variables related to the Tomcat installation
http_port: 8080
https_port: 8443
#
# This will configure a default manager-gui user
#admin_username: admin
#admin_password: adminsecret
#
# Here are variables related to Download software from Http Server
http_server_ip: 192.168.239.6
dest_path: /software
jdk_ver: jdk7u79linuxx64.tar.gz
jdk_name: jdk1.7.0_79
tomcat_ver: apache-tomcat-8.0.36.tar.gz
tomcat_name: apache-tomcat-8.0.36
3.4 定义roles
[root@tomcat ~]# mkdir prepare tomcat
3.4.1 准备阶段的设置
[root@tomcat ~]# cd roles/prepare/
[root@tomcat ~]# mkdir tasks
[root@tomcat ~]# pwd
/etc/ansible/roles/prepare/tasks
[root@tomcat ~]# cat main.yaml
- name: create down dir
file: path={{ dest_path }} state=directory
- name: down jdk
get_url: url=http://{{ http_server_ip }}/software/{{ jdk_ver }} dest={{ dest_path }}
- name: down tom
get_url: url=http://{{ http_server_ip }}/software/{{ tomcat_ver }} dest={{ dest_path }}
3.4.2 tomcat安装阶段设置
[root@tomcat ansible]# cd roles/tomcat/
[root@tomcat tomcat]# mkdir files handlers tasks templates
[root@tomcat tomcat]# ls
files handlers tasks templates
[root@tomcat tomcat]# pwd
/etc/ansible/roles/tomcat
先介绍一下这四个文件:files文件里我存放了tomcat服务启动脚本,templates模板中存放了server.xml和tomcat.users.xml(前文提到过),handlers存放触发文件(后面会提到),tasks存放任务。
(1)tasks文件
[root@tomcat tomcat]# cd tasks/
[root@tomcat tasks]# ls
install_jdk.yaml install_tomcat.yaml main.yaml
主任务包含两个子任务
[root@tomcat tasks]# cat main.yaml
- include: install_jdk.yaml
- include: install_tomcat.yaml
子任务分别为:
[root@tomcat tasks]# cat install_jdk.yaml
- name: check java7
shell: /usr/bin/ls /usr/local/java7
register: java7
ignore_errors: true
- name: jie ya
command: chdir={{ dest_path }} /usr/bin/tar xf {{ jdk_ver }}
when: java7 is failure
- name: move to /usr/local
command: chdir={{ dest_path }} /bin/mv {{ jdk_name }} /usr/local/java7
when: java7 is failure
- name: check jdk variable
shell: cat /etc/profile
register: result
- name: jdk variable configuration /etc/profile file
shell: /usr/bin/echo {{ item }} >> /etc/profile; source /etc/profile
when: result.stdout.find('JAVA_HOME') == -1
with_items:
- export JAVA_HOME=/usr/local/java7
- export JAVA_BIN=/usr/local/java7/bin
- export PATH=$PATH:/usr/local/java7/bin
- export JRE_HOME=/usr/local/java7/jre
- export CLASSPATH=.:/usr/local/java7/lib:/usr/local/java7/jre/lib
- export JAVA_HOME JAVA_BIN PATH JRE_HOME CLASSPATH
- name: check jdk variable
shell: cat /root/.bashrc
register: bashrc_result
- name: jdk variable connfiguration /root/.bashrc file
shell: /bin/echo {{ item }} >> /root/.bashrc; source /root/.bashrc
when: bashrc_result.stdout.find('JAVA_HOME') == -1
with_items:
- export JAVA_HOME=/usr/local/java7/
注意:ansible这类远程执行的non-login shell 并不会加载/etc/profile和/.bash_profile下的环境变量,只是加载了/etc/bashrc和~/.bashrc。
[root@tomcat tasks]# cat install_tomcat.yaml
- name: add group
group: name=tomcat
- name: add user tomcat
user: name=tomcat group=tomcat
- name: jia ya tomcat
command: chdir={{ dest_path }} /usr/bin/tar xf {{ tomcat_ver }} -C /usr/local
- name: link
file: src=/usr/local/{{ tomcat_name }} path=/usr/local/tomcat state=link
- name: change
file: path=/usr/local/tomcat owner=tomcat group=tomcat state=directory recurse=yes
- name: Install Tomcat init
copy: src=tomcat-initscript.sh dest=/etc/init.d/tomcat mode=0777
#- name: start tomcat
## service: name=tomcat state=started
- name: start tomcat
shell: service tomcat start
- name: Config server
template: src=server.xml dest=/usr/local/tomcat/conf/server.xml
notify:
- Restart_Tomcat
- name: Configue Tomcat user
template: src=tomcat-users.xml dest=/usr/local/tomcat/conf
notify:
- Restart_Tomcat
(2)files文件
files文件中设置脚本文件内容,脚本设置以tomcat用户启动关闭
[root@tomcat files]# cat tomcat-initscript.sh
#!/bin/bash
#
# chkconfig: 345 99 28
# description: Starts/Stops Apache Tomcat
#
# Tomcat 6 start/stop/status script
#
#Location of JAVA_HOME (bin files)
export JAVA_HOME=/usr/local/java7
#Add Java binary files to PATH
export PATH=$JAVA_HOME/bin:$PATH
#CATALINA_HOME is the location of the bin files of Tomcat
export CATALINA_HOME=/usr/local/tomcat
#CATALINA_BASE is the location of the configuration files of this instance of Tomcat
export CATALINA_BASE=$CATALINA_HOME
#TOMCAT_USER is the default user of tomcat
export TOMCAT_USER=tomcat
#TOMCAT_USAGE is the message if this script is called without any options
TOMCAT_USAGE="Usage: $0 {\e[00;32mstart\e[00m|\e[00;31mstop\e[00m|\e[00;32mstatus\e[00m|\e[00;31mrestart\e[00m}"
#SHUTDOWN_WAIT is wait time in seconds for java proccess to stop
SHUTDOWN_WAIT=20
tomcat_pid() {
echo `ps -fe | grep $CATALINA_BASE | grep -v grep | awk '{print $2}'`
}
start() {
pid=$(tomcat_pid)
if [ -n "$pid" ]
then
echo -e "\e[00;31mTomcat is already running (pid: $pid)\e[00m"
else
# Start tomcat
echo -e "\e[00;32mStarting tomcat\e[00m"
#ulimit -n 100000
#umask 007
#/bin/su -p -s /bin/sh tomcat
if [ `user_exists $TOMCAT_USER` = "1" ]
then
su $TOMCAT_USER -c $CATALINA_HOME/bin/startup.sh
else
sh $CATALINA_HOME/bin/startup.sh
fi
status
fi
return 0
}
status(){
pid=$(tomcat_pid)
if [ -n "$pid" ]; then echo -e "\e[00;32mTomcat is running with pid: $pid\e[00m"
else echo -e "\e[00;31mTomcat is not running\e[00m"
fi
}
stop() {
pid=$(tomcat_pid)
if [ -n "$pid" ]
then
echo -e "\e[00;31mStoping Tomcat\e[00m"
#/bin/su -p -s /bin/sh tomcat
if [ `user_exists $TOMCAT_USER` = "1" ]
then
su $TOMCAT_USER -c $CATALINA_HOME/bin/shutdown.sh
else
sh $CATALINA_HOME/bin/shutdown.sh
fi
let kwait=$SHUTDOWN_WAIT
count=0;
until [ `ps -p $pid | grep -c $pid` = '0' ] || [ $count -gt $kwait ]
do
echo -n -e "\e[00;31mwaiting for processes to exit\n\e[00m"
sleep 1
let count=$count+1;
done
if [ $count -gt $kwait ]
then
echo -n -e "\e[00;31mkilling processes which didn't stop after $SHUTDOWN_WAIT seconds\n\e[00m"
kill -9 $pid
fi
else
echo -e "\e[00;31mTomcat is not running\e[00m"
fi
return 0
}
user_exists() {
if id -u $1 >/dev/null 2>&1
then
echo "1"
else
echo "0"
fi
}
case $1 in
start)
start
;;
stop)
stop
;;
restart)
stop
start
;;
status)
status
;;
*)
echo -e $TOMCAT_USAGE
;;
esac
exit 0
(3)templates文件
至于templates模板文件中的两个模板文件,就是当tomcat压缩包解压后,在tomcat文件中的两个包,可以去其他安装过tomcat中找一下,复制过来(前提是tomcat版本相同),将文档中的某些值定义成变量,我是将8080和8443定义成变量,也就是全局变量那块,图片所指的变量。
模板文件:
[root@tomcat tomcat]# cat templates/server.xml
<?xml version='1.0' encoding='utf-8'?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- Note: A "Server" is not itself a "Container", so you may not
define subcomponents such as "Valves" at this level.
Documentation at /docs/config/server.html
-->
<Server port="8005" shutdown="SHUTDOWN">
<Listener className="org.apache.catalina.startup.VersionLoggerListener" />
<!-- Security listener. Documentation at /docs/config/listeners.html
<Listener className="org.apache.catalina.security.SecurityListener" />
-->
<!--APR library loader. Documentation at /docs/apr.html -->
<Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
<!-- Prevent memory leaks due to use of particular java/javax APIs-->
<Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
<Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />
<Listener className="org.apache.catalina.core.ThreadLocalLeakPreventionListener" />
<!-- Global JNDI resources
Documentation at /docs/jndi-resources-howto.html
-->
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
</GlobalNamingResources>
<!-- A "Service" is a collection of one or more "Connectors" that share
a single "Container" Note: A "Service" is not itself a "Container",
so you may not define subcomponents such as "Valves" at this level.
Documentation at /docs/config/service.html
-->
<Service name="Catalina">
<!--The connectors can use a shared executor, you can define one or more named thread pools-->
<!--
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
maxThreads="150" minSpareThreads="4"/>
-->
<!-- A "Connector" represents an endpoint by which requests are received
and responses are returned. Documentation at :
Java HTTP Connector: /docs/config/http.html (blocking & non-blocking)
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define a non-SSL/TLS HTTP/1.1 Connector on port 8080
-->
<Connector port="{{ http_port }}" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="{{ https_port }}" />
<!-- A "Connector" using the shared thread pool-->
<!--
<Connector executor="tomcatThreadPool"
port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
-->
<!-- Define a SSL/TLS HTTP/1.1 Connector on port 8443
This connector uses the NIO implementation that requires the JSSE
style configuration. When using the APR/native implementation, the
OpenSSL style configuration is required as described in the APR/native
documentation -->
<!--
<Connector port="8443" protocol="org.apache.coyote.http11.Http11NioProtocol"
maxThreads="150" SSLEnabled="true" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" />
-->
<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
<!-- An Engine represents the entry point (within Catalina) that processes
every request. The Engine implementation for Tomcat stand alone
analyzes the HTTP headers included with the request, and passes them
on to the appropriate Host (virtual host).
Documentation at /docs/config/engine.html -->
<!-- You should set jvmRoute to support load-balancing via AJP ie :
<Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
-->
<Engine name="Catalina" defaultHost="localhost">
<!--For clustering, please take a look at documentation at:
/docs/cluster-howto.html (simple how to)
/docs/config/cluster.html (reference documentation) -->
<!--
<Cluster className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
-->
<!-- Use the LockOutRealm to prevent attempts to guess user passwords
via a brute-force attack -->
<Realm className="org.apache.catalina.realm.LockOutRealm">
<!-- This Realm uses the UserDatabase configured in the global JNDI
resources under the key "UserDatabase". Any edits
that are performed against this UserDatabase are immediately
available for use by the Realm. -->
<Realm className="org.apache.catalina.realm.UserDatabaseRealm"
resourceName="UserDatabase"/>
</Realm>
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
<!-- SingleSignOn valve, share authentication between web applications
Documentation at: /docs/config/valve.html -->
<!--
<Valve className="org.apache.catalina.authenticator.SingleSignOn" />
-->
<!-- Access log processes all example.
Documentation at: /docs/config/valve.html
Note: The pattern used is equivalent to using pattern="common" -->
<Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"
prefix="localhost_access_log" suffix=".txt"
pattern="%h %l %u %t "%r" %s %b" />
</Host>
</Engine>
</Service>
</Server>
[root@tomcat tomcat]# cat templates/tomcat-users.xml
<?xml version='1.0' encoding='utf-8'?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<tomcat-users xmlns="http://tomcat.apache.org/xml"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://tomcat.apache.org/xml tomcat-users.xsd"
version="1.0">
<!--
NOTE: By default, no user is included in the "manager-gui" role required
to operate the "/manager/html" web application. If you wish to use this app,
you must define such a user - the username and password are arbitrary. It is
strongly recommended that you do NOT use one of the users in the commented out
section below since they are intended for use with the examples web
application.
-->
<!--
NOTE: The sample user and role entries below are intended for use with the
examples web application. They are wrapped in a comment and thus are ignored
when reading this file. If you wish to configure these users for use with the
examples web application, do not forget to remove the <!.. ..> that surrounds
them. You will also need to set the passwords to something appropriate.
-->
<!--
<role rolename="tomcat"/>
<role rolename="role1"/>
<user username="tomcat" password="<must-be-changed>" roles="tomcat"/>
<user username="both" password="<must-be-changed>" roles="tomcat,role1"/>
<user username="role1" password="<must-be-changed>" roles="role1"/>
-->
</tomcat-users>
(4)handlers文件
配置handlers
[root@nginx-server tomcat]# cat handlers/main.yaml
- name: Restart_Tomcat
shell: service tomcat restart
- name: wait
wait_for: port={{ http_port }}
3.4.3 安装tomcat
开始安装,进入入口文件work_dir,执行ansible-playbook:
[root@nginx-server work_dir]# ansible-playbook tomcat_install.yaml
3.4.4 部署测试
至此,tomcat部署完成。
4. 总结
总结:其实部署出来不算厉害,从中找到问题并解决才是真正的厉害,最重要的还是原理,不知道原理,全是无稽之谈。本次案例涉及的目录以及文件很多,建议大家好好看看那个树形图,把关联文件想清楚,最终达到举一反三。加油,奥里给!!!