自動化部署工具——Ansible探索

前言

即便是在傳統的企業當中,平常的備份、服務器狀態監控和日誌,經過手動的方式來進行的效率也很低,是一種人力的浪費。所以,自動化早已經是每一個運維都必須掌握的看家本領。php

在不一樣的企業中,自動化的規模、需求與實現方式都各不相同,所以在技術細節層面,運維之間很難將別的企業的方法整個套用過來。然而在不少狀況下,自動化的思路是有共通之處的。html

運維自動化前三階段node

◆純手工階段:手工操做重複地進行軟件部署和運維。python

◆腳本階段:經過編寫腳本、方便地進行軟件部署和運維。mysql

◆工具階段:藉助第三方工具高效、方便地進行軟件部署和運維。linux

這幾個階段是隨着運維知識、經驗、教訓不斷積累而不斷演進的。並且,第2個階段和第3個階段能夠說是齊頭並進,Linux下的第三方工具雖然說已經很多了,可是Linux下的腳本編寫對運維工做的促進做用是絕對不能夠忽視的。nginx

在DevOps出現以前,運維工做者在工做中仍是以這兩種方式爲主。git

下面的研究,都是一些linux下開源的第三方工具,藉助第三方工具高效、方便地進行軟件部署和運維。github

運維自動化工具介紹

在平常服務器維護中,從系統安裝到程序部署再到發佈應用,在大規模的生產環境中,若是須要手動的每臺服務器進行安裝配置將會給運維人員帶來許多繁瑣而又重複的工做。這就促使了在每一個運維層次中出現了不一樣的自動化運維工具。
常見的自動化運維工具分類有如下幾類:web

系統安裝運維工具(OS Provisioning):

常見的有:PXE,Cobbler,Red Hat Satelite(redhat)系統專用等


操做系統的配置運維工具(OS Config):

常見的有:cfengine,puppet,saltsack,chef等


應用程序部署工具(Application Service Orchestration):

常見的有:Func,Fabric,ControITier,Capistrano等


根據工做模式不一樣上面的運維工具備分爲如下兩類:

agent:基於ssl協議實現,agent工做在被監控端,例如:puppet,saltstack
agentless: 基於ssh key實現,例如:ansible


選擇Ansible的緣由:

Puppet 和 SaltStack 我曾用過,但不是十分符合預期,因此先行排除。至於 Chef,雖然老早就據說過,但卻一直沒有找到機會嘗試。翻了翻文檔,Chef 跟 Puppet 及 SaltStack 也是同樣採用服務端/客戶端模式,對於在現有必定數量的機器上部署仍然有  些麻煩。最後落單到 Ansible 上。通過對 Ansible 的把玩,我感受 Ansible 於我比較相投。我喜歡 Ansible 的方面包括:

  • 充分利用現有設施。使用 Ansible 無需安裝服務端和客戶端,只要 SSH 便可。這意味着,任何一臺裝有 Ansible 的機器均可以成爲強大的管理端。我以爲,這種去中心化的思路顯得更爲靈活。可能有人會擔憂 SSH 的效率,Ansible 的並行執行及加速模式或許能夠打消你的顧慮。

  • 使用簡單,快速上手至關容易。我在用 Puppet 以前,就沒少花時間鑽研它。想一想吧,咱們使用這類自動化管理工具不就是想把本身從重複的、複雜的事情中解放出來麼?爲了簡化一件事,而沉入另外一件複雜的事,是否是有些不划算?從個人體驗來看,Ansible 上手十分快,用 Ad-Hoc 能夠應付簡單的管理任務,麻煩點的也能夠定義 Playbook 文件來搞定。

  • 採用人類易讀的格式。Ansible 的主機定義文件使用 INI 格式,支持分組,可以指定模式;此外也能動態生成,這對管理雲主機應當頗有用。而 Playbook 則是 YAML 格式,我以爲它比 Puppet 的 DSL 要易讀易寫多了。

  • 可以使用你熟悉的語言來編寫模塊。雖然 Ansible 是使用 Python 開發的,但它不會將你限制到某種具體的編程語言,Bash、Python、Perl、Ruby 等等均可以,你擅長什麼就用什麼。

一言以蔽之,Ansible 背後的簡單化哲學深得我心。這也比較符合我選擇軟件的一向原則。可能還有人會比較關心目前 Ansible 都有誰在用。畢竟,榜樣的力量是無窮。Puppet 不正是由於 Google 在用而吸引了很多眼球麼?據我所知,當前使用 Ansible 較爲知名的用戶包括 Fedora、Rackspace、Evernote 等等。



對管理主機的要求


目前,只要機器上安裝了 Python 2.6 或 Python 2.7 (windows系統不能夠作控制主機),均可以運行Ansible.
主機的系統能夠是 Red Hat, Debian, CentOS, OS X, BSD的各類版本,等等.

對節點主機的要求


一般咱們使用 ssh 與託管節點通訊,默認使用 sftp.若是 sftp 不可用,可在 ansible.cfg 配置文件中配置成 scp 的方式. 在託管節點上也須要安裝 Python 2.4 或以上的版本.若是版本低於 Python 2.5 ,還須要額外安裝一個模塊:

python-simplejson

Ansible 與其它配置管理的對比


選擇了目前幾款主流的與 Ansible 功能相似的配置管理軟件 Puppet、Saltstack,這裏所作的對比不針對各個軟件的性能做比較,只是對各個軟件的特性作個對比。


Puppet Saltstack Ansible
開發語言 Ruby Python Python
是否有客戶端
是否支持二次開發 不支持 支持 支持
服務器與遠程機器是否相互驗證
服務器與遠程機器通訊是否加密 是,標準 SSL 協議 是,使用 AES 加密 是,使用 OpenSSH
平臺支持 支持 AIX、BSD、HP-UX、Linux、 MacOSX、Solaris、 Windows 支持 BSD、Linux、Mac OS X、Solaris、 Windows 支持 AIX、BSD、 HP-UX、 Linux、Mac OSX、Solaris
是否提供 web ui    提供 提供 提供,不過是商業版本
配置文件格式 Ruby 語法格式 YAML YAML
命令行執行 不支持,但可經過配置模塊實現 支持 支持



Ansible基本架構

  Ansible 是一個模型驅動的配置管理器,支持多節點發布、遠程任務執行。默認使用 SSH 進行遠程鏈接。無需在被管理節點上安裝附加軟件,可以使用各類編程語言進行擴展。

1240

上圖爲ansible的基本架構,從上圖能夠了解到其由如下部分組成:

遠程調用管理模塊,從Inventory裏調用主機名字
ansible特性
    基於python語言實現, 模塊化 設計 ,調用特定的模塊來完成特定任務 ,自己是核心組件,短小精悍 。
    由Paramiko來實現建立ssh鏈接,基於ssh協議鏈接每個被管理主機
    YAML格式是基於PyYAML模塊來實現功能的,由於這個模塊還支持模板語言,因此還須要jinjia2模板語言
    由Paramiko,PyYAML和Jinjia2三個關鍵模塊;

(1)、no agents:部署簡單,不須要在被管控主機上安裝任何客戶端;

(2)、no server:無服務器端,使用時直接運行命令便可;

(3)、modules in any languages:支持自定義模塊,基於「模塊」完成各類「任務」,支持各類可以使用任意語言開發模塊;

(4)、yaml,not code:使用yaml語言定製劇本playbook;

(5)、ssh by default:,使用SSH協議並基於SSH工做((1) 基於密鑰認證;(2) 在inventory文件中指定帳號和密碼);

(6)、strong multi-tier solution:可實現多級指揮。

Ansible 工做機制

Ansible 在管理節點將 Ansible 模塊經過 SSH 協議(或者 Kerberos、LDAP)推送到被管理端執 行,執行完以後自動刪除,可使用 SVN 等來管理自定義模塊及編排

 

一、管理端支持local 、ssh、zeromq 三種方式鏈接被管理端,默認使用基於ssh的鏈接---這部分對應基本架構圖中的鏈接模塊;

二、能夠按應用類型等方式進行Host Inventory(主機羣)分類,管理節點經過各種模塊實現相應的操做---單個模塊,單條命令的批量執行,咱們能夠稱之爲ad-hoc;

三、管理節點能夠經過playbooks 實現多個task的集合實現一類功能,如web服務的安裝部署、數據庫服務器的批量備份等。playbooks咱們能夠簡單的理解爲,系統經過組合多條ad-hoc操做的配置文件 。

ansible的任務執行流程

(1)讀取配置

(2)抓取全量機器&分組列表

       可從多個靜態文件、文件夾、腳本中讀取機器,分組及其變關聯量信息。

(3)使用host-pattern過濾機器列表

(4)根據參數肯定執行模塊和配置

       從modules目錄動態讀取,用戶能夠自行開發模塊。

(5)Runner執行返回

       Connection環節定義鏈接方式 => Action階段機器列表(Lookup plugin Action變量/文件等資源的獲取)

       Callback plugin各階段的鉤子調用

(6)輸出結束

       Filter plugin過濾算子

       Callback plugin各階段的鉤子調用

 

Ansible—輕量級的自動化部署工具

Ansible是新出現的運維工具是基於Python研發的糅合了衆多老牌運維工具的優勢實現了批量操做系統配置、批量程序的部署、批量運行命令等功能。

ansible是基於模塊工做的ansible自己沒有批量部署的能力。真正具備批量部署的是ansible所運行的模塊ansible只是提供一種框架。架構包括

鏈接插件connection plugins負責和被監控端實現通訊。

Host Inventory:指定操做的主機,是一個配置文件裏面定義監控的主機

各類模塊核心模塊command模塊自定義模塊

藉助於插件完成記錄日誌郵件等功能

PlayBooks:劇本執行多個任務時。並不是必需可讓節點一次性運行多個任務

Ansible的優勢

優勢:

應用代碼自動化部署。
系統管理配置自動化。
支持持續交付自動化。
支持雲計算、大數據平臺(如AWS、OpenStack、VMWare等)環境。
輕量級,無需在客戶端安裝agent,更新時只需在控制機上進行一次更新便可。
批量任務執行能夠寫成腳本,不用分發到遠程就能夠執行。
使用Python編寫,維護更簡單,Ruby語法過於複雜。
支持非root用戶管理操做,支持sudo。

Ansible 結合 Docker、Mesos、Puppet、Vagrant、Git 等系統能夠構建出很是好的自動化運維平臺。Ansible 比起其餘自動化運維工具更適合對 Docker 實例進行維護和管理。若是你的機器實例數量超過 1000,也能夠選擇Ansible 的 Web 控制工具 Ansible Tower 。


安裝配置


安裝包:

[root@John src]# wget https://www.python.org/ftp/python/2.7.8/Python-2.7.8.tgz
[root@John src]# wget https://pypi.python.org/packages/source/s/setuptools/setuptools-7.0.tar.gz
[root@John src]# wget https://pypi.python.org/packages/source/p/pycrypto/pycrypto-2.6.1.tar.gz
[root@John src]# wget http://pyyaml.org/download/libyaml/yaml-0.1.5.tar.gz
[root@John src]# wget https://pypi.python.org/packages/source/P/PyYAML/PyYAML-3.11.tar.gz
[root@John src]# wget https://pypi.python.org/packages/source/M/MarkupSafe/MarkupSafe-0.9.3.tar.gz
[root@John src]# wget https://pypi.python.org/packages/source/J/Jinja2/Jinja2-2.7.3.tar.gz
[root@John src]# wget https://pypi.python.org/packages/source/e/ecdsa/ecdsa-0.11.tar.gz
[root@John src]# wget https://pypi.python.org/packages/source/p/paramiko/paramiko-1.15.1.tar.gz
[root@John src]# wget https://pypi.python.org/packages/source/s/simplejson/simplejson-3.6.5.tar.gz
[root@John src]# wget http://releases.ansible.com/ansible/ansible-2.0.0.0.tar.gz


安裝:
python2.7安裝
[root@John src]# tar zxvf Python-2.7.8.tgz
[root@John src]# cd Python-2.7.8
[root@John Python-2.7.8]# ./configure --prefix=/usr/local/
[root@John Python-2.7.8]# make && make install
[root@John Python-2.7.8]# python -V
Python 2.7.8
setuptools模塊安裝
[root@John src]# tar zxvf setuptools-7.0.tar.gz
[root@John src]# cd setuptools-7.0
[root@John setuptools-7.0]# python setup.py install


pycrypto模塊安裝
[root@John src]# tar zxvf pycrypto-2.6.1.tar.gz
[root@John src]# cd pycrypto-2.6.1
[root@John pycrypto-2.6.1]# python setup.py install


PyYAML模塊安裝
[root@John src]# tar zxvf yaml-0.1.5.tar.gz
[root@John src]# cd yaml-0.1.5
[root@John yaml-0.1.5]# ./configure  --prefix=/usr/local/
[root@John yaml-0.1.5]# make && make install

[root@John src]# tar zxvf PyYAML-3.11.tar.gz
[root@John src]# cd PyYAML-3.11
[root@John PyYAML-3.11]# python setup.py install


Jinja2模塊安裝
[root@John src]# tar zxvf MarkupSafe-0.9.3.tar.gz ^C
[root@John src]# cd MarkupSafe-0.9.3
[root@John MarkupSafe-0.9.3]# python setup.py install


paramiko模塊安裝
[root@John src]# tar zxvf ecdsa-0.11.tar.gz
[root@John src]# cd ecdsa-0.11
[root@John ecdsa-0.11]# python setup.py install

[root@John src]# tar zxvf paramiko-1.15.1.tar.gz 
[root@John src]# cd paramiko-1.15.1
[root@John paramiko-1.15.1]# python setup.py  install


simplejson模塊安裝
[root@John src]# tar zxvf simplejson-3.6.5.tar.gz
[root@John src]# cd simplejson-3.6.5
[root@John simplejson-3.6.5]# python setup.py install


ansible安裝
[root@John src]# tar zxvf ansible-2.0.0.0.tar.gz ^C
[root@John src]# cd ansible-2.0.0.0
[root@John ansible-2.0.0.0]# python setup.py install

[root@John ansible-2.0.0.0]# mkdir /etc/ansible/
[root@John ansible-2.0.0.0]# cp -rp examples/*  /etc/ansible/

YUM安裝

[root@John src]# wget -O /etc/yum.repos.d/epel.repo  http://mirrors.aliyun.com/repo/epel-6.repo
[root@John src]# yum -y install python-jinja2 PyYAML python-paramiko python-babel python-crypto ansible        #需epel源



配置文件

/etc/ansible/ansible.cfg
主機清單:
/etc/ansible/hosts
角色目錄:
 /etc/ansible/roles
插件目錄:
/usr/share/ansible_plugins/


報錯:

[root@John ansible-2.0.0.0]# ansible test -m command -a 'ls /home'
/usr/local/lib/python2.7/site-packages/Crypto/Util/number.py:57: PowmInsecureWarning: Not using mpz_powm_sec.  You should rebuild using libgmp >= 5 to avoid timing attack vulnerability.
  _warn("Not using mpz_powm_sec.  You should rebuild using libgmp >= 5 to avoid timing attack vulnerability.", PowmInsecureWarning)
192.168.159.2 | SUCCESS | rc=0 >>
www
wwwlogs
wwwroot

192.168.159.3 | SUCCESS | rc=0 >>
www

rc=0 返回值

 解決方法:

打開 /usr/lib64/python2.6/site-packages/Crypto/Util/number.py 文件,能夠 看到 56 行上的註釋說明,要求 libgmp 爲 v5 以上版本。而系統現有版本爲 4.1.4,把如下兩行暫時註釋掉,Ansible 執行正常。
不過,此方法只是臨時加以解決,更好的方式是去將 libgmp 升級到符合要求的版本。libgmp包去網上找

命令格式

#經常使用格式
ansible <host-pattern> [-f forks] [-m module] [-a args]
host-pattern # 能夠是all,或者配置文件中的主機組名
-f forks # 指定並行處理的進程數
-m module # 指定使用的模塊,默認模塊爲command
-a args # 指定模塊的參數
#查看各模塊
ansible-doc [options] [modules]
# 主要選項有:
-l或--list # 列出可用的模塊
-s或--snippet #顯示指定模塊的簡略使用方法


Ansible命令參數介紹

-v,–verbose   詳細模式,若是命令執行成功,輸出詳細的結果(-vv –vvv -vvvv)
-i PATH,–inventory=PATH   指定host文件的路徑,默認是在/etc/ansible/hosts 
-f NUM,–forks=NU  NUM是指定一個整數,默認是5,指定fork開啓同步進程的個數。 
-m NAME,–module-name=NAME   指定使用的module名稱,默認是command
-m DIRECTORY,–module-path=DIRECTORY   指定module的目錄來加載module,默認是/usr/share/ansible, 
-a,MODULE_ARGS   指定module模塊的參數 
-k,-ask-pass     提示輸入ssh的密碼,而不是使用基於ssh的密鑰認證
-sudo                   指定使用sudo得到root權限
-K,-ask-sudo-pass       提示輸入sudo密碼,與–sudo一塊兒使用 
-u USERNAME,-user=USERNAME  指定移動端的執行用戶 
-C,-check               測試此命令執行會改變什麼內容,不會真正的去執行


主機清單介紹hosts

Ansible 經過讀取默認的主機清單配置/etc/ansible/hosts,能夠同時鏈接到多個遠程主機上執行任務,默認路徑能夠經過修改 ansible.cfg 的 hostfile 參數指定路徑。

[dbserver]  []表示主機的分組名,能夠按照功能,系統進行分類,便於進行操做
192.168.10.2 
one.example.com 
www.bds.com:5309         #支持指定ssh端口5309 
jumper ansible_ssh_port=5309 ansible_ssh_host=192.168.10.2   #設置主機別名爲jumper
www[01:50].bds.com       #支持通配符匹配www01.bds.com www02.bds.com
[web]                    #提醒下這裏面字母是隨便定義的
web-[a:f].bds.com        #支持字母匹配 web-a.bds.com ..web-f.bds.com

爲主機指定類型和鏈接用戶

[bds]
Localhost  ansible_connection=local
other1.example.com ansible_connection=ssh ansible_ssh_user=deploy
other2.example.com ansible_connection=ssh ansible_ssh_user=deploy
ansible hosts配置文件中支持指令

注意: 前面若是不配置主機免密鑰登陸,能夠在/etc/ansible/hosts中定義用戶和密碼,主機ip地址,和ssh端口,這樣也能夠進行免密碼訪問,可是這個/hosts文件要保護好,由於全部的密碼都寫在裏面

hosts文件配置參數介紹

1, ansible_ssh_host :
指定主機別名對應的真實 IP,如:100 ansible_ssh_host=192.168.1.100,隨後鏈接該主機無須指定完整 IP,只需指定 251 就行
2, ansible_ssh_port :
指定鏈接到這個主機的 ssh 端口,默認 22
3, ansible_ssh_user:
鏈接到該主機的 ssh 用戶
4, ansible_ssh_pass:
鏈接到該主機的 ssh 密碼(連-k 選項都省了),安全考慮仍是建議使用私鑰或在命令行指定-k 選項輸入
5, ansible_sudo_pass:                              sudo 密碼
6, ansible_sudo_exe:                                sudo 命令路徑
7, ansible_connection :
鏈接類型,能夠是 local、ssh 或 paramiko,ansible1.2 以前默認爲 paramiko
8, ansible_ssh_private_key_file :               私鑰文件路徑
9, ansible_shell_type  :
目標系統的 shell 類型,默認爲 sh,若是設置 csh/fish,那麼命令須要遵循它們語法
10, ansible_python_interpreter  :
python 解釋器路徑,默認是/usr/bin/python,可是如要要連BSD系統的話,就須要該指令修改 python 路徑
11, ansible__interpreter  :
這裏的"*"能夠是 ruby 或 perl 或其餘語言的解釋器,做用和 ansible_python_interpreter 相似



實現基於ssh密鑰通訊

[root@John ~]# ssh-keygen
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:
ad:c8:99:6b:70:b2:c0:10:2e:4b:c7:68:52:2d:17:e0 root@John
The key's randomart p_w_picpath is:
+--[ RSA 2048]----+
|  .o..           |
|..o o            |
|.oEo             |
|+= o     .       |
|=+.     S .      |
|. o o..+ .       |
|   . == .        |
|    . ..         |
|     ..          |
+-----------------+
[root@John ~]# chmod 700 /root/.ssh

[root@John ~]# cat /root/.ssh/id_rsa.pub > /root/.ssh/authorized_keys
[root@John ~]# chmod 600 /root/.ssh/authorized_keys

rsync -av /root/.ssh root@192.168.159.2:/root/

Ansible 可同時操做屬於一個組的多臺主機,組和主機之間的關係經過 inventory 文件配置. 默認的文件路徑爲 /etc/ansible/hosts

配置文件:ansible.cfg,hosts
 #cat /etc/ansible/ansible.cfg   主配置文件,能夠根據實際應用自行修改

[defaults]
# some basic default values...
hostfile       = /etc/ansible/hosts   \\指定默認hosts配置的位置
# library_path = /usr/share/my_modules/  
remote_tmp     = $HOME/.ansible/tmp
pattern        = *
forks          = 5
poll_interval  = 15
sudo_user      = root  \\遠程sudo用戶
#ask_sudo_pass = True  \\每次執行ansible命令是否詢問ssh密碼
#ask_pass      = True  \\每次執行ansible命令時是否詢問sudo密碼
transport      = smart
remote_port    = 22
module_lang    = C
gathering = implicit
host_key_checking = False    \\關閉第一次使用ansible鏈接客戶端是輸入命令提示
log_path    = /var/log/ansible.log \\須要時能夠自行添加。chown -R root:root ansible.log
system_warnings = False    \\關閉運行ansible時系統的提示信息,通常爲提示升級
  
# set plugin path directories here, separate with colons
action_plugins     = /usr/share/ansible_plugins/action_plugins
callback_plugins   = /usr/share/ansible_plugins/callback_plugins
connection_plugins = /usr/share/ansible_plugins/connection_plugins
lookup_plugins     = /usr/share/ansible_plugins/lookup_plugins
vars_plugins       = /usr/share/ansible_plugins/vars_plugins
filter_plugins     = /usr/share/ansible_plugins/filter_plugins
fact_caching = memory
  
[accelerate]
accelerate_port = 5099
accelerate_timeout = 30
accelerate_connect_timeout = 5.0
# The daemon timeout is measured in minutes. This time is measured
# from the last activity to the accelerate daemon.
accelerate_daemon_timeout = 30

#cat /etc/ansible/hosts  主機清單信息配置文件,能夠自定義主機,支持IP,域名,支持分組

[host01]  \\分組名,[]表示主機的分組名,能夠按照功能、系統等進行分類,便於對某些主機或者某一組功能相同的主機進行操做
10.11.8.21 ansible_ssh_user=root ansible_ssh_pass=Passwd     \\遠程ip,ssh登陸用戶,密碼 
10.11.8.28 ansible_ssh_user=root ansible_ssh_pass=GxwLaXOs&1SK
10.10.30.50                \\若主機間進行的祕鑰通訊,則只須要添加主機 ip 就好了
[host02]
10.11.2.28
  
[web]
10.11.0.25
10.11.0.26
[web:var]            \\統一對web組設置變量
ansible_ssh_port=22
ansible_ssh_user=root
ansible_ssh_pass=123456
 
[db]
10.11.1.10
test ansible_ssh_port=5555 ansible_ssh_host=10.11.15    \\設置主機別名爲 test
10.11.1.11:2156                   \\指定ssh端口
www[001:006].example.com          \\支持通配符 www001 www002 ..
new-[a:f]-node.example.com        \\支持字母匹配 new-a-node.example.com new-b-node.example.com ...
  
[server:children]   \\組能夠包含其它組
web
db
[test]        
host01
host02

hosts 文件支持一些特定指令,全部支持的指令以下:

ansible_ssh_host:指定主機別名對應的真實 IP,如:251 ansible_ssh_host=183.60.41.251,隨後鏈接該主機無須指定完整 IP,只需指定 251 就行
ansible_ssh_port:指定鏈接到這個主機的 ssh 端口,默認 22
ansible_ssh_user:鏈接到該主機的 ssh 用戶
ansible_ssh_pass:鏈接到該主機的 ssh 密碼(連-k 選項都省了),安全考慮仍是建議使用私鑰或在命令行指定-k 選項輸入
ansible_sudo_pass:sudo 密碼
ansible_sudo_exe(v1.8+的新特性):sudo 命令路徑
ansible_connection:鏈接類型,能夠是 local、ssh 或 paramiko,ansible1.2 以前默認爲 paramiko
ansible_ssh_private_key_file:私鑰文件路徑
ansible_shell_type:目標系統的 shell 類型,默認爲 sh,若是設置 csh/fish,那麼命令須要遵循它們語法
ansible_python_interpreter:python 解釋器路徑,默認是/usr/bin/python,可是如要要連*BSD系統的話,就須要該指令修改 python 路徑
ansible_*_interpreter:這裏的"*"能夠是 ruby 或 perl 或其餘語言的解釋器,做用和 ansible_python_interpreter 相似
例子:
  some_host ansible_ssh_port=2222 ansible_ssh_user=manager
  aws_host ansible_ssh_private_key_file=/home/example/.ssh/aws.pem
  freebsd_host ansible_python_interpreter=/usr/local/bin/python
  ruby_module_host ansible_ruby_interpreter=/usr/bin/ruby.1.9.3


主機清單示例

www.example.com # FQDN

[webservers] # 方括號[]中是組名
host1
host2:8888  # 指定鏈接主機得端口號
localhost ansible_connection=local # 定義鏈接類型
host3 http_port=80 maxRequestsPerChild=808 # 定義主機變量
host4 ansible_ssh_port=5555 ansible_ssh_host=192.168.1.50 # 定義主機ssh鏈接端口和鏈接地址
www[1:50].example.com # 定義 1-50範圍內的主機
www-[a:f].example.com # 定義a-f範圍內內的主機

[dbservers]
www.example.com     ansible_python_interpreter=/usr/local/bin/python #定義python執行文件
192.168.159.3     ruby_module_host  ansible_ruby_interpreter=/usr/bin/ruby.1.9.3 # 定義ruby執行文件

[webservers:vars]  # 定義webservers組的變量
ntp_server= ntp.example.com
proxy=proxy.example.com


[server:children] # 定義server組的子成員
webservers
dbservers

[server:vars] # 定義server組的變量
zabbix_server:192.168.159.2

Inventory 參數的說明


主機鏈接:

參數 說明
ansible_connection 與主機的鏈接類型.好比:local, ssh 或者 paramiko. Ansible 1.2 之前默認使用 paramiko.1.2 之後默認使用 'smart','smart' 方式會根據是否支持 ControlPersist, 來判斷'ssh' 方式是否可行.

ssh鏈接參數:

參數 說明
ansible_ssh_host 將要鏈接的遠程主機名.與你想要設定的主機的別名不一樣的話,可經過此變量設置.
ansible_ssh_port ssh端口號.若是不是默認的端口號,經過此變量設置.
ansible_ssh_user 默認的 ssh 用戶名
ansible_ssh_pass ssh 密碼(這種方式並不安全,咱們強烈建議使用 --ask-pass 或 SSH 密鑰)
ansible_ssh_private_key_file ssh 使用的私鑰文件.適用於有多個密鑰,而你不想使用 SSH 代理的狀況.
ansible_ssh_common_args 此設置附加到sftp,scp和ssh的缺省命令行
ansible_sftp_extra_args 此設置附加到默認sftp命令行。
ansible_scp_extra_args 此設置附加到默認scp命令行。
ansible_ssh_extra_args 此設置附加到默認ssh命令行。
ansible_ssh_pipelining 肯定是否使用SSH管道。 這能夠覆蓋ansible.cfg中得設置。

遠程主機環境參數:

參數 說明
ansible_shell_type 目標系統的shell類型.默認狀況下,命令的執行使用 'sh' 語法,可設置爲 'csh' 或 'fish'.
ansible_python_interpreter 目標主機的 python 路徑.適用於的狀況: 系統中有多個 Python, 或者命令路徑不是"/usr/bin/python",好比  *BSD, 或者 /usr/bin/python
ansible_*_interpreter 這裏的"*"能夠是ruby 或perl 或其餘語言的解釋器,做用和ansible_python_interpreter 相似
ansible_shell_executable 這將設置ansible控制器將在目標機器上使用的shell,覆蓋ansible.cfg中的配置,默認爲/bin/sh。



ansible 經常使用模塊介紹

ansible使用幫助

[root@John ~]# ansible-doc  -l                 #查詢ansible的全部模塊
[root@John ~]# ansible-doc -s module_name      #查看模塊的屬性

交互式命令執行界面

Usage: ansible-console <host-pattern> [options]

選項與ansible一致

ansible-doc


該指令用於查看模塊信息,經常使用參數有兩個-l-s

Usage: ansible <host-pattern> [options]

選項

參數 說明
-h, --help 顯示此幫助信息
-l, --list 列出可用的模塊
-M MODULE_PATH, --module-path=MODULE_PATH 指定到模塊庫的路徑
-s, --snippet 顯示playbook制定模塊的用法
-v, --verbose 詳細模式(-vvv表示更多,-vvvv表示啓用鏈接調試)
--version 顯示程序版本號


例子: 查詢service 模塊的信息

[root@John /]# ansible-doc -s service
less 436
Copyright (C) 1984-2009 Mark Nudelman

less comes with NO WARRANTY, to the extent permitted by law.
For information about the terms of redistribution,
see the file named README in the less distribution.
Homepage: http://www.greenwoodsoftware.com/less
- name: Manage services.
  action: service
      arguments              # Additional arguments provided on the command line
      enabled                # Whether the service should start on boot. *At least one of state and enabled are required.*
      name=                  # Name of the service.
      pattern                # If the service does not respond to the status command, name a substring to look for as would
                               be found in the output of the `ps' command as a stand-in for a
                               status result.  If the string is found, the service will be
                               assumed to be running.
      runlevel               # For OpenRC init scripts (ex: Gentoo) only.  The runlevel that this service belongs to.
      sleep                  # If the service is being `restarted' then sleep this many seconds between the stop and start
                               command. This helps to workaround badly behaving init scripts
                               that exit immediately after signaling a process to stop.
      state                  # `started'/`stopped' are idempotent actions that will not run commands unless necessary.
                               `restarted' will always bounce the service.  `reloaded' will
                               always reload. *At least one of state and enabled are
                               required.*
ansible-doc -s service- name: Manage services.
  action: service
      state=              如今是什麼狀態               
      name=               啓動的服務名稱
      runlevel=           指定在什麼級別下啓動
      pattern=            指定模式    
      enabled=             開機是否啓動 
例:設置web服務開機自動啓動
[root@control ~]# ansible all -m service -a "state=started name=httpd enabled=yes"                               

service: 指定運行狀態
    enable=:是否開機自動啓動,取值爲true或false
    name=: 服務名稱
    state=:狀態,取值有started,stoped,restarted;
    # ansible test -a  "service network status"
    # ansible test -a "chkconfig --list httpd"
# 確保某服務已開啓,沒開則開
ansible test -m service -a "name=mysql state=started"
ansible test -m service -a "name=mysql state=restarted"
ansible test -m service -a "name=mysql state=stopped"


ansible語法

ansible <pattern_goes_here> -m <module_name> -a <arguments>

command模塊

默認模塊 ,用於在各個被管理節點運行指定的命令(不支持管道和變量)
相關選項以下:

creates:一個文件名,當該文件存在,則該命令不執行

free_form:要執行的Linux指令

chdir:在執行指令以前,先切換到該目錄

removes:一個文件名,當該文件不存在,則該選項不執行

executable:切換shell來執行指令,該執行路徑必須是一個絕對路徑
[root@John /]# ansible test -m command -a "hostname"
192.168.159.2 | SUCCESS | rc=0 >>
John

192.168.159.3 | SUCCESS | rc=0 >>
John

shell模塊

command模塊功能相同,但比command的模塊功能強大(支持管道和變量)
[root@John /]# ansible all -m shell -a "cat /etc/passwd| grep root" 
192.168.159.2 | SUCCESS | rc=0 >>
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

192.168.159.3 | SUCCESS | rc=0 >>
root:x:0:0:root:/root:/bin/bash
operator:x:11:0:operator:/root:/sbin/nologin

user模塊

用戶模塊,用於在各管理節點管理用戶所使用

建立一個名字爲DBA的用戶,uid是505 ,家目錄是/home,shell是不讓用戶登陸

[root@John /]# ansible test -m user -a 'name=DBA uid=505 home=/home/ shell=/sbin/nologin'
192.168.159.3 | SUCCESS => {
    "append": false, 
    "changed": true, 
    "comment": "", 
    "group": 505, 
    "home": "/home/", 
    "move_home": false, 
    "name": "DBA", 
    "shell": "/sbin/nologin", 
    "state": "present", 
    "uid": 505
}
192.168.159.2 | SUCCESS => {
    "append": false, 
    "changed": true, 
    "comment": "", 
    "group": 505, 
    "home": "/home/", 
    "move_home": false, 
    "name": "DBA", 
    "shell": "/sbin/nologin", 
    "state": "present", 
    "uid": 505
}

刪除一個用戶

[root@John /]# ansible test -m user  -a 'name=DBA uid=506  state=absent'
192.168.159.2 | SUCCESS => {
    "changed": true, 
    "force": false, 
    "name": "DBA", 
    "remove": false, 
    "state": "absent"
}
192.168.159.3 | SUCCESS => {
    "changed": true, 
    "force": false, 
    "name": "DBA", 
    "remove": false, 
    "state": "absent"
}

setup模塊

## 收集ansible的facts信息
# ansiblestorm_cluster -m setup
## 用來測試遠程主機的運行狀態
[root@John /]# ansible test -m ping
192.168.159.3 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}
192.168.159.2 | SUCCESS => {
    "changed": false, 
    "ping": "pong"
}

file模塊

設定文件屬性

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

group:定義文件/目錄的屬組

mode:定義文件/目錄的權限

owner:定義文件/目錄的屬主

path:必選項,定義文件/目錄的路徑

recurse:遞歸設置文件的屬性,只對目錄有效

src:被連接的源文件路徑,只應用於state=link的狀況

dest:被連接到的路徑,只應用於state=link的狀況

state:

      directory:若是目錄不存在,就建立目錄

      file:即便文件不存在,也不會被建立

      link:建立軟連接

      hard:建立硬連接

      touch:若是文件不存在,則會建立一個新的文件,若是文件或目錄已存在,則更新其最後修改時間

      absent:刪除目錄、文件或者取消連接文件

示例:

## 遠程文件符號連接建立

# ansible test -m file -a "src=/etc/resolv.conf dest=/tmp/resolv.confstate=link"

## 遠程文件信息查看

# ansible test -m command -a "ls –al /tmp/resolv.conf"

## 遠程文件符號連接刪除

# ansible test -m file -a "path=/tmp/resolv.conf state=absent"

## 遠程文件信息查看

# ansible test -m command -a "ls -al /tmp/resolv.conf"

copy模塊

複製文件

backup:在覆蓋以前,將源文件備份,備份文件包含時間信息。有兩個選項:yes|no

content:用於替代「src」,能夠直接設定指定文件的值

dest:必選項。要將源文件複製到的遠程主機的絕對路徑,若是源文件是一個目錄,那麼該路徑也必須是個目錄

directory_mode:遞歸設定目錄的權限,默認爲系統默認權限

force:若是目標主機包含該文件,但內容不一樣,若是設置爲yes,則強制覆蓋.
若是爲no,則只有當目標主機的目標位置不存在該文件時,才複製。默認爲yes

others:全部的file模塊裏的選項均可以在這裏使用

src:被複制到遠程主機的本地文件,能夠是絕對路徑,也能夠是相對路徑。
若是路徑是一個目錄,它將遞歸複製。在這種狀況下,若是路徑使用「/」來結尾,則只複製目錄裏的內容.
若是沒有使用「/」來結尾,則包含目錄在內的整個內容所有複製,相似於rsync。

實例:

## 將本地文件「/etc/ansible/ansible.cfg」複製到遠程服務器

# ansible test -m copy -a "src=/etc/ansible/ansible.cfgdest=/tmp/ansible.cfg owner=root group=root mode=0644"
# ansible test -m copy -a 'src=/etc/fstab dest=/tmp/fstab.ansible owner=root mode=640'
# ansible test -m copy -a "content='Hello Ansible' dest=/tmp/test.ansible"

script模塊

自動複製腳本到遠程節點,並運行

測試腳本
[root@John ~]# cat ansible_test.sh #!/bin/bash echo "hello world " >> /tmp/ansible_sh.log

運行腳本
[root@John ~]# ansible all -m script -a 'ansible_test.sh'

cron模塊

計劃定時任務,用於在各管理節點管理計劃任務

[root@note1 ~]# ansible all -m cron -a "name=time minute='*/2' job='/usr/sbin/ntpdate

template模塊

根據官方的翻譯是:template使用了Jinjia2格式做爲文件模板,進行文檔內變量的替換的模塊。他的每次使用都會被ansible標記爲changed狀態。
在定義模板以後能夠實現各節點對應的變量來取代,表達式自身會根據當前節點
所賦值作運算,以後生成的值則賦予這個參數,用於生成不一樣配置的配置文件,
因此模板主要實現配置不一樣場景文本文件。並且這樣使用模板語言來定義,模板
語言中能夠根據定義替換成特定主機的某些值。

yum模塊

用於管理節點安裝軟件所使用
ansible-doc -s yum action: yum
      state=       指定是安裝(`present', `latest'), 仍是卸載 remove (`absent') 
      disablerepo= 若是有多個yum源可能禁用一個
      name=        要安裝的包名(若是隻寫包名,就安裝最新的包,若是想指定安裝什麼片本的就包名+版本號)
      enablerepo=  要啓用的repo
      list=        列表(跟playbook相關)
      disable_gpg_check=  是否開啓gpg_check
      conf_file=    能夠用其它服務器上的配置文件,而不使用本地的配置文件
例:全部的主機都安裝上corosync.
[root@John ~]# ansible all -m yum -a "state=present name=corosync"
[root@John ~]# ansible all -m yum -a 'name=ntp state=present'
卸載的軟件只須要將 name=ntp state=absent
安裝特定版本 name=nginx-1.6.2 state=present
指定某個源倉庫安裝軟件包name=htop enablerepo=epel state=present
更新軟件到最新版 name=nginx state=latest


實例:

執行shell
獲取web組裏得eth0接口信息
ansible web -a "ifconfig eth0"
執行ifconfig eth0 命令,ansible模塊 默認是command,它不會經過shell進行處理,
因此像$ HOME和像「<」,「>」,「|」,「;」 和「&」將不工做(若是您須要這些功能,請使用shell模塊)。
以shell解釋器執行腳本
ansible web -m shell -a "ifconfig eth0|grep addr"
以raw模塊執行腳本
ansible web -m raw -a "ifconfig eth0|grep addr
將本地腳本傳送到遠程節點上運行
ansible web -m script -a ip.sh
傳輸文件
拷貝本地的/etc/hosts 文件到web組全部主機的/tmp/hosts(空目錄除外)
ansible web -m copy -a "src=/etc/hosts dest=/tmp/hosts"
拷貝本地的ntp文件到目的地址,設置其用戶及權限,若是目標地址存在相同的文件,則備份源文件。
ansible web -m copy -a "src=/mine/ntp.conf dest=/etc/ntp.conf owner=root group=root mode=644 backup=yes force=yes"
file 模塊容許更改文件的用戶及權限
ansible web -m file -a "dest=/tmp/a.txt mode=600 owner=user group=user"
使用file 模塊建立目錄,相似mkdir -p
ansible web -m file -a "dest=/tmp/test mode=755 owner=user group=user state=directory"
使用file 模塊刪除文件或者目錄
ansible web -m file -a "dest=/tmp/test state=absent"
建立軟鏈接,並設置所屬用戶和用戶組
ansible web -m file -a  "src=/file/to/link/to dest=/path/to/symlink owner=user group=user state=link"
touch 一個文件並添加用戶讀寫權限,用戶組去除寫執行權限,其餘組減去讀寫執行權限
ansible web -m file -a  "path=/etc/foo.conf state=touch mode='u+rw,g-wx,o-rwx'"
管理軟件包
apt、yum 模塊分表用於管理Ubuntu 系列和RedHat 系列系統軟件包
更新倉庫緩存,並安裝"foo"
ansible web -m apt -a "name=foo update_cache=yes"
刪除 "foo"
ansible web -m apt -a "name=foo state=absent"
安裝  "foo"
ansible web -m apt -a "name=foo state=present"
安裝  1.0版本的 "foo"
ansible web -m apt -a "name=foo=1.00 state=present"
安裝最新得"foo"
ansible web -m apt -a "name=foo state=latest"
註釋:Ansible 支持不少操做系統的軟件包管理,使用時-m 指定相應的軟件包管理工具模塊,若是沒有這樣的模塊,能夠本身定義相似的模塊或者使用command 模塊來安裝軟件包
安裝 最新的 Apache
ansible web -m yum -a  "name=httpd state=latest"
刪除apache
ansible web -m yum -a  "name=httpd state=absent"
從testing 倉庫中安裝最後一個版本得apache
ansible web -m yum -a  "name=httpd enablerepo=testing state=present"
更新全部的包
ansible web -m yum -a  "name=* state=latest"
安裝遠程的rpm包
ansible web -m yum -a  "name=http://nginx.org/packages/centos/6/noarch/RPMS/nginx-release-centos-6-0.el6.ngx.noarch.rpm state=present"
安裝  'Development tools' 包組
ansible web -m yum -a  "name='@Development tools' state=present"
用戶和用戶組
添加用戶 'user'並設置其 uid 和主要的組'admin'
ansible web -m user -a "name=user  comment='I am user ' uid=1040 group=admin"
添加用戶 'user'並設置其登錄shell,並將其假如admins和developers組
ansible web -m user -a "name=user shell=/bin/bash groups=admins,developers append=yes"
刪除用戶 'user '
ansible web -m user -a "name=user state=absent remove=yes"
建立 user用戶得   2048-bit SSH key,並存放在 ~user/.ssh/id_rsa
ansible web -m user -a "name=user generate_ssh_key=yes ssh_key_bits=2048 ssh_key_file=.ssh/id_rsa"
設置用戶過時日期
ansible web -m user -a "name=user shell=/bin/zsh groups=nobdy expires=1422403387"
建立test組,並設置git爲1000
ansible web -m group -a "name=test gid=1000 state=present"
刪除test組
ansible web -m group -a "name=test state=absent"
源碼部署
Ansible 模塊可以通知變動,當代碼更新時,能夠告訴Ansible 作一些特定的任務,好比從git 部署代碼而後重啓apache 服務等
ansible web-m git -a "repo=https://github.com/Icinga/icinga2.git dest=/tmp/myapp   version=HEAD"
服務管理
確保web組全部主機的httpd 是啓動的
ansible web-m service -a "name=httpd state=started"
重啓web組全部主機的httpd 服務
ansible web-m service -a "name=httpd state=restarted"
確保web組全部主機的httpd 是關閉的
ansible web-m service -a "name=httpd state=stopped"
後臺運行
長時間運行的操做能夠放到後臺執行,ansible 會檢查任務的狀態;在主機上執行的同一個任
務會分配同一個job ID
後臺執行命令3600s,-B 表示後臺執行的時間
ansible all -B 3600 -a "/usr/bin/long_running_operation --do-stuff"
檢查任務的狀態
ansible all -m async_status -a "jid=123456789"
後臺執行命令最大時間是1800s 即30 分鐘,-P 每60s 檢查下狀態默認15s
ansible all -B 1800 -P 60 -a "/usr/bin/long_running_operation --do-stuff"
定時任務
天天5點,2點得時候執行 ls -alh > /dev/null
ansible test -m cron -a "name='check dirs' minute='0' hour='5,2' job='ls -alh > /dev/null'"
蒐集系統信息
蒐集主機的全部系統信息
ansible all -m setup
蒐集系統信息並以主機名爲文件名分別保存在/tmp/facts 目錄
ansible all -m setup --tree /tmp/facts
蒐集和內存相關的信息
ansible all -m setup -a 'filter=ansible_*_mb'
蒐集網卡信息
ansible all -m setup -a 'filter=ansible_eth[0-2]'

資源:

官方文檔: http://docs.ansible.com/
中文文檔: http://www.ansible.com.cn/ http://ansible-tran.readthedocs.io/en/latest/
Jinja2 中文文檔: http://docs.jinkan.org/docs/jinja2/
yaml語法: http://www.yaml.org/
書籍: https://www.ansible.com/ebooks
ansible examples: https://github.com/ansible/ansible-examples
ansible-vim: https://github.com/pearofducks/ansible-vim
相關文章
相關標籤/搜索