Ansible的使用
介紹:
Ansible是爲了更方便、快捷的進行配置管理。用Ansible可以將平常複雜的配置工作變得簡單,更加標準化且更容易控制。Ansible可以實現100、1000臺批量部署等。
Ansible特點:
(1)部署簡單,只需在主控端部署 Ansible 環境,被控端無需做任何操作。(Ansible只需要在一臺普通的服務器上運行即可,不需要在被管控的服務器上安裝客戶端)
(2)使用 SSH協議對設備進行管理。
(3)使用python編寫的,維護更簡單
操作:
Centos7安裝Ansible
[root@mail ~]# yum install ansible –y
rpm -Uvh http://mirrors.ustc.edu.cn/fedora/epel/6/x86_64/epel-release-6-8.noarch.rpm
#鏡像源,可以先按裝鏡像源,再安裝ansible,這裏是直接安裝的。
-
安裝完後,ansible的默認配置文件路徑爲
[root@mail ~]# ls /etc/ansible
ansible.cfg hosts roles - 在Ansible主機與被管理機之間做免密登陸,方便管理被管理的機器
[root@mail ~]# ssh-keygen Generating public/private rsa key pair. Enter file in which to save the key (/root/.ssh/id_rsa): yes
[root@mail ~]# cd /root/.ssh
[root@mail .ssh]# ls
authorized_keys id_rsa id_rsa.pub known_hosts
[root@mail .ssh]# ssh-copy-id -i id_rsa.pub 111.231.144.197 #將生成的公鑰拷貝到遠程機器上
4.Ansible的簡單使用
[root@mail ~]# cd /etc/ansible/
[root@mail ansible]# ls
ansible.cfg hosts roles
[root@mail ansible]# vim hosts
##默認hosts中可以配置分組,我們可以定義各種ip及規則。在hosts中添加以下內容:
[manage-other]
111.231.144.197
127.0.0.1
在命令行執行以下命令,查看磁盤使用情況:
[root@mail ansible]# ansible manage-other -m shell -a 'df -h' #查看hosts文件中自定義組中機器的磁盤使用情況
[root@mail ansible]# ansible all -m shell -a 'df -h' #查看hosts文件中所有組中機器的磁盤使用情況
命令:ansible 分組 -m 模塊名 -a 模塊參數
(1)在遠程的機器上執行命令
[root@mail ansible]# ansible manage-other -m shell -a uptime
[root@mail ansible]# ansible manage-other -m command -a uptime
(2)在遠程主機上執行主控端的shell腳本(array.sh在ansible所在的機器上)類似scp+shell命令。[root@mail SHELL]# ansible manage-other -m script -a array.sh
(3)實現主控端向目標主機拷貝文件(ansible所在機器向所控制的遠程機器拷貝文件,類似scp命令)
[root@mail SHELL]# ansible manage-other -m copy -a "src=array.sh dest=/root/array.sh"
[root@mail SHELL]# ll /root/array.sh
-rw-r--r-- 1 root root 323 Oct 25 13:01 /root/array.sh
(4)實現主控端向目標主機拷貝文件(ansible所在機器向所控制的遠程機器拷貝文件,類似scp命令)並且修改文件的權限
[root@mail SHELL]# ansible manage-other -m copy -a "src=array.sh dest=/root/array.sh owner=root group=root mode=777"
[root@mail SHELL]# ll /root/array.sh
-rwxrwxrwx 1 root root 323 Oct 25 13:01 /root/array.sh #權限發生改變
注意:遠程主機的用戶存在和組存在,否則拷貝失敗。
(5)實現在遠程主機下載指定url內容到遠程主機上[root@mail SHELL]# ansible manage-other -m get_url -a "url=http://www.baidu.com dest=/root/index.html"
總結:
command:在遠程執行權限內的shell命令.
script:在遠程主機執行控制端的腳本文件.
shell:在控制端執行遠程主機上的shell腳本文件.