ansible实战(在云计算虚拟机上进行tomcat环境搭建)

一、步骤分析

(1)tomcat安装过程

   1、安装JDK;

   2、创建tomcat用户;

   3、安装tomcat;

   4、配置tomcat,重启等。

(2)如何定义playbook

   1、定义hosts

   2、定义roles

   3、定义vars

   4、编排playbooks

二、部署实战

 创建目录及文件。如下

(1)定义hosts文件:

[root@localhost install_tomcat]# cat hosts
[tomcat-servers]
192.168.142.111
192.168.142.136
[root@localhost install_tomcat]# pwd
/etc/ansible/install_tomcat

(2)定义入口文件site.yml

  

[root@localhost install_tomcat]# cat site.yml
---
# This playbook deploy a Tomcat 6 server .
#
- hosts: tomcat-servers
  remote_user: root


  roles:
    - prepare
    - tomcat

#         #定义主机组,远程执行用户
#         #定义roles,分为准备阶段和安装阶段

(3)定义全局变量 (变量文件名称要和主机组名称相同)

[root@localhost group_vars]# pwd
/etc/ansible/install_tomcat/group_vars
[root@localhost group_vars]# cat tomcat-servers
# 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.142.199  #本机IP地址
dest_path: /root/tomcat          #tomcat与jdk存放的位置
jdk_ver: jdk-6u45-linux-x64.bin
jdk_name: jdk1.6.0_45
tomcat_ver: apache-tomcat-9.0.21

 (4)定义roles

[root@localhost tasks]# pwd
/etc/ansible/install_tomcat/roles/prepare/tasks
[root@localhost tasks]# cat main.yml
---
- name: create download directory
  file: path={{ dest_path }} state=directory
# Download JDK for HTTP Server
- name: Download JDK
  get_url: url=http://{{ http_server_ip }}/software/{{ jdk_ver }} dest={{ dest_path }}

- name: Download Tomcat
  get_url: url=http://{{ http_server_ip }}/software/{{ tomcat_ver }}.tar.gz dest={{ dest_path }}

#     #tomcat安装阶段设置
#     #其中files存放tomcat服务启动脚本,templates模板存放server.xm、tomcat-users.xml、和防火墙配置文件
#     #handless 触发文件
#     #tasks存放任务

 

[root@localhost tasks]# pwd
/etc/ansible/install_tomcat/roles/tomcat/tasks
[root@localhost tasks]# cat main.yml
---

- include: install_jdk.yml
- include: install_tomcat.yml

 

[root@localhost tasks]# pwd
/etc/ansible/install_tomcat/roles/tomcat/tasks
[root@localhost tasks]# cat install_jdk.yml
---
- name: Install JDK 1.6
  command: chdir={{ dest_path }} /bin/sh {{ jdk_ver }}

- name: move jkd to /opt
  command: chdir={{ dest_path }} /bin/mv {{ jdk_name }} /opt creates=/opt/{{ jdk_name }}
[root@localhost tasks]# pwd
/etc/ansible/install_tomcat/roles/tomcat/tasks
[root@localhost tasks]# cat install_tomcat.yml
---

- name: add group "tomcat"
  group: name=tomcat

- name: add user "tomcat"
  user: name=tomcat group=tomcat home=/opt/tomcat createhome=no
  sudo: True

- name: Extract archive Tomcat
  command: chdir={{ dest_path }} /bin/tar xf {{ tomcat_ver }}.tar.gz -C /opt creates=/opt/{{ tomcat_ver }}

- name: Symlink install directory
  file: src=/opt/{{ tomcat_ver }} path=/opt/tomcat state=link

- name: Change ownership of Tomcat installation
  file: path=/opt/tomcat/ owner=tomcat group=tomcat state=directory recurse=yes

- name: Configure Tomcat server
  template: src=server.xml dest=/opt/tomcat/conf/
  notify: restart tomcat

- name: Configure Tomcat users
  template: src=tomcat-users.xml dest=/opt/tomcat/conf/
  notify: restart tomcat

- name: Install Tomcat init script
  copy: src=tomcat-initscript.sh dest=/etc/init.d/tomcat mode=0755

- name: Start Tomcat
  service: name=tomcat state=started enabled=yes

- name: deploy iptables rules
  template: src=iptables-save dest=/etc/sysconfig/iptables
  notify: restart iptables

- name: wait for tomcat to start
  wait_for: port={{ http_port }}

#files脚本文件内容,脚本设置以tomcat用户启动关闭
[root@localhost files]# pwd
/etc/ansible/install_tomcat/roles/tomcat/files
[root@localhost 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=/opt/jdk1.6.0_45

#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=/opt/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

[root@localhost templates]# pwd
/etc/ansible/install_tomcat/roles/tomcat/templates
该目录下三个文件内容相同
[root@localhost templates]# cat server.xml
<?xml version='1.0' encoding='utf-8'?>
<!-- {{ ansible_managed }} -->
<!--
       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">

  <!--APR library loader. Documentation at /docs/apr.html -->
  <Listener className="org.apache.catalina.core.AprLifecycleListener" SSLEngine="on" />
  <!--Initialize Jasper prior to webapps are loaded. Documentation at /docs/jasper-howto.html -->
  <Listener className="org.apache.catalina.core.JasperListener" />
  <!-- Prevent memory leaks due to use of particular java/javax APIs-->
  <Listener className="org.apache.catalina.core.JreMemoryLeakPreventionListener" />
  <!-- JMX Support for the Tomcat server. Documentation at /docs/non-existent.html -->
  <Listener className="org.apache.catalina.mbeans.ServerLifecycleListener" />
  <Listener className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener" />

  <!-- 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 HTTP/1.1 Connector on port 8080
    -->
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    <!-- A "Connector" using the shared thread pool-->
    <!--
             <Connector executor="tomcatThreadPool"
               port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" />
    -->
    <!-- Define a SSL HTTP/1.1 Connector on port 8443
                  This connector uses the JSSE configuration, when using APR, the
         connector should be using the OpenSSL style configuration
         described in the APR documentation -->
    <!--
             <Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
               maxThreads="150" 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"/>
      -->

      <!-- The request dumper valve dumps useful debugging information about
                      the request and response data received and sent by Tomcat.
           Documentation at: /docs/config/valve.html -->
      <!--
                 <Valve className="org.apache.catalina.valves.RequestDumperValve"/>
      -->

      <!-- 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"/>

      <!-- Define the default virtual host
                      Note: XML Schema validation will not work with Xerces 2.2.
       -->
      <Host name="localhost"  appBase="webapps"
            unpackWARs="true" autoDeploy="true"
            xmlValidation="false" xmlNamespaceAware="false">

        <!-- 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 &quot;%r&quot; %s %b" />

      </Host>
    </Engine>
  </Service>
</Server>
<?xml version='1.0' encoding='utf-8'?>
<!-- {{ ansible_managed }} -->

<!--
       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>
<!--
       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.
-->
<!--
       NOTE:  The sample user and role entries below are wrapped in a comment
  and thus are ignored when reading this file. Do not forget to remove
  <!.. ..> that surrounds them.
-->
<user username="{{ admin_username }}" password="{{ admin_password }}" roles="manager-gui" />

<!--
       <role rolename="tomcat"/>
  <role rolename="role1"/>
  <user username="tomcat" password="tomcat" roles="tomcat"/>
  <user username="both" password="tomcat" roles="tomcat,role1"/>
  <user username="role1" password="tomcat" roles="role1"/>
-->
</tomcat-users>
# {{ ansible_managed }}
*filter
:INPUT ACCEPT [0:0]
:FORWARD ACCEPT [0:0]
:OUTPUT ACCEPT [4:512]
-A INPUT -m state --state RELATED,ESTABLISHED -j ACCEPT
-A INPUT -p icmp -j ACCEPT
-A INPUT -i lo -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport 22 -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport {{ http_port }} -j ACCEPT
-A INPUT -p tcp -m state --state NEW -m tcp --dport {{ https_port }} -j ACCEPT
-A INPUT -j REJECT --reject-with icmp-host-prohibited
-A FORWARD -j REJECT --reject-with icmp-host-prohibited
COMMIT

 

[root@localhost handlers]# pwd
/etc/ansible/install_tomcat/roles/tomcat/handlers
[root@localhost handlers]# cat main.yml
---
- name: restart tomcat
  service: name=tomcat state=restarted

- name: restart iptables
  service: name=iptables state=restarted

 三、测试部署

[root@localhost install_tomcat]# ansible-playbook -i hosts site.yml
[root@localhost install_tomcat]# pwd
/etc/ansible/install_tomcat

用ansible命令测试tomcat启动:

[root@localhost install_tomcat]# ansible -i hosts tomcat-servers -m shell -a 'netstat -lnpt | grep 8080'

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值