ansible是一款基于SSH協定的自動化運維工具,它能多線程工作,将指令推送至各個主機執行,在需要管理或部署大量伺服器的時候,是不可或缺的神器。
我們來看看它的基本配置和用法:
先安裝:yum install ansible -y
配置檔案:/etc/ansible/ansible.cfg 這個預設配置不用動,就可以使用了。
我們來看看/etc/ansible/hosts檔案
<a href="http://s3.51cto.com/wyfs02/M00/3B/A2/wKioL1O-mxKgC5VLAAMzwFu8q_A660.jpg" target="_blank"></a>
配置/etc/ansible/hosts檔案,定義組,加入需要管理的主機
<a href="http://s3.51cto.com/wyfs02/M01/3B/A2/wKioL1O-ngSQgNJPAACk2M1g7jk950.jpg" target="_blank"></a>
由于要基于ssh協定,是以要生成ssh密鑰,把公鑰拷貝到各個主機節點上去。
ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
ssh-copy-id -i ~/.ssh/id_rsa.pub [email protected]
ansible指令基本用法:
ansible <host-pattern> [-f forks] [-m module_name] [-a args]
<host-pattern>:主機模式,可以用組名
[-f forks]: 指定啟用的線程數,預設5個。
[-m module_name]:子產品名稱,預設為(command)。
-a:參數
比如我們要顯示這三個主機的時間。
ansible all -a 'date'
<a href="http://s3.51cto.com/wyfs02/M02/3B/A2/wKioL1O-oMHR_K5uAAEQY9fNoKw013.jpg" target="_blank"></a>
給全部主機,添加一個cron任務,這裡可以調用cron子產品來實作。
ansible all -m cron -a 'name="sync time from 192.168.1.1"minute="*/3"job="/usr/sbin/ntpdate 192.168.1.1 &>/dev/null"'
<a href="http://s3.51cto.com/wyfs02/M02/3B/A3/wKiom1O-pRvTGpapAAGXpog08n0500.jpg" target="_blank"></a>
檢視是否添加成功。
ansible all -a 'crontab -l'
<a href="http://s3.51cto.com/wyfs02/M00/3B/A3/wKiom1O-pbejNwS4AAIIHbF8BPk348.jpg" target="_blank"></a>
如果我們要批量安裝軟體,可以調用yum子產品,如果不知道用法,可以man ansible.yum
給全部主機安裝vsftpd。
ansible all -m yum -a'name=vsftpd state=present'
<a href="http://s3.51cto.com/wyfs02/M01/3B/A3/wKiom1O-qB3DTGI0AAKXTNIno5s451.jpg" target="_blank"></a>
再來幾個例子:
1、在每個節點上建立tuchao使用者
ansible all -a 'useradd tuchao'
ansible all -a 'id tuchao'
<a href="http://s3.51cto.com/wyfs02/M01/3B/A3/wKiom1O-q9jyi9y1AAJMSWw6qnY136.jpg" target="_blank"></a>
2、在每個節點建立/tmp/tuchaodir/其屬主屬組都為tuchao使用者。
ansible all -a 'mkdir /tmp/tuchao'
ansible all -a 'chown -R tuchao.tuchao /tmp/tuchao'
<a href="http://s3.51cto.com/wyfs02/M00/3B/A4/wKiom1O_PIzB3T7WAAGX1NoaicA938.jpg" target="_blank"></a>
3、複制/etc/fstab到/tmp/tuchao.
<a href="http://s3.51cto.com/wyfs02/M00/3B/A3/wKioL1O_PN3DFQyHAAGGkb1c4EE177.jpg" target="_blank"></a>
基本用法差不多了,有問題歡迎與我交流QQ:1183710107
本文轉自qw87112 51CTO部落格,原文連結:http://blog.51cto.com/tchuairen/1436935