輕量級集羣管理軟件-Ansible 輕量級集羣管理軟件-ClusterShell

ansible概述和運行機制

ansible概述php

Ansible是一款爲類Unix系統開發的自由開源的配置和自動化工具,  它用Python寫成,相似於saltstack和Puppet,可是有一個不一樣和優勢是咱們不須要在節點中安裝任何客戶端 , 它使用SSH來和節點進行通訊  Ansible基於 Python paramiko 開發,分佈式,無需客戶端,輕量級,配置語法使用 YMAL 及 Jinja2模板語言,更強的遠程命令執行操做html

官方網站 :https://www.ansible.com/node

2015年10月,紅帽(Red Hat)宣佈收購軟件開發公司 Ansible,消息稱這次收購耗資逾 1億美圓,也有消息稱接近 1.5億美圓python

Ansible 成立於 2013年,總部設在北卡羅來納州達勒姆,聯合創始人 aïd Ziouani 和高級副總裁 Todd Barr 都是紅帽的老員工 Ansible 旗下的開源軟件 Ansible 十分流行 ,這家公司還提供 Tower 軟件和諮詢服務,這個款軟件能使開發者輕鬆地創建和管理規模化應用程序的 IT 基礎架構mysql

 

ansiblle具備以下特色:linux

1、部署簡單,只需在主控端部署Ansible環境,被控端無需作任何操做;nginx

2、默認使用SSH協議對設備進行管理;git

3、主從集中化管理;github

4、配置簡單、功能強大、擴展性強;web

5、支持API及自定義模塊,可經過Python輕鬆擴展;

6、經過Playbooks來定製強大的配置、狀態管理

7、對雲計算平臺、大數據都有很好的支持;

 

Ansible 的組成由 5 個部分組成:

Ansible :     ansible核心

Modules :    包括 Ansible 自帶的核心模塊及自定義模塊

Plugins :      完成模塊功能的補充,包括鏈接插件、郵件插件等

Playbooks :   劇本;定義 Ansible 多任務配置文件,由Ansible 自動執行

Inventory :    定義 Ansible 管理主機的清單

 

安裝ansible服務

# 須要epel源
[root@Ansibel ~]# yum -y install ansible
[root@Ansibel ~]# ansible --version
ansible 2.6.3
  config file = /etc/ansible/ansible.cfg
  configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
  ansible python module location = /usr/lib/python2.7/site-packages/ansible
  executable location = /usr/bin/ansible
  python version = 2.7.5 (default, Jul 13 2018, 13:06:57) [GCC 4.8.5 20150623 (Red Hat 4.8.5-28)]

ansible命令參數

anisble命令語法: ansible [-i 主機文件] [-f 批次] [組名] [-m 模塊名稱] [-a 模塊參數]

ansible詳細參數:

 -v,–verbose           #  詳細模式,若是命令執行成功,輸出詳細的結果 (-vv -vvv -vvvv)

 -i PATH, -inventory=PATH      #  指定 host 文件的路徑,默認是在 /etc/ansible/hosts

 -f NUM,-forks=NUM         # NUM 是指定一個整數,默認是 5 ,指定 fork 開啓同步進程的個數。

 -m NAME,-module-name=NAME    #   指定使用的 module 名稱,默認使用 command模塊

 -a,MODULE_ARGS         # 指定 module 模塊的參數

 -k,-ask-pass                 # 提示輸入 ssh 的密碼,而不是使用基於 ssh 的密鑰認證

 -s, sudo                  # 指定使用 sudo 得到 root 權限

 -K,-ask-sudo-pass               # 提示輸入 sudo 密碼,與 -sudo 一塊兒使用

 -u USERNAME,-user=USERNAME          # 指定移動端的執行用戶

 -C,–check                 # 測試此命令執行會改變什麼內容,不會真正的去執行

ansible-doc詳細參數:

ansible-doc -l             # 列出全部的模塊列表

ansible-doc -s 模塊名    # 查看指定模塊的參數 

定義主機清單

基於端口,用戶,密碼定義主機清單

ansible基於ssh鏈接-i (inventory)參數後指定的遠程主機時,也能夠寫端口,用戶,密碼。

格式:ansible_ssh_port:指定ssh端口   ansible_ssh_user:指定 ssh 用戶 ansible_ssh_pass:指定 ssh 用戶登陸是認證密碼(明文密碼不安全)  ansible_sudo_pass:指明 sudo 時候的密碼

/etc/ansible/hosts 文件維護着Ansible中服務器的清單

[root@Ansibel ~]# vim /etc/ansible/hosts 
[web-servers]  # 主機組名
192.168.94.22 ansible_ssh_port=2222 ansible_ssh_user=damowang ansible_ssh_pass=475541270 ansible_ssh_pass=475541270
192.168.94.33 ansible_ssh_port=22 ansible_ssh_user=root ansible_ssh_pass=475541270   
# 測試連通性
[root@Ansibel ~]# ansible -i /etc/ansible/hosts web-servers -m ping
192.168.94.33 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.94.22 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

   -i    #  指定 host 文件的路徑,默認是在 /etc/ansible/hosts 定義的主機清單寫在該文件下 , 那麼能夠不加 -i

 -m    #   指定使用的ping模塊
# 若是報錯 那麼能夠手動ssh到報錯主機 , 緣由是須要創建一個fingerprint(指紋) 須要交互 手動輸入yes便可

由於明文密碼並不安全 , 因此能夠生成祕鑰對在對下面管理的節點批量分發公鑰

生成和批量分發 這裏就再也不重述了  在 <輕量級集羣管理軟件-ClusterShell> 中有講

這裏直接修改主機清單文件 把配置項裏的密碼部分刪除

[root@Ansibel ~]# vim /etc/ansible/hosts 
[web-servers]
192.168.94.22 ansible_ssh_port=2222 ansible_ssh_user=damowang 
192.168.94.33 ansible_ssh_port=22 ansible_ssh_user=root

[root@Ansibel ~]# ansible -m command -a whoami web-servers
192.168.94.22 | SUCCESS | rc=0 >>
damowang

192.168.94.33 | SUCCESS | rc=0 >>
root

爲節點建立用戶

[root@Ansibel ~]# ansible -m user -s -a 'name=mingming shell=/bin/bash home=/home/mingming state=present' web-servers
192.168.94.33 | SUCCESS => {
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 1000, 
    "home": "/home/mingming", 
    "name": "mingming", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 1000
}
192.168.94.22 | SUCCESS => {
    "changed": true, 
    "comment": "", 
    "create_home": true, 
    "group": 1001, 
    "home": "/home/mingming", 
    "name": "mingming", 
    "shell": "/bin/bash", 
    "state": "present", 
    "system": false, 
    "uid": 1001
}

 

爲用戶設置密碼

安裝 passlib 要求系統 python 版本在2.7以上

[root@Ansibel ~]# pip install passlib
-bash: pip: 未找到命令
[root@Ansibel ~]# yum -y install python-pip
[root@Ansibel ~]# pip install passlib
安裝完 passlib 後,生成加密的密碼
python 3.x 版本(sha512 加密算法):
[root@Ansibel ~]# python -c 'from  passlib.hash  import sha512_crypt;  import  getpass;  print (sha512_crypt.encrypt(getpass.getpass()))'
Password: 
$6$rounds=656000$G5MXmLZ0J0e1ppzM$V4MGqttDX9LFB5FJPbhV4vqIz0KIzTbrUkx05QLG1mdbDH0e.rVQveAGCVNXiulrkWO/42Z68DVaeNRN3q4oH.
# 在Password 後輸入咱們的密碼而後再按enter 鍵,就會生成通過加密的密碼了
python 3.x 版本(普通加密算法):
[root@Ansibel ~]# python -c 'import crypt; print (crypt.crypt("475541270","apple"))'
apAM.814qQtJg

python
2.x 版本(sha512 加密算法): [root@Ansibel ~]# python -c 'from passlib.hash import sha512_crypt; import getpass; print (sha512_crypt.encrypt(getpass.getpass()))' Password: $6$rounds=656000$G5MXmLZ0J0e1ppzM$V4MGqttDX9LFB5FJPbhV4vqIz0KIzTbrUkx05QLG1mdbDH0e.rVQveAGCVNXiulrkWO/42Z68DVaeNRN3q4oH. python 2.x 版本(普通加密算法): [root@Ansibel ~]# python -c 'import crypt; print (crypt.crypt("475541270","apple"))' apAM.814qQtJg # 其實python3.x 和 python2.x 版本的區別不大,只是加密算法是用 sha512 仍是用普通算法的區別而已

爲新建立的用戶設置密碼

[root@Ansibel ~]# ansible -m user -s -a 'name=mingming password=apAM.814qQtJg update_password=always' web-servers
192.168.94.33 | SUCCESS => {
    "append": false, 
    "changed": true, 
    "comment": "", 
    "group": 1000, 
    "home": "/home/mingming", 
    "move_home": false, 
    "name": "mingming", 
    "password": "NOT_LOGGING_PASSWORD", 
    "shell": "/bin/bash", 
    "state": "present", 
    "uid": 1000
}
192.168.94.22 | SUCCESS => {
    "append": false, 
    "changed": true, 
    "comment": "", 
    "group": 1001, 
    "home": "/home/mingming", 
    "move_home": false, 
    "name": "mingming", 
    "password": "NOT_LOGGING_PASSWORD", 
    "shell": "/bin/bash", 
    "state": "present", 
    "uid": 1001
}

df命令在全部節點執行後,重定向輸出到本機的/tmp/command-output.txt文件中

[root@Ansibel ~]# ansible -m command -a 'df -Th' web-servers > /tmp/command-output.txt
[root@Ansibel ~]# cat /tmp/command-output.txt
192.168.94.33 | SUCCESS | rc=0 >>
文件系統                類型      容量  已用  可用 已用% 掛載點
/dev/mapper/centos-root xfs        17G  2.4G   15G   14% /
devtmpfs                devtmpfs  476M     0  476M    0% /dev
tmpfs                   tmpfs     488M     0  488M    0% /dev/shm
tmpfs                   tmpfs     488M  7.7M  480M    2% /run
tmpfs                   tmpfs     488M     0  488M    0% /sys/fs/cgroup
/dev/sda1               xfs      1014M  130M  885M   13% /boot
tmpfs                   tmpfs      98M     0   98M    0% /run/user/0
192.168.94.22 | SUCCESS | rc=0 >>
文件系統                類型      容量  已用  可用 已用% 掛載點
/dev/mapper/centos-root xfs        17G  2.4G   15G   14% /
devtmpfs                devtmpfs  476M     0  476M    0% /dev
tmpfs                   tmpfs     488M     0  488M    0% /dev/shm
tmpfs                   tmpfs     488M  7.8M  480M    2% /run
tmpfs                   tmpfs     488M     0  488M    0% /sys/fs/cgroup
/dev/sda1               xfs      1014M  130M  885M   13% /boot
tmpfs                   tmpfs      98M     0   98M    0% /run/user/0
tmpfs                   tmpfs      98M     0   98M    0% /run/user/1000

ansible常見模塊高級使用方法

3個遠程命令模塊的區別

(1)、command模塊爲ansible默認模塊,不指定-m參數時,使用的就是command模塊; comand模塊比較簡單,常見的命令均可以使用,但其命令的執行不是經過shell執行的,因此,像這些 "<", ">", "|", and "&"操做都不能夠,固然,也就不支持管道; 缺點:不支持管道,無法批量執行命令;

(2)、shell模塊:使用shell模塊,在遠程命令經過/bin/sh來執行;因此,咱們在終端輸入的各類命令方式,均可以使用

3)、scripts模塊 :若是在遠程待執行的語句比較多,可寫成一個腳本,經過copy模塊傳到遠端,而後再執行;但這樣就又涉及到兩次ansible調用;對於這種需求,ansible已經爲咱們考慮到了,script模塊就是幹這事的;

使用scripts模塊能夠在本地寫一個腳本,在遠程服務器上執行:

[root@Ansibel ~]# vim /etc/ansible/test.sh
#!/bin/bash
date
hostname   
[root@Ansibel ~]# ansible -m script -a '/etc/ansible/test.sh' web-servers
192.168.94.33 | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.94.33 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.94.33 closed."
    ], 
    "stdout": "2018年 09月 09日 星期日 00:15:44 CST\r\nhost2\r\n", 
    "stdout_lines": [
        "2018年 09月 09日 星期日 00:15:44 CST", 
        "host2"
    ]
}
192.168.94.22 | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to 192.168.94.22 closed.\r\n", 
    "stderr_lines": [
        "Shared connection to 192.168.94.22 closed."
    ], 
    "stdout": "2018年 09月 09日 星期日 00:15:44 CST\r\nhost1\r\n", 
    "stdout_lines": [
        "2018年 09月 09日 星期日 00:15:44 CST", 
        "host1"
    ]
}

copy模塊:實現主控端向目標主機拷貝文件,相似scp功能

[root@Ansibel ~]# ansible -m copy -s -a 'src=/etc/hosts dest=/tmp owner=root group=root mode=755' web-servers
192.168.94.33 | SUCCESS => {
    "changed": true, 
    "checksum": "bf651d9270aa5d2f73e1987c1bba58b3a7732e30", 
    "dest": "/tmp/hosts", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "da3395b279a7cd7a1187ae82acb24b2d", 
    "mode": "0755", 
    "owner": "root", 
    "size": 225, 
    "src": "/root/.ansible/tmp/ansible-tmp-1536423509.88-40213567242184/source", 
    "state": "file", 
    "uid": 0
}
192.168.94.22 | SUCCESS => {
    "changed": true, 
    "checksum": "bf651d9270aa5d2f73e1987c1bba58b3a7732e30", 
    "dest": "/tmp/hosts", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "da3395b279a7cd7a1187ae82acb24b2d", 
    "mode": "0755", 
    "owner": "root", 
    "size": 225, 
    "src": "/home/damowang/.ansible/tmp/ansible-tmp-1536423509.88-138418725080513/source", 
    "state": "file", 
    "uid": 0
}
[root@Ansibel ~]# ansible -a 'ls -l /tmp/hosts' web-servers
192.168.94.33 | SUCCESS | rc=0 >>
-rwxr-xr-x 1 root root 225 9月   9 00:18 /tmp/hosts

192.168.94.22 | SUCCESS | rc=0 >>
-rwxr-xr-x 1 root root 225 9月   9 00:18 /tmp/hosts

file模塊設置文件屬性

[root@Ansibel ~]# ansible -m file -s -a 'path=/tmp/hosts mode=777' web-servers
192.168.94.33 | SUCCESS => {
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "path": "/tmp/hosts", 
    "size": 225, 
    "state": "file", 
    "uid": 0
}
192.168.94.22 | SUCCESS => {
    "changed": true, 
    "gid": 0, 
    "group": "root", 
    "mode": "0777", 
    "owner": "root", 
    "path": "/tmp/hosts", 
    "size": 225, 
    "state": "file", 
    "uid": 0
}
[root@Ansibel ~]# ansible -a 'ls -l /tmp/hosts' web-servers
192.168.94.33 | SUCCESS | rc=0 >>
-rwxrwxrwx 1 root root 225 9月   9 00:18 /tmp/hosts

192.168.94.22 | SUCCESS | rc=0 >>
-rwxrwxrwx 1 root root 225 9月   9 00:18 /tmp/hosts

stat模塊獲取遠程文件信息

[root@Ansibel ~]# ansible -m stat -a 'path=/tmp/hosts' web-servers
192.168.94.33 | SUCCESS => {
    "changed": false, 
    "stat": {
        "atime": 1536423510.9210756, 
        "attr_flags": "", 
        "attributes": [], 
        "block_size": 4096, 
        "blocks": 8, 
        "charset": "us-ascii", 
        "checksum": "bf651d9270aa5d2f73e1987c1bba58b3a7732e30", 
        "ctime": 1536423695.9194686, 
        "dev": 64768, 
        "device_type": 0, 
        "executable": true, 
        "exists": true, 
        "gid": 0, 
        "gr_name": "root", 
        "inode": 17913070, 
        "isblk": false, 
        "ischr": false, 
        "isdir": false, 
        "isfifo": false, 
        "isgid": false, 
        "islnk": false, 
        "isreg": true, 
        "issock": false, 
        "isuid": false, 
        "mimetype": "text/plain", 
        "mode": "0777", 
        "mtime": 1536423510.5610728, 
        "nlink": 1, 
        "path": "/tmp/hosts", 
        "pw_name": "root", 
        "readable": true, 
        "rgrp": true, 
        "roth": true, 
        "rusr": true, 
        "size": 225, 
        "uid": 0, 
        "version": "18446744072814493691", 
        "wgrp": true, 
        "woth": true, 
        "writeable": true, 
        "wusr": true, 
        "xgrp": true, 
        "xoth": true, 
        "xusr": true
    }
}
192.168.94.22 | SUCCESS => {
    "changed": false, 
    "stat": {
        "atime": 1536423510.943854, 
        "attr_flags": "", 
        "attributes": [], 
        "block_size": 4096, 
        "blocks": 8, 
        "charset": "us-ascii", 
        "checksum": "bf651d9270aa5d2f73e1987c1bba58b3a7732e30", 
        "ctime": 1536423695.9422553, 
        "dev": 64768, 
        "device_type": 0, 
        "executable": true, 
        "exists": true, 
        "gid": 0, 
        "gr_name": "root", 
        "inode": 17916998, 
        "isblk": false, 
        "ischr": false, 
        "isdir": false, 
        "isfifo": false, 
        "isgid": false, 
        "islnk": false, 
        "isreg": true, 
        "issock": false, 
        "isuid": false, 
        "mimetype": "text/plain", 
        "mode": "0777", 
        "mtime": 1536423510.5838513, 
        "nlink": 1, 
        "path": "/tmp/hosts", 
        "pw_name": "root", 
        "readable": true, 
        "rgrp": true, 
        "roth": true, 
        "rusr": true, 
        "size": 225, 
        "uid": 0, 
        "version": "439688826", 
        "wgrp": true, 
        "woth": true, 
        "writeable": true, 
        "wusr": true, 
        "xgrp": true, 
        "xoth": true, 
        "xusr": true
    }
}

get_url模塊實現遠程主機下載指定url到本地,支持sha256sum文件校驗

[root@Ansibel ~]# ansible -m get_url -a 'url=https://mirrors.aliyun.com/epel/epel-release-latest-7.noarch.rpm dest=/tmp mode=0440 force=yes' web-servers
192.168.94.33 | SUCCESS => {
    "changed": true, 
    "checksum_dest": null, 
    "checksum_src": "5512b80e5b71f2370d8419fa16a0bc14c5edf854", 
    "dest": "/tmp/epel-release-latest-7.noarch.rpm", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "d512508b8629428e7c3f535cc8012680", 
    "mode": "0440", 
    "msg": "OK (15080 bytes)", 
    "owner": "root", 
    "size": 15080, 
    "src": "/root/.ansible/tmp/ansible-tmp-1536424011.27-144130983589743/tmpJs0QN9", 
    "state": "file", 
    "status_code": 200, 
    "uid": 0, 
    "url": "https://mirrors.aliyun.com/epel/epel-release-latest-7.noarch.rpm"
}
192.168.94.22 | SUCCESS => {
    "changed": true, 
    "checksum_dest": null, 
    "checksum_src": "5512b80e5b71f2370d8419fa16a0bc14c5edf854", 
    "dest": "/tmp/epel-release-latest-7.noarch.rpm", 
    "gid": 1000, 
    "group": "damowang", 
    "md5sum": "d512508b8629428e7c3f535cc8012680", 
    "mode": "0440", 
    "msg": "OK (15080 bytes)", 
    "owner": "damowang", 
    "size": 15080, 
    "src": "/home/damowang/.ansible/tmp/ansible-tmp-1536424011.25-163292980253597/tmpvx9BOK", 
    "state": "file", 
    "status_code": 200, 
    "uid": 1000, 
    "url": "https://mirrors.aliyun.com/epel/epel-release-latest-7.noarch.rpm"
}
#
force=yes,當下載文件時,若是所下的內容和原目錄下的文件內容不同,則替換原文件,若是同樣,就不下載了
若是爲「否」,則僅在目標不存在時才下載文件
通常來講,只有小型本地文件才應該爲「是」 

在0.6以前,該模塊默認爲「是」
url=https://xxx  的等號=先後不能有空格
 

yum模塊linux平臺軟件包管理

yum模塊能夠提供的status狀態: latest ,present,installed 都是表示安裝

removed, absent 表示卸載

爲下面節點安裝apache

ansible -m yum -s -a 'name=httpd state=latest' web-servers
192.168.94.33 | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirrors.aliyun.com\n * extras: mirrors.aliyun.com\n * updates: mirrors.aliyun.com\nResolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-80.el7.centos.1 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package      Arch          Version                        Repository      Size\n================================================================================\nInstalling:\n httpd        x86_64        2.4.6-80.el7.centos.1          updates        2.7 M\n\nTransaction Summary\n================================================================================\nInstall  1 Package\n\nTotal download size: 2.7 M\nInstalled size: 9.4 M\nDownloading packages:\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Installing : httpd-2.4.6-80.el7.centos.1.x86_64                           1/1 \n  Verifying  : httpd-2.4.6-80.el7.centos.1.x86_64                           1/1 \n\nInstalled:\n  httpd.x86_64 0:2.4.6-80.el7.centos.1                                          \n\nComplete!\n"
    ]
}
192.168.94.22 | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror\nLoading mirror speeds from cached hostfile\n * base: mirrors.aliyun.com\n * extras: mirrors.aliyun.com\n * updates: mirrors.aliyun.com\nResolving Dependencies\n--> Running transaction check\n---> Package httpd.x86_64 0:2.4.6-80.el7.centos will be updated\n---> Package httpd.x86_64 0:2.4.6-80.el7.centos.1 will be an update\n--> Processing Dependency: httpd-tools = 2.4.6-80.el7.centos.1 for package: httpd-2.4.6-80.el7.centos.1.x86_64\n--> Running transaction check\n---> Package httpd-tools.x86_64 0:2.4.6-80.el7.centos will be updated\n---> Package httpd-tools.x86_64 0:2.4.6-80.el7.centos.1 will be an update\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package           Arch         Version                     Repository     Size\n================================================================================\nUpdating:\n httpd             x86_64       2.4.6-80.el7.centos.1       updates       2.7 M\nUpdating for dependencies:\n httpd-tools       x86_64       2.4.6-80.el7.centos.1       updates        90 k\n\nTransaction Summary\n================================================================================\nUpgrade  1 Package (+1 Dependent package)\n\nTotal download size: 2.8 M\nDownloading packages:\nDelta RPMs disabled because /usr/bin/applydeltarpm not installed.\n--------------------------------------------------------------------------------\nTotal                                              5.6 MB/s | 2.8 MB  00:00     \nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\n  Updating   : httpd-tools-2.4.6-80.el7.centos.1.x86_64                     1/4 \n  Updating   : httpd-2.4.6-80.el7.centos.1.x86_64                           2/4 \n  Cleanup    : httpd-2.4.6-80.el7.centos.x86_64                             3/4 \n  Cleanup    : httpd-tools-2.4.6-80.el7.centos.x86_64                       4/4 \n  Verifying  : httpd-tools-2.4.6-80.el7.centos.1.x86_64                     1/4 \n  Verifying  : httpd-2.4.6-80.el7.centos.1.x86_64                           2/4 \n  Verifying  : httpd-tools-2.4.6-80.el7.centos.x86_64                       3/4 \n  Verifying  : httpd-2.4.6-80.el7.centos.x86_64                             4/4 \n\nUpdated:\n  httpd.x86_64 0:2.4.6-80.el7.centos.1                                          \n\nDependency Updated:\n  httpd-tools.x86_64 0:2.4.6-80.el7.centos.1                                    \n\nComplete!\n"
    ]
}

cron模塊遠程主機crontab配置

[root@Ansible ~]# ansible -m cron -s -a "name='My Wifi' minute='*/1' job='cat /root/mingming>/var/www/html/index.html'" web-servers
192.168.94.33 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "My Wifi"
    ]
}
192.168.94.22 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "My Wifi"
    ]
}
[root@Ansible ~]# ansible -m shell -s -a  'crontab -l' web-servers
192.168.94.33 | SUCCESS | rc=0 >>
#Ansible: My Wifi
*/1 * * * * cat /root/mingming>/var/www/html/index.html

192.168.94.22 | SUCCESS | rc=0 >>
#Ansible: My Wifi
*/1 * * * * cat /root/mingming>/var/www/html/index.html

service模塊遠程主機系統服務管理(CentOS7 中爲systemd模塊 用法基本同樣)

service模塊經常使用參數:

(1)name參數:此參數用於指定須要操做的服務名稱,好比 nginx,httpd

(2)state參數:此參數用於指定服務的狀態,好比,咱們想要啓動遠程主機中的httpd,則能夠將 state 的值設置爲 started;若是想要中止遠程主機中的服務,則能夠將 state 的值設置爲 stopped

此參數的可用值有 started、stopped、restarted(重啓)、reloaded

enabled參數:此參數用於指定是否將服務設置爲開機 啓動項,設置爲 yes 表示將對應服務設置爲開機啓動,設置爲 no 表示不會開機啓動

想使用service模塊啓動服務,被啓動的服務,必須可使用service 命令啓動或關閉

[root@Ansible ~]# ansible -m systemd -s -a 'name=httpd state=started' web-servers
192.168.94.33 | SUCCESS => {
    "changed": true, 
    "name": "httpd", 
    "state": "started", 
    "status": {
        "ActiveEnterTimestampMonotonic": "0", 
        "ActiveExitTimestampMonotonic": "0", 
        "ActiveState": "inactive", 
        "After": "-.mount basic.target network.target tmp.mount remote-fs.target system.slice systemd-journald.socket nss-lookup.target", 
        "AllowIsolate": "no", 
        "AmbientCapabilities": "0", 
        "AssertResult": "no", 
        "AssertTimestampMonotonic": "0", 
        "Before": "shutdown.target", 
        "BlockIOAccounting": "no", 
        "BlockIOWeight": "18446744073709551615", 
        "CPUAccounting": "no", 
        "CPUQuotaPerSecUSec": "infinity", 
        "CPUSchedulingPolicy": "0", 
        "CPUSchedulingPriority": "0", 
        "CPUSchedulingResetOnFork": "no", 
        "CPUShares": "18446744073709551615", 
        "CanIsolate": "no", 
        "CanReload": "yes", 
        "CanStart": "yes", 
        "CanStop": "yes", 
        "CapabilityBoundingSet": "18446744073709551615", 
        "ConditionResult": "no", 
        "ConditionTimestampMonotonic": "0", 
        "Conflicts": "shutdown.target", 
        "ControlPID": "0", 
        "DefaultDependencies": "yes", 
        "Delegate": "no", 
        "Description": "The Apache HTTP Server", 
        "DevicePolicy": "auto", 
        "Documentation": "man:httpd(8) man:apachectl(8)", 
        "EnvironmentFile": "/etc/sysconfig/httpd (ignore_errors=no)", 
        "ExecMainCode": "0", 
        "ExecMainExitTimestampMonotonic": "0", 
        "ExecMainPID": "0", 
        "ExecMainStartTimestampMonotonic": "0", 
        "ExecMainStatus": "0", 
        "ExecReload": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -k graceful ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "ExecStart": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -DFOREGROUND ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "ExecStop": "{ path=/bin/kill ; argv[]=/bin/kill -WINCH ${MAINPID} ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "FailureAction": "none", 
        "FileDescriptorStoreMax": "0", 
        "FragmentPath": "/usr/lib/systemd/system/httpd.service", 
        "GuessMainPID": "yes", 
        "IOScheduling": "0", 
        "Id": "httpd.service", 
        "IgnoreOnIsolate": "no", 
        "IgnoreOnSnapshot": "no", 
        "IgnoreSIGPIPE": "yes", 
        "InactiveEnterTimestampMonotonic": "0", 
        "InactiveExitTimestampMonotonic": "0", 
        "JobTimeoutAction": "none", 
        "JobTimeoutUSec": "0", 
        "KillMode": "control-group", 
        "KillSignal": "18", 
        "LimitAS": "18446744073709551615", 
        "LimitCORE": "18446744073709551615", 
        "LimitCPU": "18446744073709551615", 
        "LimitDATA": "18446744073709551615", 
        "LimitFSIZE": "18446744073709551615", 
        "LimitLOCKS": "18446744073709551615", 
        "LimitMEMLOCK": "65536", 
        "LimitMSGQUEUE": "819200", 
        "LimitNICE": "0", 
        "LimitNOFILE": "4096", 
        "LimitNPROC": "3802", 
        "LimitRSS": "18446744073709551615", 
        "LimitRTPRIO": "0", 
        "LimitRTTIME": "18446744073709551615", 
        "LimitSIGPENDING": "3802", 
        "LimitSTACK": "18446744073709551615", 
        "LoadState": "loaded", 
        "MainPID": "0", 
        "MemoryAccounting": "no", 
        "MemoryCurrent": "18446744073709551615", 
        "MemoryLimit": "18446744073709551615", 
        "MountFlags": "0", 
        "Names": "httpd.service", 
        "NeedDaemonReload": "no", 
        "Nice": "0", 
        "NoNewPrivileges": "no", 
        "NonBlocking": "no", 
        "NotifyAccess": "main", 
        "OOMScoreAdjust": "0", 
        "OnFailureJobMode": "replace", 
        "PermissionsStartOnly": "no", 
        "PrivateDevices": "no", 
        "PrivateNetwork": "no", 
        "PrivateTmp": "yes", 
        "ProtectHome": "no", 
        "ProtectSystem": "no", 
        "RefuseManualStart": "no", 
        "RefuseManualStop": "no", 
        "RemainAfterExit": "no", 
        "Requires": "-.mount basic.target", 
        "RequiresMountsFor": "/var/tmp", 
        "Restart": "no", 
        "RestartUSec": "100ms", 
        "Result": "success", 
        "RootDirectoryStartOnly": "no", 
        "RuntimeDirectoryMode": "0755", 
        "SameProcessGroup": "no", 
        "SecureBits": "0", 
        "SendSIGHUP": "no", 
        "SendSIGKILL": "yes", 
        "Slice": "system.slice", 
        "StandardError": "inherit", 
        "StandardInput": "null", 
        "StandardOutput": "journal", 
        "StartLimitAction": "none", 
        "StartLimitBurst": "5", 
        "StartLimitInterval": "10000000", 
        "StartupBlockIOWeight": "18446744073709551615", 
        "StartupCPUShares": "18446744073709551615", 
        "StatusErrno": "0", 
        "StopWhenUnneeded": "no", 
        "SubState": "dead", 
        "SyslogLevelPrefix": "yes", 
        "SyslogPriority": "30", 
        "SystemCallErrorNumber": "0", 
        "TTYReset": "no", 
        "TTYVHangup": "no", 
        "TTYVTDisallocate": "no", 
        "TasksAccounting": "no", 
        "TasksCurrent": "18446744073709551615", 
        "TasksMax": "18446744073709551615", 
        "TimeoutStartUSec": "1min 30s", 
        "TimeoutStopUSec": "1min 30s", 
        "TimerSlackNSec": "50000", 
        "Transient": "no", 
        "Type": "notify", 
        "UMask": "0022", 
        "UnitFilePreset": "disabled", 
        "UnitFileState": "disabled", 
        "Wants": "system.slice", 
        "WatchdogTimestampMonotonic": "0", 
        "WatchdogUSec": "0"
    }
}
192.168.94.22 | SUCCESS => {
    "changed": true, 
    "name": "httpd", 
    "state": "started", 
    "status": {
        "ActiveEnterTimestampMonotonic": "0", 
        "ActiveExitTimestampMonotonic": "0", 
        "ActiveState": "inactive", 
        "After": "systemd-journald.socket nss-lookup.target network.target basic.target tmp.mount remote-fs.target system.slice -.mount", 
        "AllowIsolate": "no", 
        "AmbientCapabilities": "0", 
        "AssertResult": "no", 
        "AssertTimestampMonotonic": "0", 
        "Before": "shutdown.target", 
        "BlockIOAccounting": "no", 
        "BlockIOWeight": "18446744073709551615", 
        "CPUAccounting": "no", 
        "CPUQuotaPerSecUSec": "infinity", 
        "CPUSchedulingPolicy": "0", 
        "CPUSchedulingPriority": "0", 
        "CPUSchedulingResetOnFork": "no", 
        "CPUShares": "18446744073709551615", 
        "CanIsolate": "no", 
        "CanReload": "yes", 
        "CanStart": "yes", 
        "CanStop": "yes", 
        "CapabilityBoundingSet": "18446744073709551615", 
        "ConditionResult": "no", 
        "ConditionTimestampMonotonic": "0", 
        "Conflicts": "shutdown.target", 
        "ControlPID": "0", 
        "DefaultDependencies": "yes", 
        "Delegate": "no", 
        "Description": "The Apache HTTP Server", 
        "DevicePolicy": "auto", 
        "Documentation": "man:httpd(8) man:apachectl(8)", 
        "EnvironmentFile": "/etc/sysconfig/httpd (ignore_errors=no)", 
        "ExecMainCode": "0", 
        "ExecMainExitTimestampMonotonic": "0", 
        "ExecMainPID": "0", 
        "ExecMainStartTimestampMonotonic": "0", 
        "ExecMainStatus": "0", 
        "ExecReload": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -k graceful ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "ExecStart": "{ path=/usr/sbin/httpd ; argv[]=/usr/sbin/httpd $OPTIONS -DFOREGROUND ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "ExecStop": "{ path=/bin/kill ; argv[]=/bin/kill -WINCH ${MAINPID} ; ignore_errors=no ; start_time=[n/a] ; stop_time=[n/a] ; pid=0 ; code=(null) ; status=0/0 }", 
        "FailureAction": "none", 
        "FileDescriptorStoreMax": "0", 
        "FragmentPath": "/usr/lib/systemd/system/httpd.service", 
        "GuessMainPID": "yes", 
        "IOScheduling": "0", 
        "Id": "httpd.service", 
        "IgnoreOnIsolate": "no", 
        "IgnoreOnSnapshot": "no", 
        "IgnoreSIGPIPE": "yes", 
        "InactiveEnterTimestampMonotonic": "0", 
        "InactiveExitTimestampMonotonic": "0", 
        "JobTimeoutAction": "none", 
        "JobTimeoutUSec": "0", 
        "KillMode": "control-group", 
        "KillSignal": "18", 
        "LimitAS": "18446744073709551615", 
        "LimitCORE": "18446744073709551615", 
        "LimitCPU": "18446744073709551615", 
        "LimitDATA": "18446744073709551615", 
        "LimitFSIZE": "18446744073709551615", 
        "LimitLOCKS": "18446744073709551615", 
        "LimitMEMLOCK": "65536", 
        "LimitMSGQUEUE": "819200", 
        "LimitNICE": "0", 
        "LimitNOFILE": "4096", 
        "LimitNPROC": "3802", 
        "LimitRSS": "18446744073709551615", 
        "LimitRTPRIO": "0", 
        "LimitRTTIME": "18446744073709551615", 
        "LimitSIGPENDING": "3802", 
        "LimitSTACK": "18446744073709551615", 
        "LoadState": "loaded", 
        "MainPID": "0", 
        "MemoryAccounting": "no", 
        "MemoryCurrent": "18446744073709551615", 
        "MemoryLimit": "18446744073709551615", 
        "MountFlags": "0", 
        "Names": "httpd.service", 
        "NeedDaemonReload": "no", 
        "Nice": "0", 
        "NoNewPrivileges": "no", 
        "NonBlocking": "no", 
        "NotifyAccess": "main", 
        "OOMScoreAdjust": "0", 
        "OnFailureJobMode": "replace", 
        "PermissionsStartOnly": "no", 
        "PrivateDevices": "no", 
        "PrivateNetwork": "no", 
        "PrivateTmp": "yes", 
        "ProtectHome": "no", 
        "ProtectSystem": "no", 
        "RefuseManualStart": "no", 
        "RefuseManualStop": "no", 
        "RemainAfterExit": "no", 
        "Requires": "-.mount basic.target", 
        "RequiresMountsFor": "/var/tmp", 
        "Restart": "no", 
        "RestartUSec": "100ms", 
        "Result": "success", 
        "RootDirectoryStartOnly": "no", 
        "RuntimeDirectoryMode": "0755", 
        "SameProcessGroup": "no", 
        "SecureBits": "0", 
        "SendSIGHUP": "no", 
        "SendSIGKILL": "yes", 
        "Slice": "system.slice", 
        "StandardError": "inherit", 
        "StandardInput": "null", 
        "StandardOutput": "journal", 
        "StartLimitAction": "none", 
        "StartLimitBurst": "5", 
        "StartLimitInterval": "10000000", 
        "StartupBlockIOWeight": "18446744073709551615", 
        "StartupCPUShares": "18446744073709551615", 
        "StatusErrno": "0", 
        "StopWhenUnneeded": "no", 
        "SubState": "dead", 
        "SyslogLevelPrefix": "yes", 
        "SyslogPriority": "30", 
        "SystemCallErrorNumber": "0", 
        "TTYReset": "no", 
        "TTYVHangup": "no", 
        "TTYVTDisallocate": "no", 
        "TasksAccounting": "no", 
        "TasksCurrent": "18446744073709551615", 
        "TasksMax": "18446744073709551615", 
        "TimeoutStartUSec": "1min 30s", 
        "TimeoutStopUSec": "1min 30s", 
        "TimerSlackNSec": "50000", 
        "Transient": "no", 
        "Type": "notify", 
        "UMask": "0022", 
        "UnitFilePreset": "disabled", 
        "UnitFileState": "disabled", 
        "Wants": "system.slice", 
        "WatchdogTimestampMonotonic": "0", 
        "WatchdogUSec": "0"
    }
}

訪問節點web頁面

sysctl模塊遠程主機sysctl配置

# 開啓路由轉發功能
[root@Ansible ~]# ansible -m sysctl -s -a 'name=net.ipv4.ip_forward value=1 reload=yes' web-servers
192.168.94.33 | SUCCESS => {
    "changed": true
}
192.168.94.22 | SUCCESS => {
    "changed": true
}
[root@Ansible ~]# ansible -m shell -a "cat /proc/sys/net/ipv4/ip_forward" web-servers
192.168.94.33 | SUCCESS | rc=0 >>
1

192.168.94.22 | SUCCESS | rc=0 >>
1

Playbook是一個不一樣於使用ansible命令行執行方式的模式,功能更強大更靈活

playbooks使用步驟:

1、在playbooks 中定義任務:

- name: task description     #任務描述信息

 module_name: module_args    #須要使用的模塊名字:  模塊參數

2、ansible-playbook 執行 命令:

[root@Ansible ~]# ansible-playbook LAMP.yml

playbook是由一個或多個"play"組成的列表

play的主要功能在於將事先歸爲一組的主機裝扮成事先經過ansible中的task定義好的角色

github上提供了大量的實例供你們參考  https://github.com/ansible/ansible-examples

 

使用Playbook批量部署多臺LAMP環境

Playbook經常使用文件夾做用: 

files:存放須要同步到異地服務器的源碼文件及配置文件; 

handlers:當服務的配置文件發生變化時須要進行的操做,好比:重啓服務,從新加載配置文件; 

meta:角色定義,可留空;    

tasks:須要進行的執行的任務; 

templates:用於執行lamp安裝的模板文件,通常爲腳本;   

vars:本次安裝定義的變量

咱們能夠在ansible服務器上安裝LAMP環境,而後,再將配置文件經過ansible拷貝到遠程主機上

[root@Ansible ~]# yum -y install httpd mariadb mariadb-server php php-mysql
[root@Ansible ~]# mkdir -p  /mydata/data
[root@Ansible ~]# chown -R mysql:mysql /mydata/
[root@Ansible ~]# vim /etc/my.cnf
# 修改成 datadir=/mydata/data
[root@Ansible ~]# systemctl start mariadb
[root@Ansible ~]# echo "<?php phpinfo(); ?>" > /var/www/html/index.php 
[root@Ansible ~]# systemctl start httpd

訪問測試頁面 確認MySQL已經被整合進來再進行下一步

使用playbook建立一個LAMP構建的任務

建立相關文件

[root@Ansible ~]# mkdir -pv /etc/ansible/lamp/roles/{prepare,httpd,mysql,php}/{tasks,files,templates,vars,meta,default,handlers}
mkdir: 已建立目錄 "/etc/ansible/lamp"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/prepare"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/prepare/tasks"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/prepare/files"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/prepare/templates"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/prepare/vars"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/prepare/meta"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/prepare/default"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/prepare/handlers"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/httpd"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/httpd/tasks"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/httpd/files"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/httpd/templates"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/httpd/vars"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/httpd/meta"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/httpd/default"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/httpd/handlers"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/mysql"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/mysql/tasks"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/mysql/files"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/mysql/templates"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/mysql/vars"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/mysql/meta"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/mysql/default"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/mysql/handlers"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/php"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/php/tasks"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/php/files"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/php/templates"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/php/vars"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/php/meta"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/php/default"
mkdir: 已建立目錄 "/etc/ansible/lamp/roles/php/handlers"

咱們將上面搭建成功的LAMP環境的httpd和MySQL的配置文件拷貝到對應目錄下

[root@Ansible ~]# cd /etc/ansible/ 
[root@Ansible ansible]# cp /etc/httpd/conf/httpd.conf lamp/roles/httpd/files/
[root@Ansible ansible]# cp /etc/my.cnf lamp/roles/mysql/files/

prepare(前期準備)角色的playbooks

[root@Ansible ansible]# vim lamp/roles/prepare/tasks/main.yml
- name: delete yum config
  shell: rm -rf /etc/yum.repos.d/*  #刪除原有的yum配置文件
- name: provide yumrepo file
  shell: wget -O /etc/yum.repos.d/CentOS-Base.repo http://mirrors.aliyun.com/repo/Centos-7.repo   #下載新的yum配置文件
- name: clean the yum repo
  shell: yum clean all    #清除原有的yum緩存信息
- name: clean the iptables
  shell: iptables -F    #清除原有防火牆規則,否則後可能上不了網

構建httpd的任務

[root@Ansible ansible]# cd /etc/ansible/lamp/roles
[root@Ansible roles]# mv /var/www/html/index.php httpd/files/
[root@Ansible roles]#  vim httpd/tasks/main.yml
- name: web server install
  yum: name=httpd state=present    #安裝httpd服務
- name: provide test page
  copy: src=index.php dest=/var/www/html    #提供測試頁
- name: delete apache config
  shell: rm -rf  /etc/httpd/conf/httpd.conf  #刪除原有的apache配置文件,若是不刪除,下面的copy任務是不會執行的,由於當源文件httpd.conf和目標文件同樣時,copy命令是不執行的。若是copy命令不執行,那麼notify將不調用handler
- name: provide configuration file
  copy: src=httpd.conf dest=/etc/httpd/conf/httpd.conf    #提供httpd的配置文件
  notify: restart httpd   #當前面的copy複製成功後,經過notify通知名字爲restart httpd的handlers運行。

notify: 這個action可用於在每一個play的最後被觸發,這樣能夠避免屢次有改變發生時,每次都執行指定的操做,取而代之,僅在全部的變化發生完成後一次性地執行指定操做

在notify中列出的操做稱爲handler,也即notify中調用handler中定義的操做

---- name: test.yml just for test 

    hosts: testserver 

    vars:   

        region: ap-southeast-1 

    tasks:   

        - name: template configuration

          file      template: src=template.j2 dest=/etc/foo.conf     

    notify:         

        - restart memcached         

        - restart apache 

    handlers:   

          - name: restart memcached     

            service: name=memcached state=restarted   

          - name: restart apache      

            service: name=apache state=restarted

handlers概述:

Handlers 也是一些 task 的列表,經過名字來引用,它們和通常的 task 並無什麼區別

Handlers 是由通知者進行notify, 若是沒有被 notify,handlers 不會執行

無論有多少個通知者進行了notify,等到 play 中的全部 task 執行完成以後,handlers 也只會被執行一次

Handlers 最佳的應用場景是用來重啓服務,或者觸發系統重啓操做.除此之外不多用到了

 

構建httpd的handlers

[root@Ansible roles]# vim httpd/handlers/main.yml
- name: restart httpd
  service: name=httpd enabled=yes state=restarted

部署mariadb數據庫

建立MySQL服務的任務,須要安裝MySQL服務,改變屬主信息,啓動MySQL

[root@Ansible roles]# cd /etc/ansible/lamp/roles
[root@Ansible roles]# vim mysql/tasks/main.yml
- name: install the mysql
  yum: name=mariadb-server state=present    #安裝mysql服務
- name: mkdir date directory
  shell: mkdir -p /mydata/data    #建立掛載點目錄
- name: provide configration file
  copy: src=my.cnf dest=/etc/my.cnf    #提供mysql的配置文件
- name: chage the owner
  shell: chown -R mysql:mysql /mydata/*    #更改屬主和屬組
- name: start mariadb
  service: name=mariadb enabled=yes state=started    #啓動mysql服務

構建PHP的任務

[root@Ansible roles]# vim php/tasks/main.yml
- name: install php
  yum: name=php state=present    #安裝php
- name: install php-mysql
  yum: name=php-mysql state=present    #安裝php與mysql交互的插件

定義整個的任務

[root@Ansible roles]# cd /etc/ansible/lamp/roles
[root@Ansible roles]# vim site.yml 
- name: LAMP build
  remote_user: root
  hosts: web-servers
  roles:
    - prepare
    - mysql
    - php 
    - httpd

全部yml的配置文件中,空格必須嚴格對齊

開始部署

 

[root@Ansible roles]# ansible-playbook -s /etc/ansible/lamp/roles/site.yml 

 

 

 

 

在瀏覽器中訪問這兩臺節點主機 IP/index.php

 

特別注意 : 默認狀況下,首次登錄一臺服務器,系統會提示是否要記住對端的指紋,用ansible也會這樣,這樣會致使須要手工輸入yes或no,ansible 才能夠往下執行。如需避免這種狀況,須要在 /etc/ansible/ansible.cfg 文件中設置 host_key_checking = False

相關文章
相關標籤/搜索