Ansible 實現批量架構

項目簡介:

公司部署一次大型市場促銷活動,全面衝刺下交易額公司,要求各業務組對年底大促做準備;運維部要求所有業務容量進行三倍的擴容,並搭建出多套環境可以共開發和測試人員做測試;

1、在Centos上安裝控制節點

在Centos6版本的系統上ansible安裝包還未被加入到yum的base源中,需要安裝epel源之後纔可以安裝ansible

[root@ chenc01 ~]# yum -y install epel-release

在Centos7上時,ansible安裝包已經被加入到了yum的base源中,所以可以直接使用yum安裝

[root@ chenc01 ~]# yum -y install ansible

2 、ssh無密碼連接配置

控制節點在和受管節點在通信時是通過openssh建立的,所以控制節點在和受管節點建立通信時肯定需要賬號和密碼的認證!每次執行任務都需要輸入賬號和密碼在使用過程當中是很不方便的!所以我們這裏要建立起控制節點和受管節點的授信配置,通過公鑰認證來實現控制節點和受管節點ssh的無密碼連接!

# 在控制節點操作:
# 生成密鑰對
[root@ chenc01 ~]# ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa): 
Created directory '/root/.ssh'.
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
8d:e5:df:ca:b4:2f:2f:b7:d1:c4:0a:4b:fa:2b:a0:f7 [email protected]
The key's randomart image is:
+--[ RSA 2048]----+
|                 |
|                 |
|          .      |
|         =     . |
|        S o o   o|
|        .  + + + |
|       . .. + + .|
|      . . .+oo.. |
|       . .E.*B+. |
+-----------------+
# 拷貝公鑰到受管節點
[root@ chenc01 ~]# ssh-copy-id  root@IP
The authenticity of host 'IP (IP)' can't be established.
RSA key fingerprint is 9b:57:b9:86:84:90:a4:4b:44:3e:18:9f:8a:29:6f:e5.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added 'IP' (RSA) to the list of known hosts.
root@IP's password: 
Now try logging into the machine, with "ssh 'root@IP'", and check in:

  .ssh/authorized_keys

to make sure we haven't added extra keys that you weren't expecting.

首次拷貝需要再輸入一次密碼纔可以將公鑰複製過去,輸入完畢後以後再連接就不需要輸入賬號密碼了!

3、編輯主機清單文件(Inventory)

我們需要將所有受管節點以主機名或者ip的形式添加的主機清單文件

中括號中的webservers就是定義的組名,下面50臺服務器是這個組的成員主機;

# 編輯主機清單文件
[root@ chenc01 ~]# vim /etc/ansible/hosts
# 我們也可以按如下格式添加主機
[webservers]
192.0.2.[50:100]

4、測試

ansible執行一條任務的語法格式:
ansible  主機/主機組  -m  模塊  -a ‘模塊的參數’
# 我們使用ping模塊ping清單文件中所有節點,查看是否可達
[root@ chenc01 ~]# ansible all -m ping
10.0.0.62 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
10.0.0.63 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

# 當然我們也可以指定組或者主機操作
[root@ chenc01 ~]# ansible webservers -m ping
10.0.0.62 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
10.0.0.63 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

# 我們再來在受管節點執行一條命令,查看受管節點的ip信息
[root@ chenc01 ~]# ansible webservers -a "ifconfig"
10.0.0.62 | SUCCESS | rc=0 >>
1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN 
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
    inet 10.0.0.99/30 brd 10.0.0.99 scope global lo:0
    inet6 ::1/128 scope host 
       valid_lft forever preferred_lft forever
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc pfifo_fast state UP qlen 1000
    link/ether 00:0c:29:4e:13:49 brd ff:ff:ff:ff:ff:ff
    inet 10.0.0.62/24 brd 10.0.0.255 scope global eth0
    inet6 fe80::20c:29ff:fe4e:1349/64 scope link 
       valid_lft forever preferred_lft forever
。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。。

5、Yum安裝Apache

yum模塊用來在CentOS系統上使用yum命令安裝軟件包
選項:
	name: 指定安裝包的名字
	state:latest 安裝最新版  present 默認安裝  installed 安裝  absent 卸載
	removed 卸載
例子:[root@ chenc01 ~]# ansible webservers -m yum -a 'name=httpd state=latest'
10.0.0.62 | SUCCESS => {
    "changed": false, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "All packages providing httpd are up to date", 
        ""
    ]
}
10.0.0.63 | SUCCESS => {
    "changed": false, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "All packages providing httpd are up to date", 
        ""
    ]
}

# service開啓服務器
service模塊用來管理CentOS上的服務的啓動、關閉、重啓和重載
選項:
	name: 服務名字
	state:  started(啓動)  stopped(停止) restarted(重啓)  reloaded(重載)
	enabled: 默認是no,將服務設置爲開機自啓
例子:[root@ chenc01 ~]# ansible webservers -m service -a 'name=httpd state=started enabled=yes'
10.0.0.62 | SUCCESS => {
    "changed": true, 
    "enabled": true, 
    "name": "httpd", 
    "state": "started"
}
10.0.0.63 | SUCCESS => {
    "changed": true, 
    "enabled": true, 
    "name": "httpd", 
    "state": "started"
}

6、Ansible-playbook批量部署Tomcat

1) 構建目錄結構

# 此操作是安裝nginx+mysql+tomcat+db的目錄結構,可以參考一下,不錯~
[root@ chenc01 ~]# mkdir -p /ansible/roles/{nginx,mysql,tomcat,db}/{defaults,files,handlers,meta,tasks,templates,vars}
  • defaults 默認尋找路徑
  • tasks 存放playbooks路徑
  • files 存放文件和腳本包,copy模塊文件搜索路徑
  • templates 模版存放路徑
  • handlers notify調用部分playbook存放路徑
  • vars roles內變量存放路徑

2)文件目錄結構

[root@ chenc01 ~]# tree /ansible/
/ansible/
└── roles
    ├── db
    │   ├── defaults
    │   ├── files
    │   ├── handlers
    │   ├── meta
    │   ├── tasks
    │   ├── templates
    │   └── vars
    ├── mysql
    │   ├── defaults
    │   ├── files
    │   ├── handlers
    │   ├── meta
    │   ├── tasks
    │   ├── templates
    │   └── vars
    ├── nginx
    │   ├── defaults
    │   ├── files
    │   ├── handlers
    │   ├── meta
    │   ├── tasks
    │   ├── templates
    │   └── vars
    └── tomcat
        ├── defaults
        ├── files
        ├── handlers
        ├── meta
        ├── tasks
        ├── templates
        └── vars

33 directories, 0 files

3)使用playbook安裝Tomcat

[root@ chenc01 ~]# cat main.yml
---
- hosts: webservers    # 這裏根據自己的需要修改成要被操作的遠程主機 
  remote_user: root    # 遠程執行命令的用戶名
  tasks:               # 任務列表
#創建用戶
    - name: group
      group: name=tomcat
    - name: user
      user: name=tomcat group=tomcat home=/usr/tomcat
      sudo: True

##############################這個源碼包安裝JDK#############################
# 複製jdk到tmp目錄下
    - name: "複製jdk到tmp目錄下"
      copy: src=/root/jdk-8u131-linux-x64_.rpm dest=/tmp/jdk-8u131-linux-x64_.rpm
# 解壓jdk包到/application
    - name: "解壓jdk包"
      yum:
        name: /tmp/jdk-8u131-linux-x64_.rpm
        state: present
     # command: /bin/rpm -ivh /tmp/jdk-8u131-linux-x64_.rpm -C /application
##########################安裝tomcat###########################################
    - name: "解壓Tomcat"
      copy: src=apache-tomcat-8.5.35.tar.gz dest=/tmp/apache-tomcat-8.5.35.tar.gz
# 解壓tomcat到opt目錄
    - name: "解壓tomcat到opt目錄"
      command: /bin/tar xf /tmp/apache-tomcat-8.5.35.tar.gz -C /opt
# 創建軟連接
    - name: "創建軟連接"
      file: src=/opt/apache-tomcat-8.5.35/ dest=/tmp/tomcat state=link
# 賦予目錄權限
    - name: "賦予目錄權限"
      file: path=/application/tomcat/ owner=tomcat group=tomcat state=directory recurse=yes
# 開啓tomcat
    - name: "開啓tomcat"
      shell: ss -anpt|grep 8080 || nohup /tmp/tomcat/bin/catalina.sh run &
      
[root@ chenc01 ~]# ansible-playbook main.yml --syntax-check  #檢查語法
[root@ chenc01 ~]# ansible-playbook main.yml  #執行

7、Ansible-playbook批量部署MySQL

[root@ chenc01 ~]# mkdir mysql
[root@ chenc01 mysql]# vim mysql.yml 
---
- hosts: webservers
  tasks:
    - name: copy mysql_tar_gz to client
      copy: src=mysql-5.6.35.tar.gz dest=/tmp/mysql-5.6.35.tar.gz
    - name: copy install_script to client
      copy: src=mysql_install.sh dest=/tmp/mysql_install.sh owner=root group=root mode=755
    - name: install mysql
      shell: /bin/bash /tmp/mysql_install.sh

1)創建mysql 安裝腳本

[root@ chenc01 mysql]# cat mysql_install.sh
#!/bin/bash

# 定義mysql數據庫路徑,和mysql登錄密碼
DBDIR='/application/mysql/data'
PASSWD='bingoclo123'

# 判斷數據目錄是否存在如果不存在遞歸創建目錄
[ -d $DBDIR ] || mkdir $DBDIR -p

# 安裝mysql組件
yum install cmake make gcc-c++ bison-devel ncurses-devel -y
id mysql &> /dev/null

# 如果執行id mysql輸出爲0 那麼就是執行正確創建mysql用戶
if [ $? -ne 0 ];then
 useradd mysql -s /sbin/nologin -M
fi

# 賦予數據目錄權限
chown -R mysql.mysql $DBDIR

# 切換到tmp目錄,解壓mysql,編譯安裝mysql到/application/mysql
cd /tmp/
tar xf mysql-5.6.35.tar.gz
cd mysql-5.6.35
cmake . -DCMAKE_INSTALL_PREFIX=/application/mysql \
-DMYSQL_DATADIR=$DBDIR \
-DMYSQL_UNIX_ADDR=$DBDIR/mysql.sock \
-DDEFAULT_CHARSET=utf8 \
-DEXTRA_CHARSETS=all \
-DENABLED_LOCAL_INFILE=1 \
-DWITH_READLINE=1 \
-DDEFAULT_COLLATION=utf8_general_ci \
-DWITH_EMBEDDED_SERVER=1

# 判斷如果以上執行結果不等於0,說明執行失敗,退出!
if [ $? != 0 ];then
 echo "cmake error!"
 exit 1
fi

# 判斷執行成功,繼續往下走
make && make install
if [ $? -ne 0 ];then
 echo "install mysql is failed!" && /bin/false
fi
sleep 2

# 做軟連接
ln -s /application/mysql/bin/* /usr/bin/

# 複製mysql配置文件
cp -f /application/mysql/support-files/my-default.cnf /etc/my.cnf

# 複製mysql啓停腳本到init.d
cp -f /application/mysql/support-files/mysql.server /etc/init.d/mysqld

# 執行權
chmod 700 /etc/init.d/mysqld

# 初始化mysql
/application/mysql/scripts/mysql_install_db  --basedir=/application/mysql --datadir=$DBDIR --user=mysql

# 如果mysql初始化失敗提示install mysql is failed!  否則/etc/init.d/mysqld start
if [ $? -ne 0 ];then
 echo "install mysql is failed!" && /bin/false
fi
/etc/init.d/mysqld start

# 如果mysql開啓失敗提示install mysql is failed! 否則繼續往下走
if [ $? -ne 0 ];then
 echo "install mysql is failed!" && /bin/false
fi

# 開機自啓
chkconfig --add mysqld
chkconfig mysqld on
/application/mysql/bin/mysql -e "update mysql.user set password=password('$PASSWD') where host='localhost' and user=
'root';"
/application/mysql/bin/mysql -e "update mysql.user set password=password('$PASSWD') where host='127.0.0.1' and user=
'root';"
/application/mysql/bin/mysql -e "delete from mysql.user where password='';"
/application/mysql/bin/mysql -e "flush privileges;"
if [ $? -eq 0 ];then
 echo "ins_done"
fi

2)執行ansible 命令

[root@ chenc01 mysql]# ansible-playbook mysql.yml --syntax-check  #檢查語法
[root@ chenc01 mysql]# ansible-playbook mysql.yml  #執行

8、Ansible-playbook批量部署Nginx

# 創建nginx目錄
[root@ chenc01 ~]# mkdir nginx
[root@ chenc01 ~]# cd nginx
# 上傳並解壓nginx包
[root@ chenc01 nginx]# tar zxf nginx-1.12.2.tar.gz 
[root@ chenc01 nginx]# cd nginx-1.12.2
# 把nginx.conf文件複製到root下的nginx裏
[root@ chenc01 nginx-1.12.2]# cp conf/nginx.conf /root/nginx/
[root@ chenc01 nginx-1.12.2]# cd /root/nginx/
[root@ chenc01 nginx]# ls
nginx-1.12.2  nginx-1.12.2.tar.gz  nginx.conf
# 刪除本機解壓的nginx包
[root@ chenc01 nginx]# rm -rf nginx-1.12.2
[root@ chenc01 nginx]# vim nginx.yml
[root@ chenc01 nginx]# cat nginx.yml 
---
- hosts: webservers
  tasks:
     - name: "推送Nginx源碼包"
       unarchive: src=nginx-1.12.2.tar.gz dest=/root/
     - name: "安裝依賴環境庫"
       yum: name=gcc,gcc-c++,pcre-devel,zlib-devel state=latest
     - name: "安裝Nginx"
       shell: cd /root/nginx-1.12.2 && ./configure && make && make install
     - name: "推送配置文件"
       copy: src=nginx.conf dest=/usr/local/nginx/conf/nginx.conf
     - name: "啓動Nginx服務"
       shell: netstat -ntl | grep -qw 80 || /usr/local/nginx/sbin/nginx
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章