2010年左右1,當時系統多數運行在小型機上,如HP、Sun、IBM小型機,如某系統當時使用10臺小型機,但隨着業務量不斷增加,前幾年去IOE的火熱進行,開源技術的不斷髮展,原先使用10臺小型機的系統在現在可能已暴漲似增漲到使用百來臺X86 Linux主機。html
如何運維成百上千臺的主機成爲一個挑戰,本人經歷過以下3階段:python
最近一項目做者使用ansible批量管理了200多臺PC Server,所作事情簡單描述以下:linux
ansible爲什麼如此強大且好用,做者決定使用實戰方式帶領初學者迅速掌握此工具,從入門到精通。shell
本示例準備了兩臺虛擬機,操做系統版本爲Centos 7.6,主機均採用最小化模式安裝。centos
% cat /etc/redhat-release CentOS Linux release 7.6.1810 (Core) % cat /root/anaconda-ks.cfg ... %packages @^minimal @core kexec-tools ...
兩主機IP地址以下:ruby
% cat /etc/hosts 127.0.0.1 localhost localhost.localdomain localhost4 localhost4.localdomain4 ::1 localhost localhost.localdomain localhost6 localhost6.localdomain6 okd-l01 192.168.18.2 okd-i01 192.168.18.3
對於非RHEL系列主機安裝ansible可參考官方文檔Installation Guide。運維
okd-l01主機能鏈接英特網,下面將在此主機上安裝ansible軟件。dom
% rpm -ivh https://mirrors.tuna.tsinghua.edu.cn/epel/epel-release-latest-7.noarch.rpm
% yum -y install ansible
% ansible --version ansible 2.7.5 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, Apr 9 2019, 14:30:50) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)]
okd-l01與okd-i01均做爲ansible被管主機,需知足以下條件:python2.7
主機若關閉了selinux(/etc/selinux/config文件中設置SELINUX=disabled
並重啓)則無需安裝libselinux-python軟件包,不然需安裝此軟件包以免copy/file等模塊報錯。ssh
% yum -y install libselinux-python
假設咱們需在遠程主機okd-i01上建立/test目錄,若採用ssh方式,咱們可在okd-l01執行命令:
ssh 192.168.18.3 'mkdir /test'
那麼,採用ansible如何作一樣的事情呢?首先需將被控主機的主機名或ip地址寫入到清單文件(inventory)中,做者在okd-l01上使用root用戶3爲本實驗在/root/test目錄下建立清單文件hosts4:
% mkdir /root/test && cd /root/test % echo 192.168.18.3 > hosts
如同ssh命令相似,咱們其替換爲ansible後執行以下命令便可:
ssh
命令替換爲ansible
命令;-i hosts
參數指定清單文件名爲hosts,然後緊接着輸入ansible管理的被控主機ip地址;-a
參數後接執行的命令mkdir /test
;-k
參數提示輸入被控主機的用戶密碼。% ansible -i hosts 192.168.18.3 -a"mkdir /test" -k # 因做者採用root用戶執行,故默認此命令將使用root鏈接到遠程主機, # 此處需輸入被控主機的ssh密碼: SSH password: # 告警信息: [WARNING]: Consider using the file module with state=directory rather than running mkdir. If you need to use command because file is insufficient you can add warn=False to this command task or set command_warnings=False in ansible.cfg to get rid of this message. # 命令返回結果: 192.168.18.3 | CHANGED | rc=0 >>
如上爲最簡單的ansible使用方式,其僅是替換爲以前運行的ssh命令,接下來做者將詳細講解用於生產時所需知曉的必要知識。