Ansible常用模塊和高級應用

Ansible常用模塊和高級應用

本節所講內容:
集中化管理平臺Ansible的講解與實戰
ansible自動化環境搭建
用ansible自動化部署apache實戰

Ansible官網:https://www.ansible.com/
Ansible在線文檔:http://docs.ansible.com/ansible/index.html
Ansible中文權威指南:http://www.ansible.com.cn/
Ansibl Playbook分享平臺:https://galaxy.ansible.com/

Ansible 簡介:

​ Ansible是一種集成IT系統的配置管理、應用部署、執行特定任務的開源平臺,是由Cobbler和Func的作者於2012年創立的AnsibleWorks公司名下的項目,於2015年被RedHat收購。
Ansible基於Python語言實現,由Paramiko和PyYAML兩個關鍵模塊構建。

具有如下特點:

  • 部署簡單,只需在主控端部署Ansible環境,被控端無需做任何操作;
  • 默認使用SSH協議對設備進行管理;
  • 主從集中化管理;
  • 配置簡單、功能強大、擴展性強;
  • 支持API及自定義模塊,可通過Python輕鬆擴展;
  • 通過Playbooks來定製強大的配置、狀態管理;
  • 對雲計算平臺、大數據都有很好的支持;

Ansible的架構圖如下:

ansible1

ansible core : ansible 自身核心模塊
host inventory: 主機庫,定義可管控的主機列表
connection plugins: 連接插件,一般默認基於 ssh 協議連接
modules:core modules ( 自帶模塊 ) 、custom modules ( 自定義模塊 )
playbooks :劇本,按照所設定編排的順序執行完成安排任務

​ Ansible與Saltstack和puppet的最大區別是Ansible無需在被控端部署任何客戶端代理,默認直接通過SSH通道進行遠程命令的執行或下發配置;相同點都是具備功能強大、靈活的的系統管理、狀態配置,都使用YAML格式來描述配置,都具有豐富的模板及API。

​ Ansible提供了一個在線的Playbook分享平臺,地址是:https://galaxy.ansible.com/,該平臺匯聚了各類常用功能的角色,找到適合自己的Role(角色)後,只需要運行“ansible-galaxy install 作者id.角色包名稱”就可以安裝到本地。

環境
系統版本:
[root@centos6-130-130 ansible]# ansible --version
ansible 2.5.5

系統版本:CentOS release 6.5 (Final)
服務端: 192.168.10.129
客戶端: 192.168.10.130 192.168.10.131

一.服務端進行安裝ansible 服務:

1.需要進行安裝epel源

```'
[root@centos6-130-130~]# wget http://download.fedoraproject.org/pub/epel/6/i386/epel-release-6-8.noarch.rpm
[root@centos6-130-130~]# ls
anaconda-ks.cfg epel-release-6-8.noarch.rpm install.log install.log.syslog
[root@centos6-130-130~]# rpm -ivh epel-release-6-8.noarch.rpm
warning: epel-release-6-8.noarch.rpm: Header V3 RSA/SHA256 Signature, key ID 0608b895: NOKEY
Preparing... ########################################### [100%]
1:epel-release ########################################### [100%]
生成緩存
[root@centos6-130-130 ~]# yum makecache
[root@centos6-130-130 ~]# yum list | grep ansible
ansible.noarch 2.5.5-1.el6 epel
ansible-doc.noarch 2.5.5-1.el6 epel
ansible-inventory-grapher.noarch 2.4.4-1.el6 epel
ansible-lint.noarch 3.4.21-1.el6 epel
python2-ansible-tower-cli.noarch 3.1.7-1.el6 epel


### 2.部署ansible

安裝ansible
[root@centos6-130-130 ~]# yum install -y ansible
創建應用於存放ansible文件的目錄,這裏存放在
[root@centos6-130-130 ansible]# pwd
/opt/ansible
創建hosts 文件,定義主機羣組
[root@centos6-130-130 ansible]# cat hosts
[web] #主機羣組名稱
192.168.10.131 #IP地址或主機名稱
192.168.10.132


### 3.ansible 通訊加密設置

**Ansible** **使用ssh 協議進行通信,爲了方便進行測試使用,ansible想要進行統一進行部署管理,需要進行免密認證。** 

[root@centos6-130-130 ~]# ssh-keygen -t rsa -P ""
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
Created directory '/root/.ssh'.
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:
db:da:0d:58:23:c1:2a:b6:2f:0b:9d:3d:f6:01:b6:fd [email protected]
The key's randomart image is:
+--[ RSA 2048]----+
| o |
| . . |
| o + S o |
| o + . |
| . + = = o |
| ..o o = o |
| .o. o E . |
+-----------------+
由於最小化安裝 系統,ssh-copy-id 命令是沒有的,需要單獨的進行安裝。
[root@centos6-130-130 ~]# yum -y install openssh-clients
把公鑰發佈到客戶端服務器上,保證服務端能夠正常登陸。
[root@centos6-130-130 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub 192.168.10.131
The authenticity of host '192.168.10.131 (192.168.10.131)' can't be established.
RSA key fingerprint is 13:86:c3:34:61:1c:f4:85:30:e3:8e:81:bd:9a:7b:3e.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.10.131' (RSA) to the list of known hosts.
[email protected]'s password:
Now try logging into the machine, with "ssh '192.168.10.131'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.

[root@centos6-130-130 ~]# ssh-copy-id -i ~/.ssh/id_rsa.pub 192.168.10.132
The authenticity of host '192.168.10.132 (192.168.10.132)' can't be established.
RSA key fingerprint is 13:86:c3:34:61:1c:f4:85:30:e3:8e:81:bd:9a:7b:3e.
Are you sure you want to continue connecting (yes/no)? yes
Warning: Permanently added '192.168.10.132' (RSA) to the list of known hosts.
[email protected]'s password:
Now try logging into the machine, with "ssh '192.168.10.132'", and check in:
.ssh/authorized_keys
to make sure we haven't added extra keys that you weren't expecting.

測試免密登陸:
[root@centos6-130-130 ~]# ssh [email protected]
Last login: Mon Aug 13 08:56:42 2018 from 192.168.10.1
[root@centos6-130-130 ~]# ssh [email protected]
Last login: Mon Aug 13 08:56:48 2018 from 192.168.10.1


### 4.測試機器連通性

[root@centos6-130-130 ansible]# ansible -i hosts web -m ping
192.168.10.131 | SUCCESS => {
"changed": false,
"ping": "pong"
}
192.168.10.132 | SUCCESS => {
"changed": false,
"ping": "pong"
}


### 5.Ansible 語法

ansible -i 指定配置文件名稱 web 指定主機羣組 -m 指定模塊 –a 指定模塊參數
模塊查詢命令
ansible-doc -l 列出所有的模塊列表
ansible-doc -s 查看指定模塊的參數


### 6.Ansible配置文件介紹

[root@centos6-130 ansible]# vim /etc/ansible/ansible.cfg
#inventory = /etc/ansible/hosts #指定主機清單文件
#library = /usr/share/my_modules/ #指定模塊地址
#module_utils = /usr/share/my_module_utils/
#remote_tmp = ~/.ansible/tmp #指定遠程執行的路徑
#local_tmp = ~/.ansible/tmp #ansible 管理節點執行路徑
#plugin_filters_cfg = /etc/ansible/plugin_filters.yml
#forks = 5 # 置默認情況下Ansible最多能有多少個進程同時工作,默認設置最多5個進程並行處理
#poll_interval = 15 #輪詢間隔
#sudo_user = root #sudo默認用戶
#ask_sudo_pass = True #是否需要用戶輸入sudo密碼
#ask_pass = True #是否需要用戶輸入連接密碼
#transport = smart #通信機制.默認 值爲’smart’。如果本地系統支持 ControlPersist技術的話,將會使用(基於OpenSSH)‘ssh’,如果不支持將使用‘paramiko’.其他傳輸選項‘local’,‘chroot’,’jail’等等
#remote_port = 22 #遠程鏈接的端口
#module_lang = C #這是默認模塊和系統之間通信的計算機語言,默認爲’C’語言.
#module_set_locale = False
#timeout = 10 #SSH超時時間
#log_path = /var/log/ansible.log #日誌文件存放路徑
#module_name = command #ansible命令執行默認的模塊
#private_key_file = /path/to/file //私鑰文件存儲位置


---

## 二.Ansible 常用模塊介紹及演示:

### 1.ping 模塊

測試目標主機是否在線

主機如果在線,則回覆pong
[root@centos6-130-130 ansible]# ansible -i hosts web -m ping
192.168.10.131 | SUCCESS => {
"changed": false,
"ping": "pong"
}
192.168.10.132 | SUCCESS => {
"changed": false,
"ping": "pong"
}


### 2.setup模塊

setup模塊,主要用於獲取主機信息,在playbooks裏經常會用到的一個參數gather_facts就與該模塊相關。setup模塊下經常使用的一個參數是filter參數,具體使用示例如下(由於輸出結果較多,這裏只列命令不寫結果):

查看web主機羣組內內存的情況
[root@centos6-130-130 ansible]# ansible -i hosts web -m setup -a 'filter=ansible*mb'
查看web主機羣組內網卡eth0的情況
[root@centos6-130-130 ansible]# ansible -i hosts web -m setup -a 'filter=ansible_eth0'


### 3.file 模塊

file模塊主要用於遠程主機上的文件操作,file模塊包含如下選項:

force:需要在兩種情況下強制創建軟鏈接,一種是源文件不存在但之後會建立的情況下;另一種是目標軟鏈接已存在,需要先取消之前的軟鏈,然後創建新的軟鏈,有兩個選項:yes|no

group:定義文件/目錄的屬組
mode:定義文件/目錄的權限
owner:定義文件/目錄的屬主
path:必選項,定義文件/目錄的路徑
recurse:遞歸的設置文件的屬性,只對目錄有效
src:要被鏈接的源文件的路徑,只應用於state=link的情況
dest:被鏈接到的路徑,只應用於state=link的情況
state: directory:如果目錄不存在,創建目錄
file:即使文件不存在,也不會被創建
link:創建軟鏈接
hard:創建硬鏈接
touch:如果文件不存在,則會創建一個新的文件,如果文件或目錄已存在,則更新其最後修改時間
absent:刪除目錄、文件或者取消鏈接文件


#### 3.1創建文件

[root@centos6-130-130 ansible]# ansible -i hosts web -m file -a 'path=/tmp/bawei.txt state=touch'
192.168.10.131 | SUCCESS => {
"changed": true,
"dest": "/tmp/bawei.txt",
"gid": 0,
"group": "root",
"mode": "0644",
"owner": "root",
"size": 0,
"state": "file",
"uid": 0
}
192.168.10.132 | SUCCESS => {
"changed": true,
"dest": "/tmp/bawei.txt",
"gid": 0,
"group": "root",
"mode": "0644",
"owner": "root",
"size": 0,
"state": "file",
"uid": 0
}


#### 3.2刪除文件

[root@centos6-130-130 ansible]# ansible -i hosts web -m file -a "path=/tmp/yum.log state=absent"
192.168.10.131 | SUCCESS => {
"changed": true,
"path": "/tmp/yum.log",
"state": "absent"
}
192.168.10.132 | SUCCESS => {
"changed": true,
"path": "/tmp/yum.log",
"state": "absent"
}


####3.3 創建一個目錄  所屬用戶 所屬組 以及權限

[root@centos6-130-130 ansible]# ansible -i hosts web -m file -a 'path=/tmp/bawei state=directory owner=root group=root mode=777'
192.168.10.131 | SUCCESS => {
"changed": true,
"gid": 0,
"group": "root",
"mode": "0777",
"owner": "root",
"path": "/tmp/bawei",
"size": 4096,
"state": "directory",
"uid": 0
}
192.168.10.132 | SUCCESS => {
"changed": true,
"gid": 0,
"group": "root",
"mode": "0777",
"owner": "root",
"path": "/tmp/bawei",
"size": 4096,
"state": "directory",
"uid": 0
}


#### 3.4給/etc/hosts文件 創建硬鏈接

[root@centos6-130-130 ansible]# ansible -i hosts web -m file -a "path=/tmp/hardfile state=hard src=/etc/hosts"
192.168.10.131 | SUCCESS => {
"changed": true,
"dest": "/tmp/hardfile",
"gid": 0,
"group": "root",
"mode": "0644",
"owner": "root",
"size": 158,
"src": "/etc/hosts",
"state": "hard",
"uid": 0
}
192.168.10.132 | SUCCESS => {
"changed": true,
"dest": "/tmp/hardfile",
"gid": 0,
"group": "root",
"mode": "0644",
"owner": "root",
"size": 158,
"src": "/etc/hosts",
"state": "hard",
"uid": 0
}


### 4.copy 模塊

backup:在覆蓋之前將原文件備份,備份文件包含時間信息。有兩個選項:yes|no
content:用於替代"src",可以直接設定指定文件的值
dest:必選項。要將源文件複製到的遠程主機的絕對路徑,如果源文件是一個目錄,那麼該路徑也必須是個目錄
directory_mode:遞歸的設定目錄的權限,默認爲系統默認權限
force:如果目標主機包含該文件,但內容不同,如果設置爲yes,則強制覆蓋,如果爲no,則只有當目標主機的目標位置不存在該文件時,才複製。默認爲yes
others:所有的file模塊裏的選項都可以在這裏使用
src:要複製到遠程主機的文件在本地的地址,可以是絕對路徑,也可以是相對路徑。如果路徑是一個目錄,它將遞歸複製。在這種情況下,如果路徑使用"/"來結尾,則只複製目錄裏的內容,如果沒有使用"/"來結尾,則包含目錄在內的整個內容全部複製,類似於rsync。


####4.1 copy /etc/hosts 文件到root 下面並賦予權限及所屬用戶 用戶組

[root@centos6-130-130 ansible]# ansible -i hosts web -m copy -a 'src=/etc/hosts dest=/root/file2 mode=755 owner=root group=root'
192.168.10.131 | SUCCESS => {
"changed": true,
"checksum": "7335999eb54c15c67566186bdfc46f64e0d5a1aa",
"dest": "/root/file2",
"gid": 0,
"group": "root",
"md5sum": "54fb6627dbaa37721048e4549db3224d",
"mode": "0755",
"owner": "root",
"size": 158,
"src": "/root/.ansible/tmp/ansible-tmp-1534132243.73-96320200892462/source",
"state": "file",
"uid": 0
}
192.168.10.132 | SUCCESS =>
"changed": true,
"checksum": "7335999eb54c15c67566186bdfc46f64e0d5a1aa",
"dest": "/root/file2",
"gid": 0,
"group": "root",
"md5sum": "54fb6627dbaa37721048e4549db3224d",
"mode": "0755",
"owner": "root",
"size": 158,
"src": "/root/.ansible/tmp/ansible-tmp-1534132243.75-178891778388558/source",
"state": "file",
"uid": 0
}


### 5.command 模塊

command模塊包含如下選項:
creates:一個文件名,當該文件存在,則該命令不執行
free_form:要執行的Linux指令
chdir:在執行指令之前,先切換到該指定的目錄
removes:一個文件名,當該文件不存在,則該選項不執行
executable:切換shell來執行指令,該執行路徑必須是一個絕對路徑


####5.1查看主機時間

[root@centos6-130-130 ansible]# ansible -i hosts web -m command -a 'date'
192.168.10.132 | SUCCESS | rc=0 >>
2018年 08月 13日 星期一 11:56:10 CST
192.168.10.131 | SUCCESS | rc=0 >>
2018年 08月 13日 星期一 11:56:09 CST


###6.Shell 模塊 shell 支持管道

####6.1查看httpd 進程狀態

[root@centos6-130-130 ansible]# ansible -i hosts web -m shell -a 'ps -ef | grep httpd'
192.168.10.132 | SUCCESS | rc=0 >>
root 2085 2084 0 12:01 pts/1 00:00:00 /bin/sh -c ps -ef | grep httpd
root 2087 2085 0 12:01 pts/1 00:00:00 grep httpd
192.168.10.131 | SUCCESS | rc=0 >>
root 2123 2122 0 12:01 pts/1 00:00:00 /bin/sh -c ps -ef | grep httpd
root 2125 2123 0 12:01 pts/1 00:00:00 grep httpd


### 7.user group 模塊

user模塊:管理用戶的模塊。user模塊是請求的是useradd, userdel, usermod三個指令,goup模塊請求的是groupadd, groupdel, groupmod 三個指令。
模塊參數詳解:
name:指定用戶名
password:設定用戶密碼,password參數需要接受md5加密後的值
state:用戶狀態,默認爲present
present:表示添加用戶
absent:表示刪除用戶
update_password:修改用戶密碼
always:新密碼和舊密碼不同時進行修改
on_create:爲新創建的用戶指定密碼
createhome:創建家目錄
yes:默認項,即創建用戶默認是有家目錄的
no:創建用戶時不創建家目錄
remove:
yes:刪除用戶家目錄,需要指定此參數
no:默認項,刪除用戶時默認不刪除用戶的家目錄
system:
yes:默認創建爲普通用戶,而非系統用戶
如果不指定默認生成的選項有:
home:創建家目錄
shell:創建默認的shell爲/bin/bash
system:默認創建爲普通用戶,而非系統用戶,指定是用yes


#### 7.1 增加ansible用戶 指定用戶 用戶組 及uid

[root@centos6-130-130 ansible]# ansible -i hosts web -m user -a "name=ansible uid=2018 group=ansible state=present"
192.168.10.132 | SUCCESS => {
"changed": true,
"comment": "",
"create_home": true,
"group": 2018,
"home": "/home/ansible",
"name": "ansible",
"shell": "/bin/bash",
"state": "present",
"system": false,
"uid": 2018
}
192.168.10.131 | SUCCESS => {
"changed": true,
"comment": "",
"create_home": true,
"group": 2018,
"home": "/home/ansible",
"name": "ansible",
"shell": "/bin/bash",
"state": "present",
"system": false,
"uid": 2018
}


#### 7.2 使用user 模塊刪除用戶,及家目錄

[root@centos6-130-130 ansible]# ansible -i hosts web -m user -a "name=test state=absent remove=yes"
192.168.10.132 | SUCCESS => {
"changed": true,
"force": false,
"name": "test",
"remove": true,
"state": "absent"
}
192.168.10.131 | SUCCESS => {
"changed": true,
"force": false,
"name": "test",
"remove": true,
"state": "absent"
}


#### 7.3 group模塊

#####7.3.1 增加ansible 組指定gid

root@centos6-130-130 ansible]# ansible -i hosts web -m group -a "name=ansible gid=2018 "
192.168.10.131 | SUCCESS => {
"changed": true,
"gid": 2018,
"name": "ansible",
"state": "present",
"system": false
}
192.168.10.132 | SUCCESS => {
"changed": true,
"gid": 2018,
"name": "ansible",
"state": "present",
"system": false


#####7.3.2 刪除用戶羣組

[root@centos6-130-130 ansible]# ansible -i hosts web -m group -a "name=test state=absent"
192.168.10.132 | SUCCESS => {
"changed": true,
"name": "test",
"state": "absent"
}
192.168.10.131 | SUCCESS => {
"changed": true,
"name": "test",
"state": "absent"
}


### 8.yum 模塊

state:
name:必選的項目
默認值; present
選項值 present/latest/absent 用於描述安裝包最終狀態,present/latest用於安裝包,absent用於remove安裝包


#### 8.1**進行部署安裝openssh-clients** 

[root@centos6-130 ansible]# ansible -i hosts web -m yum -a "state=present name=openssh-clients"


### 9.Script模塊

script 模塊可以幫助我們在遠程主機上執行 ansible 管理主機上的腳本,也就是說,腳本一直存在於 ansible 管理主機本地,不需要手動拷貝到遠程主機後再執行。 學習此模塊之前,請先學習 command 模塊。
chdir參數 : 此參數的作用就是指定一個遠程主機中的目錄,在執行對應的腳本之前,會先進入到 chdir 參數指定的目錄中。
creates參數 :使用此參數指定一個遠程主機中的文件,當指定的文件存在時,就不執行對應腳本,可參考 command 模塊中的解釋。
removes參數 :使用此參數指定一個遠程主機中的文件,當指定的文件不存在時,就不執行對應腳本,可參考 command 模塊中的解釋。


####9.1 執行ansible 管理端的腳本

[root@centos6-130 ansible]# ansible -i hosts web -m script -a "chdir=/tmp /tmp/test.sh"
192.168.10.131 | SUCCESS => {
"changed": true,
"rc": 0,
"stderr": "Shared connection to 192.168.10.131 closed.\r\n",
"stdout": "",
"stdout_lines": []
}
192.168.10.132 | SUCCESS => {
"changed": true,
"rc": 0,
"stderr": "Shared connection to 192.168.10.132 closed.\r\n",
"stdout": "",
"stdout_lines": []
}
192.168.10.130 | SUCCESS => {
"changed": true,
"rc": 0,
"stderr": "Shared connection to 192.168.10.130 closed.\r\n",
"stdout": "",
"stdout_lines": []
}


### 10. server模塊

模塊參數詳解:
enabled:表示設置服務開機是否啓動,取值爲true或者false;enabled=yes
name=:表示要控制哪一個服務
state:
started:表示現在就啓動此服務
stopped:表示現在關閉此服務
restarted:表示重啓此服務
sleep:如果執行了restarted,在stop和start之間沉睡幾秒
runlevel:定義在哪些級別可以自啓動
arguments:表示向命令行傳遞的參數


#### 10.1 啓動httpd 服務

[root@centos6-130 ansible]# ansible -i hosts web -m service -a "name=httpd state=started"
192.168.10.132 | SUCCESS => {
"changed": true,
"name": "httpd",
"state": "started"
}
192.168.10.130 | SUCCESS => {
"changed": true,
"name": "httpd",
"state": "started"
}
192.168.10.131 | SUCCESS => {
"changed": true,
"name": "httpd",
"state": "started"


#### 10.2 使用service模塊重啓httpd並設定開機自啓

[root@centos6-130 ansible]# ansible -i hosts web -m service -a "name=httpd enabled=yes state=restarted"
192.168.10.132 | SUCCESS => {
"changed": true,
"enabled": true,
"name": "httpd",
"state": "started"
}
192.168.10.131 | SUCCESS => {
"changed": true,
"enabled": true,
"name": "httpd",
"state": "started"
}
192.168.10.130 | SUCCESS => {
"changed": true,
"enabled": true,
"name": "httpd",
"state": "started"
}


### 11.cron 模塊

backup:對遠程主機上的原任務計劃內容修改之前做備份
cron_file:如果指定該選項,則用該文件替換遠程主機上的cron.d目錄下的用戶的任務計劃
day:日(1-31,/2,……)
hour:小時(0-23,/2,……)
minute:分鐘(0-59,/2,……)
month:月(1-12,/2,……)
weekday:周(0-7,*,……)
job:要執行的任務,依賴於state=present
name:該任務的描述
special_time:指定什麼時候執行,參數:reboot,yearly,annually,monthly,weekly,daily,hourly
state:確認該任務計劃是創建還是刪除
user:以哪個用戶的身份執行


####11.1 查看計劃任務

[root@centos6-130 ansible]# ansible -i hosts web -m shell -a 'crontab -l'
192.168.10.131 | SUCCESS | rc=0 >>
#Ansible: reboot system

  • 2 * /sbin/reboot
    192.168.10.132 | SUCCESS | rc=0 >>
    #Ansible: reboot system
  • 2 * /sbin/reboot

####11.2 root用戶下 重啓系統計劃任務 每天的兩點進行重啓系統

[root@centos6-130 ansible]# ansible -i hosts web -m cron -a 'name="reboot system" hour=2 user=root job="/sbin/reboot"'
192.168.10.132 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "reboot system"
    ]
}
192.168.10.131 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "reboot system"
    ]
}

11.3 刪除計劃任務 用absent

[root@centos6-130 ansible]#  ansible -i hosts web -m cron -a 'name="reboot system" hour=2 user=root job="/sbin/reboot" state=absent'
192.168.10.131 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": []
}
192.168.10.132 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": []
}

11.4 每10分鐘進行同步一次時間

[root@centos6-130 ansible]# ansible -i hosts web -m cron -a 'name="sync time from ntpserver" minute=*/10 job="/usr/sbin/ntpdate 3.cn.pool.ntp.org"'
192.168.10.132 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "sync time from ntpserver"
    ]
}
192.168.10.131 | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "sync time from ntpserver"
    ]
}

12.synchronize模塊

archive                # 是否採用歸檔模式同步,即以源文件相同屬性同步到目標地址
checksum               # 是否效驗
compress               # 開啓壓縮,默認爲開啓
copy_links             # 同步的時候是否複製連接
delete                 # 刪除源中沒有而目標存在的文件(即以推送方爲主)
dest=                  # 目標地址
dest_port              # 目標接受的端口,ansible配置文件中的 ansible_ssh_port 變量優先級高於該 dest_port 變量
dirs                   # 以非遞歸的方式傳輸目錄
existing_only          # Skip creating new files on receiver.
group                  # Preserve group
links                  # Copy symlinks as symlinks.
mode                   # 模式,rsync 同步的方式 PUSH\PULL,默認都是推送push。如果你在使用拉取pull功能的時候,可以參考如下來實現mode=pull   更改推送模式爲拉取模式
recursive              # 是否遞歸 yes/no
rsync_opts             # 使用rsync 的參數
rsync_path             # 服務的路徑,指定 rsync 命令來在遠程服務器上運行。這個參考rsync命令的--rsync-path參數,--rsync-path=PATH     # 指定遠程服務器上的rsync命令所在路徑信息
rsync_timeout          # 指定 rsync 操作的 IP 超時時間,和rsync命令的 --timeout 參數效果一樣.
set_remote_user        # put user@ for the remote paths. If you have a custom ssh config to define the remote user for
src=\‘#\‘"                  # 源,同步的數據源
times                  # 
--exclude=.Git  忽略同步.git結尾的文件
由於模塊默認啓用了archive參數,該參數默認開啓了recursive, links, perms, times, owner,group和-D參數。如果你將該參數設置爲no,那麼你將停止很多參數,比如會導致如下目的遞歸失敗,導致無法拉取
使用rsync 模塊,系統必須安裝rsync 包,否則無法使用這個模塊

12.1 先進行部署安裝rsync服務

[root@centos6-130-130 ~]# ansible -i hosts  web -a "yum install rsync -y"

12.2 把/tmp 目錄中的test.txt 文件 同步到root 目錄下

[root@centos6-130-130 ansible]# ansible -i hosts  web -m synchronize -a "src=/tmp/test.txt dest=/root/"
192.168.10.132 | SUCCESS => {
    "changed": true, 
    "cmd": "/usr/bin/rsync --delay-updates -F --compress --archive --rsh=/usr/bin/ssh -S none -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null --out-format=<<CHANGED>>%i %n%L /tmp/test.txt 192.168.10.132:/root/", 
    "msg": "<f+++++++++ test.txt\n", 
    "rc": 0, 
    "stdout_lines": [
        "<f+++++++++ test.txt"
    ]
}
192.168.10.131 | SUCCESS => {
    "changed": true, 
    "cmd": "/usr/bin/rsync --delay-updates -F --compress --archive --rsh=/usr/bin/ssh -S none -o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null --out-format=<<CHANGED>>%i %n%L /tmp/test.txt 192.168.10.131:/root/", 
    "msg": "<f+++++++++ test.txt\n", 
    "rc": 0, 
    "stdout_lines": [
        "<f+++++++++ test.txt"
    ]
}

12.3 把tmp 目錄同步到root目錄下tmp目錄中

[root@centos6-130-130 ansible]# ansible -i hosts  web -m synchronize -a "src=/tmp/ dest=/root/tmp"

ansbible


三.ansible --yaml語法

介紹:

​ YAML是一個可讀性高的用來表達資料序列的格式。YAML參考了其他多種語言,包括:XML、C語言、Python、Perl等。

​ YAML不是XML,不過,在開發的這種語言時,YAML的意思其實是:“Yet Another Makup Language”(仍是一種標記語言)

###特點:

  • 可讀性好

  • 和腳本的交互性好
  • 使用實現怨言的數據類型
  • 有一個一致的信息模型
  • 易於實現。
  • 可以基於流來處理。
  • 表達能力強,擴展性好

###YAML語法:

YAML的語法和其他高階語言類似,並且可以簡單表達清單、散列表、標量等數據結構。其結構(structure)通過空格來展示。

序列(sequence):裏的項用“-”來代表,來代表不同元素。
MAP裏的鍵值對,用":"分隔,比如:

name:tom
age:22
gender:Male
spouse:
          name:lili
          age:18
          gender:Female
children:
         - name:tom1
            age:5
            gender:Male
         - name:tom2
           age:5
           gender:Female

一個鍵值對,可以一個鍵值對應一個value,也可以一個鍵值對應另一個鍵值對。
序列,相同的數據類型,元素間用"-"表示一個序列內,元素是鍵值對。
用空格來表示結構關係,不是tab。

###ansible中YAML

在ansible中叫序列爲列表,列表爲序列都可以。他們之間元素用"-"開頭例如:

1 # a list of colors
2 - red
3 - blue
4 - black
dictionary:

字典:通過key:value 進行標識。例如:

1 # tom information
2 name:tom
3 age:22
4 job:it

如上3個鍵值對錶示一個實體,也可以用{}來表示一個實體,也就是說將上面3個鍵值對放在一個{}中來表示一個實體。

1 #tom information
2 1 {name:tom,age:22,job:it}

##四.PlayBook介紹

playbook是由一個或者多個play組成的列表,主要功能是將task定義好的角色歸併爲一組進行統一管理。

playbooks本身組成部分有如下幾份:
hosts: 用於指定操作對象節點,多個節點用逗號分隔
tasks: 用於指定要處理的內容
name:task的名稱,ansible可以把很多task使用playbook編排起來,通過名稱,實際執行的時候可以清楚地看到執行情況

shell: ansible的shell模塊,在前面的實例中我們已經知道command/shell/raw等的區別,所以可以知道這個簡單的例子中使用哪個模塊都能實現這個簡單的功能。

示例:

[root@centos6-130 ansible]# cat hello.playbook 
- hosts: web #主機羣組
  gather_facts: false  #facts不會被收集,這個選項當有需求節省fact收集時比較有用
  tasks:  #運行的動作
    - name:  say hello task  #運行動作的名稱
      shell: echo hello world `date` by `hostname` >/tmp/hello.log  # 所執行的動作語句
[root@centos6-130 ansible]# ansible-playbook hello.playbook 
PLAY [web] ***********************************************************************************
TASK [say hello task] *************************************************************************
changed: [192.168.10.131]
changed: [192.168.10.132]
PLAY RECAP ************************************************************************************
192.168.10.131             : ok=1    changed=1    unreachable=0    failed=0   
192.168.10.132             : ok=1    changed=1    unreachable=0    failed=0  
驗證tmp 下面生成hello.log 文件
[root@centos6-130 ansible]# ansible -i hosts web -m command -a "ls /tmp/"
192.168.10.131 | SUCCESS | rc=0 >>
ansible_8mboRu
hello.log
192.168.10.132 | SUCCESS | rc=0 >>
ansible_vExmQp
hello.log

1. ansible 來部署apache服務

1.1 定義主機羣組hosts文件

[root@centos6-130 ansible]# cat hosts
[web]
192.168.10.131
192.168.10.132

思路:

  • 明確playbook做哪些任務?
  • web組的主機完成下列任務
  • 遠程執行用戶爲root
  • 安裝httpd
  • apache配置文件實現自定義http端口和客戶端連接數
  • 啓動httpd,並設置其開機自啓動

1.2 編輯playbook文件

[root@centos6-130 ansible]# cat  httpd.yml
- hosts: web
  remote_user: root
  tasks:
  - name: install httpd
    yum: name=httpd state=present
  - name: install configure file
    copy: src=/root/httpd.conf dest=/etc/httpd/conf/
  - name: start httpd service
service: name=httpd state=started
注意:這裏的src 指的是ansible 服務器上的文件位置。
[root@centos6-130 ansible]#  grep ^Listen /root/httpd.conf
Listen 808
除了端口,其他的配置文件都是相同的。

1.3 測試playbook

ansible3

1.4 運行playbook

ansible4

####1.5 查看服務啓動時的端口

[root@centos6-130 ansible]# ansible -i hosts  web -m shell -a "ss -tnl| grep :808"
192.168.10.131 | SUCCESS | rc=0 >>
LISTEN     0      128         :::808                     :::*                  
192.168.10.132 | SUCCESS | rc=0 >>
LISTEN     0      128         :::808                     :::*  

###2.Playbook常用的功能:

  • playbook裏面的變量使用

  • playbook裏面的循環

  • Playbook 中的 條件判斷

  • playbook中的handlers

  • playbook中的notify

  • playbook中的roles角色

2.1playbook裏面的變量使用

增加用戶

[root@centos6-130 ansible]# cat  create_user.yml 
---
- name: create_user
  hosts: web
  user: root
  gather_facts: false
  vars:
    - user: "test"
  tasks:
    - name: create user
      user: name="{{ user }}"

查看用戶

[root@centos6-130 ansible]# cat while.yml
---
- hosts: web
  user: root
  tasks:
    - name: change mode for files
      file: path=/tmp/{{ item }} state=touch mode=600
      with_items:
        - 1.txt
        - 2.txt
        - 3.txt
解釋說明:
file模塊可以對文件進行相關的操作,例如創建文件或者更改文件權限等,具體可以查看該模塊的文檔
with_items爲循環的對象,相當於是一個數組或集合,寫在下面的1.txt、2.txt以及3.txt是該集合的元素。而item則表示的是遍歷出來的元素,也就是說item指代的是1.txt、2.txt以及3.txt。
state的值設置爲touch表示如果該文件不存在就進行創建
path表示文件的路徑
mode設置權限

ansible5
查看生成的文件

[root@centos6-130 ansible]# ansible -i hosts web -m command -a "ls  /tmp"
192.168.10.132 | SUCCESS | rc=0 >>
1.txt
2.txt
3.txt
192.168.10.131 | SUCCESS | rc=0 >>
1.txt
2.txt
3.txt

###3.Playbook 中的 條件判斷

我們都知道在腳本中循環和條件判斷是必不可少的語句,所以在playbook裏這兩種語句也是有的,循環我們已經介紹完了,接下來我們通過一個簡單的創建文件的例子演示一下條件判斷語句的使用方式。
我們一般以setup模塊收集到的主機信息,來作爲判斷條件。所以在編寫代碼之前,我們需要先獲取相應的信息,例如我要以ip地址來作爲判斷條件,那麼我就得先從setup裏獲取主機ip的相關信息。

獲取信息查看文件

[root@centos6-130 ansible]# ansible web -m setup
[root@centos6-130 ansible]# cat when.yml 
---
- hosts: web
  user: root
  gather_facts: True
  tasks:
    - name: use when
      shell: touch /tmp/when.txt
      when: ansible_eth0.ipv4.address == "192.168.10.131"

ansible6

結果顯示:192.168.10.132 changed=0 沒有進行改變 when 條件判斷生效。

查看是否創建文件:

[root@centos6-130 ansible]# ansible web -m shell -a 'ls /tmp/when.txt'
192.168.10.132 | FAILED | rc=2 >>
ls: 無法訪問/tmp/when.txt: 沒有那個文件或目錄non-zero return code
192.168.10.131 | SUCCESS | rc=0 >>
/tmp/when.txt

4.playbook中的handlers

handlers: 在發生改變時執行的操作
handlers是另一種的tasks,handlers是另一種的任務列表,handlers中的任務會被tasks中的任務進行調用,但是調用並不意味着就一定會被執行,只有當tasks中的任務真正執行以後(真在的進行實際操作,造成實際的改變),handles中被調用的任務纔會執行,如果tasks中的任務並沒有做出任何的實際操作,那麼handlers 中的任務即使被調用,也不會執行。

配置文件

[root@centos6-130 ansible]# cat handlers.yml
- hosts: web
  remote_user: root
  tasks:
  - name: install redis package
    yum: name=redis state=latest
  - name: install conf file
    copy: src=/root/redis.conf dest=/etc/redis.conf owner=redis group=root mode=644
    tags: instconf
    notify: restart redis service
  - name: start redis service
    service: name=redis state=started
  handlers: 
  - name: restart redis service
service: name=redis state=restarted

注意:/root/redis.conf 是在ansible 服務端,這裏我對redis.conf 端口進行了調整6399

條件式觸發:handler,滿足條件的時候觸發條件
handlers:處理器,配置文件被修改的時候才執行,條件定義在notify
以下命令,表示當配置文件被更改的時候,notify就會觸發handler,實現重啓的操作.注意格式的書寫。

ansible7

###5.playbook中的notify

notify這個action可用於在每個play的最後被觸發,這樣可以避免多次有改變發生時每次都執行指定的操作,取而代之,僅在所有的變化發生完成後一次性地執行指定操作。

###6.playbook中的roles角色

什麼場景會使用roles?
假如我們現在有3個被管理主機,第一個要配置成httpd,第二個要配置成php服務器,第三個要配置成MySQL服務器。我們如何來定義playbook?
第一個play用到第一個主機上,用來構建httpd,第二個play用到第二個主機上,用來構建php,第三個play用到第三個主機上,用來構建MySQL。這些個play定義在playbook中比較麻煩,將來也不利於模塊化調用,不利於多次調。比如說後來又加進來一個主機,這個第4個主機既是httpd服務器,又是php服務器,我們只能寫第4個play,上面寫上安裝httpd和php。這樣playbook中的代碼就重複了。
爲了避免代碼重複,roles能夠實現代碼重複被調用。定義一個角色叫websrvs,第二個角色叫phpappsrvs,第三個角色叫dbsrvs。那麼調用時如下來調用:

創建hosts

[root@centos6-130 ansible]# cat hosts
[mysqld]
192.168.10.130
[httpd]
192.168.10.131
[php]
192.168.10.132

示例:
假設有3臺主機,192.168.10.130主機上安裝MySQL,192.168.10.131上安裝httpd,192.168.10.132上安裝MySQL和httpd。我們建立兩個角色websrvs和dbsrvs,然後應用到這幾個主機上。

6.1創建目錄

[root@centos6-130 ansible]# mkdir -pv ansible_playbooks/roles/{websrvs,dbsrvs}/{tasks,files,templates,meta,handlers,vars}
mkdir: 已創建目錄 "ansible_playbooks"
mkdir: 已創建目錄 "ansible_playbooks/roles"
mkdir: 已創建目錄 "ansible_playbooks/roles/websrvs"
mkdir: 已創建目錄 "ansible_playbooks/roles/websrvs/tasks"
mkdir: 已創建目錄 "ansible_playbooks/roles/websrvs/files"
mkdir: 已創建目錄 "ansible_playbooks/roles/websrvs/templates"
mkdir: 已創建目錄 "ansible_playbooks/roles/websrvs/meta"
mkdir: 已創建目錄 "ansible_playbooks/roles/websrvs/handlers"
mkdir: 已創建目錄 "ansible_playbooks/roles/websrvs/vars"
mkdir: 已創建目錄 "ansible_playbooks/roles/dbsrvs"
mkdir: 已創建目錄 "ansible_playbooks/roles/dbsrvs/tasks"
mkdir: 已創建目錄 "ansible_playbooks/roles/dbsrvs/files"
mkdir: 已創建目錄 "ansible_playbooks/roles/dbsrvs/templates"
mkdir: 已創建目錄 "ansible_playbooks/roles/dbsrvs/meta"
mkdir: 已創建目錄 "ansible_playbooks/roles/dbsrvs/handlers"
mkdir: 已創建目錄 "ansible_playbooks/roles/dbsrvs/vars"

[root@centos6-130 ansible]# tree ansible_playbooks/
ansible_playbooks/
└── roles
    ├── dbsrvs
    │   ├── files
    │   ├── handlers
    │   ├── meta
    │   ├── tasks
    │   ├── templates
    │   └── vars
    └── websrvs
        ├── files
        ├── handlers
        ├── meta
        ├── tasks
        ├── templates
        └── vars

每個role下面有個目錄叫meta,在裏面可以新建文件main.yml,在文件中可以設置該role和其它role之前的關聯關係。

6.2配置角色websrvs

[root@centos6-130 ansible]# cd ansible_playbooks/roles/
[root@centos6-130 roles]# cd websrvs/
[root@centos6-130 websrvs]# ls
files  handlers  meta  tasks  templates  vars

6.2.1 上傳配置文件

將httpd配置文件上傳到files目錄下,我這裏假設httpd.conf每臺主機都是一樣的,實際上應該用模板,先用一樣的配置文件舉例

[root@centos6-130 websrvs]# cp /etc/httpd/conf/httpd.conf  files/

6.2.2 配置任務tasks列表

[root@centos6-130 websrvs]# cat tasks/main.yml 
- name: install httpd package
  yum: name=httpd
- name: install configuration file
  copy: src=/root/httpd.conf dest=/etc/httpd/conf
  tags:
  - conf
  notify:
  - restart httpd
- name: start httpd
  service: name=httpd state=started

ansible8

於上面的tasks中定義了notify,所以要定義handlers

[root@centos6-130 websrvs]# cat handlers/main.yml 
- name: restart httpd
  service: name=httpd state=restarted

如果需要定義變量,則在vars目錄下創建main.yml文件,在文件中寫入變量,以key:value的形式定義,比如:

[root@centos6-130 websrvs]# cat vars/main.yml 
http_port: 8080

6.3 配置角色dbservs

[root@centos6-130 dbsrvs]# ls
files  handlers  meta  tasks  templates  vars

6.3.1將MySQL配置文件上傳到files目錄下。

[root@centos6-130 files]# ls
my.cnf
[root@centos6-130 files]# pwd
/etc/ansible/ansible_playbooks/roles/dbsrvs/files

6.3.2 編寫任務列表tasks

[root@centos6-130 dbsrvs]# cat tasks/main.yml 
- name: install mysql-server package
  yum:
      name: "{{item}}"
      state: present
  with_items:
  - mysql
  - mysql-server
  - mysql-libs
- name: install configuration file
  copy: src=/root/my.cnf dest=/etc/my.cnf
  tags:
  - conf
  notify:
  - restart mysqld
- name:
  service: name=mysqld enabled=true state=started

6.3.3 定義handlers

[root@centos6-130 dbsrvs]# cat handlers/main.yml 
- name: restart mysqld
  service: name=mysqld state=restarted

6.4 創建playbooks

[root@centos6-130 ansible_playbooks]# cat db.yml 
- hosts: mysqld
  roles:
  - dbsrvs 
[root@centos6-130 ansible_playbooks]# cat web.yml 
- hosts: httpd
  roles:
  - websrvs
[root@centos6-130 ansible_playbooks]# cat site.yml 
- hosts: php
  roles:
  - websrvs
  - dbsrvs

6.5運行進行測試

[root@centos6-130 ansible_playbooks]# ansible-playbook web.yml

ansible9

[root@centos6-130 ansible_playbooks]# ansible-playbook db.yml

ansible10

[root@centos6-130 ansible_playbooks]# ansible-playbook site.yml

ansible11

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章