1. 程式人生 > >ansible安裝tomcat8 最終版

ansible安裝tomcat8 最終版

ansible

假如你要在一臺機器安裝多個tomcat或者安裝多臺tomcat,你可以選擇

假設現在tomcat有三個,分別為cxx,wxx,sxx

  1. 多建立對應的yml文件,一個項目一個

  2. copy.yml,install.yml,delete.yml 分別一個

我選擇第二種方法,變量可以定義在一個文件中


借用ansible生成動態的hosts優勢

#!/usr/bin/python
# coding:utf-8
import sqlite3
import sys

try:
    import json
except ImportError:
    import simplejson as json

def grouplist():
    inventory = {}
    inventory[‘local‘] = [‘127.0.0.1‘]
    sfile=‘/etc/ansible/books.txt‘
    with open(sfile,‘rb‘) as f:
        for i in f.readlines():
            group=i.strip().split()[0]
            name=i.strip().split()[1]
            if not group in inventory:
                inventory[group] = {
                    ‘hosts‘: []
                }
            inventory[group][‘hosts‘].append(name)

        print json.dumps(inventory, indent=4)

    
def hostinfo(name):
    vars = {}
    vars = {
        ‘admin‘: ‘Jane Jolie‘,
        ‘datacenter‘: 1
    }
    print json.dumps(vars, indent=4)

if __name__ == ‘__main__‘:
    if len(sys.argv) == 2 and (sys.argv[1] == ‘--list‘):
        grouplist()
    elif len(sys.argv) == 3 and (sys.argv[1] == ‘--host‘):
        hostinfo(sys.argv[2])
    else:
        print "Usage: %s --list or --host <hostname>" % sys.argv[0]
        sys.exit(1)

這個配置文件,指明端口和分組。cxx就是分組,後面的端口,你懂的。

cat books.txt
cxx 192.168.1.3 sc_tomcat 8005 8080
wxx 192.168.1.3 sc_tomcat 8006 8081
sxx 192.168.1.3 sc_tomcat 8007 8082


先來說ansible部分吧

技術分享

目錄結構

[[email protected] roles]# tree
.
├── copy
│   ├── default
│   ├── files
│   │   └── ROOT
│   │       └── test.html
│   ├── meta
│   │   └── test
│   │       └── test.html
│   └── tasks
│       ├── copy.yml
│       ├── delete.yml
│       ├── install.yml
│       ├── main.bak
│       ├── main.yml
│       ├── main.yml.v1
│       └── main.yml.v2
├── delete
│   ├── default
│   ├── files
│   │   └── ROOT
│   │       └── test.html
│   ├── handlers
│   │   └── main.yml
│   ├── meta
│   │   └── test
│   │       └── test.html
│   ├── tasks
│   │   ├── copy.yml
│   │   ├── delete.yml
│   │   ├── install.yml
│   │   ├── main.bak
│   │   ├── main.yml
│   │   ├── main.yml.v1
│   │   └── main.yml.v2
│   ├── templates
│   │   ├── server.xml
│   │   └── tomcat.sh
│   └── vars
│       └── main.yml
└── install
    ├── default
    ├── files
    │   └── ROOT
    │       └── test.html
    ├── handlers
    │   └── main.yml
    ├── meta
    │   └── test
    │       └── test.html
    ├── tasks
    │   ├── copy.yml
    │   ├── delete.yml
    │   ├── install.yml
    │   ├── main.bak
    │   ├── main.yml
    │   ├── main.yml.v1
    │   └── main.yml.v2
    ├── templates
    │   ├── server.xml
    │   └── tomcat.sh
    └── vars
        └── main.yml

對比以前的變化是

cd /etc/ansible/tomcat/roles
install中的install.yml 文件改變了
cd /etc/ansible/tomcat/roles/install/tasks
[[email protected] tasks]# cat install.yml
- name: pro
  file: path=/opt/apps/{{cxx_pro_dir}} state=directory
- name: tar
  shell: chdir=/opt/ea rm -rf {{cxx_dir}} && cp -r tomcat {{cxx_dir}}
- name: copy server.xml
  template: src=server.xml dest=/opt/ea/{{cxx_dir}}/conf/ force=yes mode=0644
- name: rm webapps
  file: dest=/opt/ea/{{cxx_dir}}/webapps/ state=absent
- name: copy tomcat.sh
  copy: src=/opt/src/tomcat.sh dest=/opt/ea/{{cxx_pro_dir}}.sh owner=tomcat group=tomcat
- name: modify tomcat.sh
  shell: chdir=/opt/ea sed -i ‘s%/ea/tomcat%/ea/{{cxx_dir}}%g‘ {{cxx_pro_dir}}.sh
- name: modify 
  file: path=/opt/ea/{{cxx_dir}}/ owner=tomcat group=tomcat mode=0755
- name: chown
  file: path=/opt/ea/{{cxx_dir}}/ state=directory recurse=yes owner=tomcat group=tomcat
- name: 首次啟動tomcat
  shell: cd /opt/ea && source /etc/profile && sudo -i -u tomcat nohup sh {{cxx_pro_dir}}.sh start &
- name: copy test
  copy: src=/etc/ansible/tomcat/roles/install/meta/test dest=/opt/apps/{{cxx_pro_dir}}/
cd /etc/ansible/tomcat/roles/install/vars  變量文件有大改變
說明cxx_pro_dir 也可以指明wxx_pro_dir,你可以把它當做變量,上面的install.yml引用這個變量而已。
[[email protected] vars]# cat main.yml 
cxx_pro_dir: "{{ cxx_pro_dir }}"
cxx_dir: "{{ cxx_dir }}"
cxx_port1: "{{ cxx_port1 }}"
cxx_port2: "{{ cxx_port2 }}"

ansible部分完結。

因為有好多主機,不想手動書寫ansible執行文件,可以用python腳本自動生成

主要想自動生成這樣的腳本

ansible-playbook -i /etc/ansible/test.py copy.yml --extra-vars "host=192.168.1.3"

ansible-playbook -i /etc/ansible/test.py install.yml --extra-vars "host=192.168.1.3 cxx_pro_dir=cxx cxx_dir=cxx_tomcat cxx_port1=8005 cxx_port2=8080"


以下python腳本,讀取生成的

聲明 什麽cxx都是變量,你可以隨便取名字

# !/usr/bin/env python
# coding:utf-8
#import sqlite3
import sys

try:
    import json
except ImportError:
    import simplejson as json

dfile=‘/etc/ansible/ansible.sh
‘‘‘
cxx 172.29.12.196 sc_tomcat 8005 8080

‘‘‘
def ansiblec(host,cxx_pro_dir=None,cxx_dir=None,cxx_port1=None,cxx_port2=None):
    if cxx_port1==None:
        stringa = ‘ansible-playbook -i /etc/ansible/test.py copy.yml --extra-vars "host=%s"‘ %(host)
        return stringa
    else:
        stringb = ‘ansible-playbook -i /etc/ansible/test.py install.yml --extra-vars "host=%s cxx_pro_dir=%s cxx_dir=%s cxx_port1=%s cxx_port2=%s"‘        %(host,cxx_pro_dir,cxx_dir,cxx_port1,cxx_port2)
        return stringb

def grouplist():
    inventory = {}
    sfile = ‘/etc/ansible/books.txt‘
    with open(sfile, ‘rb‘) as f:
        iplist=[]
        glist=[]
        for i in f.readlines():
            group = i.strip().split()[0]
            grouptomcat=group+"_"+"tomcat"
            name = i.strip().split()[1]
            cxx_port1=i.strip().split()[3]
            cxx_port2=i.strip().split()[4]
            iplist.append(ansiblec(name))
            glist.append(ansiblec(name,group,grouptomcat,cxx_port1,cxx_port2))
            # if not group in inventory:
            #     inventory[group] = {
            #         ‘hosts‘: []
            #     }
            # inventory[group][‘hosts‘].append(name)
        # for ip in inventory.iteritems():
        #     ipt= ip[1][‘hosts‘][0]
        ipset=set(iplist)
        gset=set(glist)
        # print json.dumps(inventory, indent=4)
        with open(dfile,‘wb‘) as f1:
            for i in ipset:
                line = str(i) + "\n"
                f1.write(line)
            for i in gset:
                line = str(i) + "\n"
                f1.write(line)
        f1.close()

def hostinfo(name):
    vars = {}
    vars = {
        ‘admin‘: ‘Jane Jolie‘,
        ‘datacenter‘: 1
    }
    print json.dumps(vars, indent=4)


if __name__ == ‘__main__‘:
    grouplist()


直接執行這個腳本後,自動生成

/etc/ansible/ansible.sh

裏面包含就是

ansible-playbook -i /etc/ansible/test.py copy.yml --extra-vars "host=192.168.1.3"

ansible-playbook -i /etc/ansible/test.py install.yml --extra-vars "host=192.168.1.3 cxx_pro_dir=cxx cxx_dir=cxx_tomcat cxx_port1=8005 cxx_port2=8080"


這樣,通過兩個python腳本,只需要一個配置文件,寫明端口和應用名稱,自動生成創建腳本。


剩余沒有解決的問題

1.root權限,ansible最好不要用root權限

2.context.xml沒有加入到模板裏面去,主要做集群,可以自己添加

3.lib包,比如集群包沒有,主要做session共享的集群包

4.沒有自動啟動腳本,這個需要寫下tomcat的啟動腳本


這是自己個人的想法,比以前快點。

本文出自 “python 運維” 博客,謝絕轉載!

ansible安裝tomcat8 最終版