本文主要內(nèi)容均收集于網(wǎng)絡(luò)上的博文資料缰泡,僅以此文作為學(xué)習(xí)總結(jié)。BTW,目前Ansible對python3的支持還不是很完備菱农。
一缭付、基礎(chǔ)介紹
1、 簡介
ansible是新出現(xiàn)的自動化運(yùn)維工具循未,基于Python開發(fā)陷猫,集合了眾多運(yùn)維工具(puppet、cfengine的妖、chef绣檬、func、fabric)的優(yōu)點(diǎn)嫂粟,實(shí)現(xiàn)了批量系統(tǒng)配置娇未、批量程序部署、批量運(yùn)行命令等功能星虹。ansible是基于模塊工作的零抬,本身沒有批量部署的能力。真正具有批量部署的是ansible所運(yùn)行的模塊宽涌,ansible只是提供一種框架平夜。主要包括:
(1)、連接插件connection plugins:負(fù)責(zé)和被監(jiān)控端實(shí)現(xiàn)通信卸亮;
(2)忽妒、host inventory:指定操作的主機(jī),是一個(gè)配置文件里面定義監(jiān)控的主機(jī)兼贸;
(3)段直、各種模塊核心模塊、command模塊溶诞、自定義模塊坷牛;
(4)、借助于插件完成記錄日志郵件等功能很澄;
(5)京闰、playbook:劇本執(zhí)行多個(gè)任務(wù)時(shí)颜及,非必需可以讓節(jié)點(diǎn)一次性運(yùn)行多個(gè)任務(wù)。
2蹂楣、總體架構(gòu)
3俏站、特性
(1)、no agents:不需要在被管控主機(jī)上安裝任何客戶端痊土;
(2)肄扎、no server:無服務(wù)器端,使用時(shí)直接運(yùn)行命令即可赁酝;
(3)犯祠、modules in any languages:基于模塊工作,可使用任意語言開發(fā)模塊酌呆;
(4)衡载、yaml,not code:使用yaml語言定制劇本playbook隙袁;
(5)痰娱、ssh by default:基于SSH工作;
(6)菩收、strong multi-tier solution:可實(shí)現(xiàn)多級指揮梨睁。
4、優(yōu)點(diǎn)
(1)娜饵、輕量級坡贺,無需在客戶端安裝agent,更新時(shí)箱舞,只需在操作機(jī)上進(jìn)行一次更新即可拴念;
(2)、批量任務(wù)執(zhí)行可以寫成腳本褐缠,而且不用分發(fā)到遠(yuǎn)程就可以執(zhí)行政鼠;
(3)、使用python編寫队魏,維護(hù)更簡單公般,ruby語法過于復(fù)雜;
(4)胡桨、支持sudo官帘。
5、任務(wù)執(zhí)行流程
二昧谊、安裝Ansible
- 從github下載源碼:
$ git clone https://github.com/ansible/ansible.git --recursive
$ cd ./ansible
- 運(yùn)行環(huán)境配置腳本:
$ source ./hacking/env-setup
- 如果沒有安裝pip刽虹,請先安裝對應(yīng)于你的Python版本的pip:
$ sudo easy_install pip
以下的Python模塊也需要安裝:
$ sudo pip install paramiko PyYAML Jinja2 httplib2 six pycrypto
如果安裝paramiko 的時(shí)候系統(tǒng)報(bào)openssl相關(guān)的錯(cuò)誤,那么需要再安裝以下文件:
$ sudo apt-get install -y libffi-dev libssl-dev python-dev
當(dāng)更新ansible版本時(shí),不只要更新git的源碼樹呢诬,也要更新git中指向Ansible自身模塊的 “submodules” (不是同一種模塊):
$ git pull --rebase
$ git submodule update --init --recursive
三涌哲、Ansible 配置
1胖缤、SSH免密鑰登錄設(shè)置
- 使用ssh-keygen生成key-pair,然后將公鑰配置在每臺服務(wù)器.ssh/authorized_keys文件中:
# ssh-keygen -t rsa -P ''
- 寫入信任文件(將/root/.ssh/id_rsa.pub分發(fā)到其他服務(wù)器阀圾,并在所有服務(wù)器上執(zhí)行如下指令):
# cat /root/.ssh/id_rsa.pub >> /root/.ssh/authorized_keys
# chmod 600 /root/.ssh/authorized_keys
如果需要配置公鑰的服務(wù)器數(shù)量比較多的話哪廓,也可以通過使用ansible中的authorize_key模塊來進(jìn)行分布式部署。
2初烘、Ansible配置
Ansible使用前通常需要配置/etc/anisble/路徑下的hosts和ansible.cfg這個(gè)兩個(gè)文件涡真。要注意的是,編輯這兩個(gè)文件需要root權(quán)限肾筐。
# mkdir -p /etc/ansible`
# vim /etc/ansible/ansible.cfg`
……
remote_port = 36000
private_key_file = /root/.ssh/id_rsa
……
Ansible 可同時(shí)操作屬于一個(gè)組的多臺主機(jī)哆料,組和主機(jī)之間的關(guān)系通過 inventory 文件(INI 格式)配置,默認(rèn)的文件路徑為 /etc/ansible/hosts吗铐。一個(gè)系統(tǒng)可以屬于不同的組东亦,比如一臺服務(wù)器可以同時(shí)屬于 webserver組 和 dbserver組。
# vim /etc/ansible/hosts
[test]
10.139.13.80
/etc/ansible/hosts是配置分組的默認(rèn)文件抓歼,還有一種方式可以通過定義環(huán)境變量ANSIBLE_HOSTS來改變配置文件的引用路徑:
export ANSIBLE_HOSTS=~/test/qiuyi_ansible/test_hosts
四讥此、Ansible ad-hoc命令
Ansible提供兩種方式去完成任務(wù)拢锹,一種是 ad-hoc 命令谣妻,另一種寫 Ansible playbook。前者可以解決一些簡單的任務(wù)卒稳,后者解決較復(fù)雜的任務(wù)蹋半。ad-hoc只能做些一些輕量級的指令操作,而配置管理或部署這種事還是要借助 playbook 來完成充坑,即使用 ‘/usr/bin/ansible-playbook’ 這個(gè)命令减江。
ad-hoc的命令格式:
ansible <host-pattern> [options]
ansible有許多模塊,默認(rèn)是 ‘command’捻爷,也就是命令模塊辈灼,我們可以通過 -m 選項(xiàng)來指定不同的模塊。
常用模塊:
1. setup:用來查看遠(yuǎn)程主機(jī)的一些基本信息
2. ping:用來測試遠(yuǎn)程主機(jī)的運(yùn)行狀態(tài)
3. file:設(shè)置文件屬性
相關(guān)選項(xiàng)如下:
force:需要在兩種情況下強(qiáng)制創(chuàng)建軟鏈接也榄,一種是源文件不存在巡莹,但之后會建立的情況下;另一種是目標(biāo)軟鏈接已存在甜紫,需要先取消之前的軟鏈降宅,然后創(chuàng)建新的軟鏈,有兩個(gè)選項(xiàng):yes|no
group:定義文件/目錄的屬組
mode:定義文件/目錄的權(quán)限
owner:定義文件/目錄的屬主
path:必選項(xiàng)囚霸,定義文件/目錄的路徑
recurse:遞歸設(shè)置文件的屬性腰根,只對目錄有效
src:被鏈接的源文件路徑,只應(yīng)用于state=link的情況
dest:被鏈接到的路徑拓型,只應(yīng)用于state=link的情況
-
state
state: directory:如果目錄不存在额嘿,就創(chuàng)建目錄 file:即使文件不存在瘸恼,也不會被創(chuàng)建 link:創(chuàng)建軟鏈接 hard:創(chuàng)建硬鏈接 touch:如果文件不存在,則會創(chuàng)建一個(gè)新的文件岩睁,如果文件或目錄已存在钞脂,則更新其最后 修改時(shí)間 absent:刪除目錄、文件或者取消鏈接文件
示例
- 遠(yuǎn)程文件符號鏈接創(chuàng)建
# ansible test -m file -a "src=/etc/resolv.conf dest=/tmp/resolv.conf state=link"
- 遠(yuǎn)程文件信息查看
# ansible test -m command -a "ls –al /tmp/resolv.conf"
- 遠(yuǎn)程文件符號鏈接刪除
# ansible test -m file -a "path=/tmp/resolv.conf state=absent"
- 遠(yuǎn)程文件信息查看
# ansible test -m command -a "ls -al /tmp/resolv.conf"
4. copy:復(fù)制文件到遠(yuǎn)程主機(jī)
相關(guān)選項(xiàng)如下:
- backup:在覆蓋之前捕儒,將源文件備份冰啃,備份文件包含時(shí)間信息。有兩個(gè)選項(xiàng):yes|no
- content:用于替代“src”刘莹,可以直接設(shè)定指定文件的值
- dest:必選項(xiàng)阎毅。要將源文件復(fù)制到的遠(yuǎn)程主機(jī)的絕對路徑,如果源文件是一個(gè)目錄点弯,那么該路徑也必須是個(gè)目錄
- directory_mode:遞歸設(shè)定目錄的權(quán)限扇调,默認(rèn)為系統(tǒng)默認(rèn)權(quán)限
- force:如果目標(biāo)主機(jī)包含該文件,但內(nèi)容不同抢肛,如果設(shè)置為yes狼钮,則強(qiáng)制覆蓋,如果為no捡絮,則只有當(dāng)目標(biāo)主機(jī)的目標(biāo)位置不存在該文件時(shí)熬芜,才復(fù)制。默認(rèn)為yes
- others:所有的file模塊里的選項(xiàng)都可以在這里使用
- src:被復(fù)制到遠(yuǎn)程主機(jī)的本地文件福稳,可以是絕對路徑涎拉,也可以是相對路徑。如果路徑是一個(gè)目錄的圆,它將遞歸復(fù)制鼓拧。在這種情況下,如果路徑使用“/”來結(jié)尾越妈,則只復(fù)制目錄里的內(nèi)容季俩,如果沒有使用“/”來結(jié)尾,則包含目錄在內(nèi)的整個(gè)內(nèi)容全部復(fù)制梅掠,類似于rsync酌住。
示例:
- 將本地文件“/etc/ansible/ansible.cfg”復(fù)制到遠(yuǎn)程服務(wù)器
# ansible test -m copy -a "src=/etc/ansible/ansible.cfg dest=/tmp/ansible.cfg owner=root group=root mode=0644"
- 遠(yuǎn)程文件信息查看
# ansible test -m command -a "ls -al /tmp/ansible.cfg"
5. command:在遠(yuǎn)程主機(jī)上執(zhí)行命令
相關(guān)選項(xiàng)如下:
- creates:一個(gè)文件名,當(dāng)該文件存在瓤檐,則該命令不執(zhí)行
- free_form:要執(zhí)行的linux指令
- chdir:在執(zhí)行指令之前赂韵,先切換到該目錄
- removes:一個(gè)文件名,當(dāng)該文件不存在挠蛉,則該選項(xiàng)不執(zhí)行
- executable:切換shell來執(zhí)行指令祭示,該執(zhí)行路徑必須是一個(gè)絕對路徑
示例:
- 如果遠(yuǎn)端服務(wù)器的~/qiuyi_test目錄中已經(jīng)存在1.txt文件的話,則不執(zhí)行l(wèi)s操作:
$ ansible test -m command -a "chdir=~/qiuyi_test creates=~/qiuyi_test/1.txt ls"
10.139.13.80 | skipped
- 如果遠(yuǎn)端服務(wù)器的"~/qiuyi_test"目錄中已經(jīng)不存在2.txt文件的話谴古,
則在"~/qiuyi_test"路徑下執(zhí)行l(wèi)s操作:
$ ansible test -m command -a "chdir=~/qiuyi_test creates=~/qiuyi_test/2.txt ls"
10.139.13.80 | success | rc=0 >>
1.txt
qiuyi.sh
ssh
注意质涛,creates選項(xiàng)并不會創(chuàng)建文件稠歉。
6. shell:切換到某個(gè)shell執(zhí)行指定的指令,參數(shù)與command相同
與command不同的是汇陆,此模塊可以支持命令管道怒炸,同時(shí)還有另一個(gè)模塊也具備此功能:raw
示例:
# ansible raleigh -m shell -a "echo $TERM"
使用 Ansible ad-hoc 命令行接口時(shí)(與使用 Playbooks 的情況相反),尤其注意 shell 引號的規(guī)則. 比如在上面的例子中,如果使用雙引號”echo $TERM”,會求出TERM變量在當(dāng)前系統(tǒng)的值,而我們實(shí)際希望的是把這個(gè)命令傳遞 到其它機(jī)器執(zhí)行.
示例:
- 先在本地創(chuàng)建一個(gè)SHELL腳本
$ vim /home/user_00/test/qiuyi_ansible/qiuyi_test.sh
#!/bin/sh
date +%F_%H:%M:%S
$ chmod +x /home/user_00/test/qiuyi_ansible/qiuyi_test.sh
- 將創(chuàng)建的腳本文件分發(fā)到遠(yuǎn)程
$ ansible test -m copy -a "src= /home/user_00/test/qiuyi_ansible/qiuyi_test.sh dest=/home/user_00/qiuyi_test owner=user_00 mode=0755"
- 遠(yuǎn)程執(zhí)行
$ ansible test -m shell -a "~/qiuyi_test/qiuyi.sh"
10.139.13.80 | success | rc=0 >>
2017-03-22_12:27:18
7. 更多模塊
其他常用模塊毡代,比如:service阅羹、cron、yum教寂、synchronize就不一一例舉捏鱼,可以結(jié)合自身的系統(tǒng)環(huán)境進(jìn)行測試。在使用中酪耕,如果想查看某個(gè)模塊的信息导梆,可以使ansible-doc命令。
- service:系統(tǒng)服務(wù)管理
- cron:計(jì)劃任務(wù)管理
- yum:yum軟件包安裝管理
- synchronize:使用rsync同步文件
- user:系統(tǒng)用戶管理
- group:系統(tǒng)用戶組管理
# ansible-doc –l
add_host add a host (and alternatively a group) to the ansible-playbo
apt Manages apt-packages
apt_repository Manages apt repositores
assemble Assembles a configuration file from fragments
async_status Obtain status of asynchronous task
authorized_key Adds or removes an SSH authorized key
command Executes a command on a remote node
copy Copies files to remote locations.
cron Manage crontab entries.
debug Print statements during execution
easy_install Installs Python libraries
ec2 create an instance in ec2, return instanceid
facter Runs the discovery program `facter' on the remote system...
fail Fail with custom message
fetch Fetches a file from remote nodes
file Sets attributes of files
get_url Downloads files from HTTP, HTTPS, or FTP to node
git Deploy software (or files) from git checkouts
group Add or remove groups
group_by Create Ansible groups based on facts
ini_file Tweak settings in INI files
lineinfile Ensure a particular line is in a file
mail Send an email
mount Control active and configured mount points
mysql_db Add or remove MySQL databases from a remote host.
mysql_user Adds or removes a user from a MySQL database.
nagios Perform common tasks in Nagios related to downtime and notif
ohai Returns inventory data from `Ohai'
pause Pause playbook execution
ping Try to connect to host and return `pong' on success.
pip Manages Python library dependencies.
postgresql_db Add or remove PostgreSQL databases from a remote host.
postgresql_user Adds or removes a users (roles) from a PostgreSQL database..
raw Executes a low-down and dirty SSH command
script Runs a local script on a remote node
seboolean Toggles SELinux booleans.
selinux Change policy and state of SELinux
service Manage services.
setup Gathers facts about remote hosts
shell Execute commands in nodes.
slurp Slurps a file from remote nodes
subversion Deploys a subversion repository.
supervisorctl Manage the state of a program or group of programs running v
svr4pkg Manage Solaris SVR4 packages
template Templates a file out to a remote server.
user Manage user accounts
virt Manages virtual machines supported by libvirt
wait_for Waits for a given port to become accessible on a server....
yum Manages packages with the `yum' package manager
五迂烁、 Palybooks
1看尼、基礎(chǔ)介紹
Playbooks與ad-hoc相比,是一種完全不同的運(yùn)用 ansible 的方式盟步。
簡單來說藏斩,playbooks是一種簡單的配置管理系統(tǒng)與多機(jī)器部署系統(tǒng)的基礎(chǔ)。與現(xiàn)有的其他系統(tǒng)有不同之處址芯,且非常適合于復(fù)雜應(yīng)用的部署灾茁。Playbooks可用于聲明配置窜觉,更強(qiáng)大的地方在于谷炸,在 playbooks中可以編排有序的執(zhí)行過程,甚至于做到在多組機(jī)器間禀挫,來回有序的執(zhí)行特別指定的步驟旬陡。并且可以同步或異步的發(fā)起任務(wù)。
Playbooks 采用的格式是YAML语婴。
---
- hosts: webservers
vars:
http_port: 80
max_clients: 200
remote_user: root
tasks:
- name: ensure apache is at the latest version
yum: pkg=httpd state=latest
- name: write the apache config file
template: src=/srv/httpd.j2 dest=/etc/httpd.conf
notify:
- restart apache
- name: ensure apache is running
service: name=httpd state=started
handlers:
- name: restart apache
service: name=httpd state=restarted
hosts 行的內(nèi)容是一個(gè)或多個(gè)組或主機(jī)的 patterns描孟,以逗號為分隔符;
remote_user 就是賬戶名砰左;
-
vars為變量列表匿醒;
在 action 行中可以使用變量。假設(shè)在 ‘vars’ 那里定義了一個(gè)變量 ‘vhost’ 缠导,可以這樣使用它:
tasks:
- name: create a virtual host file for {{ vhost }}
template: src=somefile.j2 dest=/etc/httpd/conf.d/{{ vhost }}
-
task的目標(biāo)在于執(zhí)行一個(gè)moudle廉羔;
每一個(gè) play 包含了一個(gè) task 列表(任務(wù)列表)。一個(gè) task 在其所對應(yīng)的所有主機(jī)上(通過 host pattern 匹配的所有主機(jī))執(zhí)行完畢之后僻造,下一個(gè) task 才會執(zhí)行憋他。有一點(diǎn)需要明白的是孩饼,在一個(gè) play 之中,所有 hosts 會獲取相同的任務(wù)指令,這是 play 的一個(gè)目的所在,也就是將一組選出的 hosts 映射到 task竹挡。
在運(yùn)行playbook時(shí)(從上到下執(zhí)行)镀娶,如果一個(gè)host執(zhí)行task失敗,這個(gè)host將會從整個(gè) playbook的rotation中移除揪罕。如果發(fā)生執(zhí)行失敗的情況梯码,請修正playbook 中的錯(cuò)誤,然后重新執(zhí)行即可好啰。每一個(gè)task必須有一個(gè)名稱name忍些,這樣在運(yùn)行playbook 時(shí),從其輸出的任務(wù)執(zhí)行信息中可以很好的辨別出是屬于哪一個(gè)task的坎怪。一個(gè)基本的tasks定義:
tasks:
- name: make sure apache is running
service: name=httpd state=running
-
Handlers: 在發(fā)生改變時(shí)執(zhí)行的操作
這里有一個(gè)例子,當(dāng)一個(gè)文件的內(nèi)容被改動時(shí),重啟兩個(gè) services罢坝,‘notify’ 下列出的即是 handlers:
- name: template configuration file
template: src=template.j2 dest=/etc/foo.conf
notify:
- restart memcached
- restart apache
Handlers 也是一些task的列表,通過名字來引用搅窿,它們和一般的 task 并沒有什么區(qū)別嘁酿。Handlers是由通知者進(jìn)行 notify, 如果沒有被 notify男应,handlers 不會執(zhí)行闹司。不管有多少個(gè)通知者進(jìn)行了 notify,等到 play 中的所有 task 執(zhí)行完成之后沐飘,handlers也只會被執(zhí)行一次游桩。handlers 會按照聲明的順序執(zhí)行。
這里是一個(gè) handlers 的示例:
handlers:
- name: restart memcached
service: name=memcached state=restarted
- name: restart apache
service: name=apache state=restarted
Handlers 最佳的應(yīng)用場景是用來重啟服務(wù)耐朴,或者觸發(fā)系統(tǒng)重啟操作借卧。除此以外很少用到了。
- 執(zhí)行一個(gè)playbook
以下示例是并行的運(yùn)行playbook筛峭,并行的級別是10:
ansible-playbook playbook.yml -f 10
在執(zhí)行一個(gè) playbook 之前,想看看這個(gè) playbook 的執(zhí)行會影響到哪些 hosts,你可以這樣做:
ansible-playbook playbook.yml --list-hosts
playbook是由一個(gè)或多個(gè)“play”組成的列表铐刘,可以讓它們聯(lián)同起來按事先編排的機(jī)制執(zhí)行;所謂task無非是調(diào)用ansible的一個(gè)module影晓,而在模塊參數(shù)中可以使用變量镰吵;模塊執(zhí)行是冪等的,這意味著多次執(zhí)行是安全的挂签,因?yàn)槠浣Y(jié)果均一致疤祭。
冪等(idempotent、idempotence)是一個(gè)數(shù)學(xué)與計(jì)算機(jī)學(xué)概念饵婆,常見于抽象代數(shù)中勺馆。
在編程中,一個(gè)冪等操作的特點(diǎn)是其任意多次執(zhí)行所產(chǎn)生的影響均與一次執(zhí)行的影響相同。冪等函數(shù)谓传,或冪等方法蜈项,是指可以使用相同參數(shù)重復(fù)執(zhí)行,并能獲得相同結(jié)果的函數(shù)续挟。這些函數(shù)不會影響系統(tǒng)狀態(tài)紧卒,也不用擔(dān)心重復(fù)執(zhí)行會對系統(tǒng)造成改變。
2诗祸、Roles和include語句
假如你希望在多個(gè)play或者多個(gè)playbook中重用同一個(gè)task列表跑芳,你可以使用include 做到這一點(diǎn)。 當(dāng)我們希望為系統(tǒng)定義一個(gè)角色時(shí)直颅,使用include去包含task列表是一種很好用的方法博个。需要記住的是,一個(gè)play所要達(dá)成的目標(biāo)是將一組系統(tǒng)映射為多個(gè)角色功偿。
一個(gè) task include file 由一個(gè)普通的 task 列表所組成盆佣,像這樣:
---
# possibly saved as tasks/foo.yml
- name: placeholder foo
command: /bin/foo
- name: placeholder bar
command: /bin/bar
Include 指令看起來像下面這樣,在一個(gè) playbook 中械荷,Include 指令可以跟普通的 task 混合在一起使用:
tasks:
- include: tasks/foo.yml
Roles 基于一個(gè)已知的文件結(jié)構(gòu)共耍,去自動的加載某些 vars_files,tasks 以及 handlers吨瞎”远担基于 roles 對內(nèi)容進(jìn)行分組,使得我們可以容易地與其他用戶分享 roles 颤诀。
一個(gè)項(xiàng)目的結(jié)構(gòu)如下:
site.yml
webservers.yml
fooservers.yml
roles/
common/
files/
templates/
tasks/
handlers/
vars/
defaults/
meta/
webservers/
files/
templates/
tasks/
handlers/
vars/
defaults/
meta/
一個(gè) playbook 如下:
---
- hosts: webservers
roles:
- common
- webservers
這個(gè) playbook 為一個(gè)角色 ‘x’ 指定了如下的行為:
- 如果 roles/x/tasks/main.yml 存在, 其中列出的 tasks 將被添加到 play 中
- 如果 roles/x/handlers/main.yml 存在, 其中列出的 handlers 將被添加到 play 中
- 如果 roles/x/vars/main.yml 存在, 其中列出的 variables 將被添加到 play 中
- 如果 roles/x/meta/main.yml 存在, 其中列出的 “角色依賴” 將被添加到 roles 列表中 (1.3 and later)
- 所有 copy tasks 可以引用 roles/x/files/ 中的文件字旭,不需要指明文件的路徑。
- 所有 script tasks 可以引用 roles/x/files/ 中的腳本崖叫,不需要指明文件的路徑遗淳。
- 所有 template tasks 可以引用 roles/x/templates/ 中的文件,不需要指明文件的路徑归露。
- 所有 include tasks 可以引用 roles/x/tasks/ 中的文件洲脂,不需要指明文件的路徑斤儿。
3剧包、小結(jié)
本節(jié)只對Playbooks的基礎(chǔ)內(nèi)容進(jìn)行了簡單的介紹;而余下的如Roles依賴往果、條件控制疆液、循環(huán)操作、異步處理等相關(guān)內(nèi)容可以參考Ansible中文權(quán)威指南進(jìn)行學(xué)習(xí)陕贮,本文將不再深入介紹堕油。
六、參考文獻(xiàn)
Reference:
[1] http://www.ansible.com.cn/docs/
[2] http://sofar.blog.51cto.com/353572/1579894
[3] http://baike.baidu.com/item/ansible