1. 程式人生 > >Ansible安裝配置及常用模組簡介

Ansible安裝配置及常用模組簡介

Ansible是一種整合IT系統的配置管理, 應用部署, 執行特定任務的開源平臺。 它基於Python語言實現, 部署只需在主控端部署Ansible環境, 被控端無需安裝代理工具, 只需開啟SSH, 讓主控端通過SSH祕鑰認證對其進行所有的管理監控操作。相對於SaltStack, 它除了利用SSH安全傳輸, 無需在客戶端進行任何配置, 而且它有一個很龐大的使用者群體以及豐富的API, 相對適合部署到數量比較大且對系統軟體安裝要求比較嚴格的叢集中。Ansible可以實現批量系統配置、批量軟體部署、批量檔案拷貝、批量執行命令等功能。

更多配置參考: https://github.com/ansible

 

官方文件: http://docs.ansible.com/ansible

本文介紹ansible的安裝和常用模組使用

安裝環境:centos6.8

管理端IP:內網192.168.9.101 外網192.168.10.133

被管理端:www.lemon.com:內網192.168.9.134 外網192.168.10.137

                 www.orange.com: 內網192.168.9.135 外網192.168.10.138

一、ansible管理端配置SSH金鑰免密登入被管理端

yum install epel-release -y

# yum install ssh* -y

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:
24:13:34:e9:71:2b:20:0b:48:a6:86:9a:1d:1b:1d:26 
[email protected]
The key's randomart image is: +--[ RSA 2048]----+ |ooE o.+. | |* .+..oo. | |oooo.ooo.. | |oo.+ o+. | |o o .S | | | | | | | | | +-----------------+

同步公鑰檔案id_rsa.pub到目標主機

# ssh-copy-id -i /root/.ssh/id_rsa.pub r[email protected]

# ssh-copy-id -i /root/.ssh/id_rsa.pub [email protected]

校驗SSH免密碼配置是否成功.

# ssh [email protected]

如直接進入則配置完成.

二、ansible軟體安裝

1.管理端安裝軟體

yum install ansible -y

2.被管理端安裝軟體

yum install libselinux-python -y

PS:如果關閉selinux,那麼被管理端可以不安裝(建議安裝)

3.管理端配置管理檔案

# vim /etc/ansible/hosts

文字內容修改為如下:

[webservers] #定義一個webservers組,組裡有www.lemon.com和www.orange.com兩臺主機
www.lemon.com
www.orange.com
[host01] #同上解釋
www.lemon.com
[host02] #同上解釋
www.orange.com

三、ansible批量管理

ansible語法示例:

ansible命令語法格式:

ansible  <host-pattern>  [-f forks] [-m module_name]  [-a args]

<host-pattern>
指明管控主機,以模式形式表示或者直接給定IP,必須事先定義在檔案中;all設定所有
 
 [-f forks]
指明每批管控多少主機,預設為5個主機一批次
 
[-m module_name]
使用何種模組管理操作,所有的操作都需要通過模組來指定
 
[-a args]
指明模組專用引數;args一般為key=value格式
注意:command模組的引數非為kv格式,而是直接給出要執行的命令即可;

ansible執行命令後輸出資訊中:

綠色——表示查詢,或者沒有發生任何改變

紅色——表示命令操作出現異常

屎×××——對遠端主機做了相應改動

粉色——對操作提出建議或忠告

四、常用模組介紹

1.command命令模組

command: 執行遠端主機SHELL命令:

[[email protected] ~]# ansible webservers -m command -a "free -m" #執行free -m檢視主機記憶體使用情況
www.lemon.com | SUCCESS | rc=0 >>
             total       used       free     shared    buffers     cached
Mem:           980        276        703          0         16        142
-/+ buffers/cache:        118        861
Swap:         1983          0       1983

www.orange.com | SUCCESS | rc=0 >>
             total       used       free     shared    buffers     cached
Mem:           980        256        724          0         17        118
-/+ buffers/cache:        120        860
Swap:         1983          0       1983
 

用於在各被管理節點執行指定的命令 
shell和command的區別:shell模組可以特殊字元,而command是不支援

2.ping模組

ping:檢查指定節點機器是否還能連通,用法很簡單,不涉及引數,主機如果線上,則回覆pong 

[[email protected] ~]# ansible webservers -m ping #測試主機連通性
www.lemon.com | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
www.orange.com | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

3.copy模組和template模組(用法基本相同)

copy:實現主控端向目標主機拷貝檔案, 類似scp功能

[[email protected] test]# ansible webservers -m copy -a "src=/root/test/test.sh dest=/root/test/ owner=root group=root mode=0755"

#複製管理端一個名為test.sh的檔案到root下的test目錄,所屬者和所屬組都為root 許可權為755
www.orange.com | SUCCESS => {
    "changed": true, 
    "checksum": "234c9b72821d3c9d68f4d1e07a4d36d2849cec26", 
    "dest": "/root/test/test.sh", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "f8096daec345773cbc2b13b86109e54f", 
    "mode": "0755", 
    "owner": "root", 
    "size": 69, 
    "src": "/root/.ansible/tmp/ansible-tmp-1542236024.1-90099218503531/source", 
    "state": "file", 
    "uid": 0
}
www.lemon.com | SUCCESS => {
    "changed": true, 
    "checksum": "234c9b72821d3c9d68f4d1e07a4d36d2849cec26", 
    "dest": "/root/test/test.sh", 
    "gid": 0, 
    "group": "root", 
    "md5sum": "f8096daec345773cbc2b13b86109e54f", 
    "mode": "0755", 
    "owner": "root", 
    "size": 69, 
    "src": "/root/.ansible/tmp/ansible-tmp-1542236024.09-200586221288059/source", 
    "state": "file", 
    "uid": 0
}

template基於模板方式生成一個檔案複製到遠端主機(template使用Jinjia2格式作為檔案模版,進行文件內變數的替換的模組。它的每次使用都會被ansible標記為”changed”狀態。) 
– backup: 如果原目標檔案存在,則先備份目標檔案 
– src:在ansible控制器上的Jinja2格式化模板的路徑。 這可以是相對或絕對的路徑。 
– dest:將模板渲染到遠端機器上的位置。 
force:是否強制覆蓋,預設為yes 
– owner:目標檔案屬主 
– group:目標檔案屬組 
– mode:目標檔案的許可權模式,模式可以被指定為符號模式(例如,u + rwx或u = rw,g = r,o = r)。

4.stat模組

stat:獲取遠端檔案狀態資訊, 包括atime, ctime, mtime, md5, uid, gid等資訊

[[email protected] test]# ansible webservers -m stat -a "path=/root/test/test.sh"    #檢視指令碼檔案資訊                                                
www.orange.com | SUCCESS => {
    "changed": false, 
    "stat": {
        "atime": 1542338028.7207732, 
        "attr_flags": "e", 
        "attributes": [
            "extents"
        ], 
        "block_size": 4096, 
        "blocks": 8, 
        "charset": "us-ascii", 
        "checksum": "234c9b72821d3c9d68f4d1e07a4d36d2849cec26", 
        "ctime": 1542338028.7247732, 
        "dev": 64768, 
        "device_type": 0, 
        "executable": true, 
        "exists": true, 
        "gid": 0, 
        "gr_name": "root", 
        "inode": 786081, 
        "isblk": false, 
        "ischr": false, 
        "isdir": false, 
        "isfifo": false, 
        "isgid": false, 
        "islnk": false, 
        "isreg": true, 
        "issock": false, 
        "isuid": false, 
        "mimetype": "text/x-shellscript", 
        "mode": "0755", 
        "mtime": 1542338028.3807731, 
        "nlink": 1, 
        "path": "/root/test/test.sh", 
        "pw_name": "root", 
        "readable": true, 
        "rgrp": true, 
        "roth": true, 
        "rusr": true, 
        "size": 69, 
        "uid": 0, 
        "version": "1922158357", 
        "wgrp": false, 
        "woth": false, 
        "writeable": true, 
        "wusr": true, 
        "xgrp": true, 
        "xoth": true, 
        "xusr": true
    }
}
www.lemon.com | SUCCESS => {
    "changed": false, 
    "stat": {
        "atime": 1542338028.7619922, 
        "attr_flags": "e", 
        "attributes": [
            "extents"
        ], 
        "block_size": 4096, 
        "blocks": 8, 
        "charset": "us-ascii", 
        "checksum": "234c9b72821d3c9d68f4d1e07a4d36d2849cec26", 
        "ctime": 1542338028.7659922, 
        "dev": 64768, 
        "device_type": 0, 
        "executable": true, 
        "exists": true, 
        "gid": 0, 
        "gr_name": "root", 
        "inode": 785266, 
        "isblk": false, 
        "ischr": false, 
        "isdir": false, 
        "isfifo": false, 
        "isgid": false, 
        "islnk": false, 
        "isreg": true, 
        "issock": false, 
        "isuid": false, 
        "mimetype": "text/x-shellscript", 
        "mode": "0755", 
        "mtime": 1542338028.4139922, 
        "nlink": 1, 
        "path": "/root/test/test.sh", 
        "pw_name": "root", 
        "readable": true, 
        "rgrp": true, 
        "roth": true, 
        "rusr": true, 
        "size": 69, 
        "uid": 0, 
        "version": "934519185", 
        "wgrp": false, 
        "woth": false, 
        "writeable": true, 
        "wusr": true, 
        "xgrp": true, 
        "xoth": true, 
        "xusr": true
    }
}

 5.script模組

script:遠端執行MASTER本地SHELL指令碼.(類似scp+shell)

[[email protected] test]# ansible webservers -m script -a "/root/test/test.sh"   #執行test.sh指令碼,指令碼內容為echo ""this iiiiis a test"                                                       
www.orange.com | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to www.orange.com closed.\r\n", 
    "stderr_lines": [
        "Shared connection to www.orange.com closed."
    ], 
    "stdout": "this iiiiis a test\r\n", 
    "stdout_lines": [
        "this iiiiis a test"
    ]
}
www.lemon.com | SUCCESS => {
    "changed": true, 
    "rc": 0, 
    "stderr": "Shared connection to www.lemon.com closed.\r\n", 
    "stderr_lines": [
        "Shared connection to www.lemon.com closed."
    ], 
    "stdout": "this iiiiis a test\r\n", 
    "stdout_lines": [
        "this iiiiis a test"
    ]
}

6.yum模組

yum:Linux包管理平臺操作,  常見都會有yum和apt, 此處會呼叫yum管理模式

[[email protected] test]# ansible webservers -m yum -a 'name=wget state=latest' #安裝wget
www.orange.com | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror\nSetting up Install Process\nLoading mirror speeds from cached hostfile\n * base: centos.ustc.edu.cn\n * extras: ftp.sjtu.edu.cn\n * updates: centos.ustc.edu.cn\nResolving Dependencies\n--> Running transaction check\n---> Package wget.x86_64 0:1.12-10.el6 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package         Arch              Version                Repository       Size\n================================================================================\nInstalling:\n wget            x86_64            1.12-10.el6            base            484 k\n\nTransaction Summary\n================================================================================\nInstall       1 Package(s)\n\nTotal download size: 484 k\nInstalled size: 1.8 M\nDownloading Packages:\nRunning rpm_check_debug\nRunning Transaction Test\nTransaction Test Succeeded\nRunning Transaction\n\r  Installing : wget-1.12-10.el6.x86_64                                      1/1 \n\r  Verifying  : wget-1.12-10.el6.x86_64                                      1/1 \n\nInstalled:\n  wget.x86_64 0:1.12-10.el6                                                     \n\nComplete!\n"
    ]
}
www.lemon.com | SUCCESS => {
    "changed": true, 
    "msg": "", 
    "rc": 0, 
    "results": [
        "Loaded plugins: fastestmirror\nSetting up Install Process\nLoading mirror speeds from cached hostfile\n * base: centos.ustc.edu.cn\n * extras: ftp.sjtu.edu.cn\n * updates: centos.ustc.edu.cn\nResolving Dependencies\n--> Running transaction check\n---> Package wget.x86_64 0:1.12-10.el6 will be installed\n--> Finished Dependency Resolution\n\nDependencies Resolved\n\n================================================================================\n Package         Arch              Version                Repository       Size\n================================================================================\nInstalling:\n wget            x86_64            1.12-10.el6            base            484 k\n\nTransaction Summary\n================================================================================\nInstall       1 Package(s)\n\nTotal download size: 484 k\nInstalled size: 1.8 M\nDownloading Packages:\nRunning rpm_check_debug\nRunning Transaction Test\nTransaction Test Succeeded\nRunning Transaction\n\r  Installing : wget-1.12-10.el6.x86_64                                      1/1 \n\r  Verifying  : wget-1.12-10.el6.x86_64                                      1/1 \n\nInstalled:\n  wget.x86_64 0:1.12-10.el6                                                     \n\nComplete!\n"
    ]
}

使用`yum’軟體包管理器管理軟體包,其選項有: 
– config_file:yum的配置檔案 (optional) 
– disable_gpg_check:關閉gpg_check (optional) 
– disablerepo:不啟用某個源 (optional) 
– enablerepo:啟用某個源(optional) 
– name:要進行操作的軟體包的名字,預設最新的程式包,指明要安裝的程式包,可以帶上版本號,也可以傳遞一個url或者一個本地的rpm包的路徑 
– state:狀態(present,absent,latest),表示是安裝還解除安裝 
   present:預設的,表示為安裝 
   lastest: 安裝為最新的版本 
   absent:表示刪除 
7.cron模組

cron:遠端主機crontab配置

[[email protected] test]# ansible webservers -m cron -a 'name=sync_time minute=*/5 job="/usr/sbin/ntpdate cn.pool.ntp.org >/dev/null 2>&1"' #每五分鐘同步一次網路時間
www.orange.com | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "check dir", 
        "sync_time"
    ]
}
www.lemon.com | SUCCESS => {
    "changed": true, 
    "envs": [], 
    "jobs": [
        "check dir", 
        "sync_time"
    ]
}

job                    # 定義定時任務與要做什麼事

name       # 給定時任務加一個備註,避免創建出多個重複的定時任務(根據定時任務備份判斷        是否生成一個新的定時任務)

stat       #若設定為present,表示建立定時任務,若設定為absent,表示刪除指定定時任務

disabled      #disable=yes註釋掉定時任務(不生效),disable=no解除註釋定時任務(生效)

8.service模組

service:遠端主機系統服務管理

[[email protected] test]# ansible webservers -m service -a 'name=mysqld state=restarted' #重啟mysql服務
www.orange.com | SUCCESS => {
    "changed": true, 
    "name": "mysqld", 
    "state": "started"
}
www.lemon.com | SUCCESS => {
    "changed": true, 
    "name": "mysqld", 
    "state": "started"
}

9.file模組

file模組主要用於遠端主機上的檔案操作,file模組包含如下選項: 
– force:需要在兩種情況下強制建立軟連結,一種是原始檔不存在但之後會建立的情況下;另一種是目標軟連結已存在,需要先取消之前的軟鏈,然後建立新的軟鏈,有兩個選項:yes|no 
– group:定義檔案/目錄的屬組 
– mode:定義檔案/目錄的許可權 
– owner:定義檔案/目錄的屬主 
– path:必選項,定義檔案/目錄的路徑 
– recurse:遞迴的設定檔案的屬性,只對目錄有效 
– src:要被連結的原始檔的路徑,只應用於state=link的情況 
– dest:被連結到的路徑,只應用於state=link的情況 
– state: 
   directory:如果目錄不存在,建立目錄 
   file:即使檔案不存在,也不會被建立 
   link:建立軟連結 
   hard:建立硬連結 
   touch:如果檔案不存在,則會建立一個新的檔案,如果檔案或目錄已存在,則更新其最後修改時間 
   absent:刪除目錄、檔案或者取消連結檔案

[[email protected] ~]# ansible webservers -m file -a "dest=/root/test/test.sh state=absent"  #刪除test.sh檔案
www.orange.com | SUCCESS => {
    "changed": true, 
    "path": "/root/test/test.sh", 
    "state": "absent"
}
www.lemon.com | SUCCESS => {
    "changed": true, 
    "path": "/root/test/test.sh", 
    "state": "absent"
}

10.setup模組

ansible webservers -m setup 

#顯示遠端主機的所有資訊(後面加-v顯示詳細資訊)

#提取IP、或架構資訊等,X86來判斷主機架構,安裝合適軟體

ansible webservers -m setup -v  

#主要用於解決一些錯誤:如遠端主機hang住了,ansible會輸出少量資訊(最多-vvvv)