ansible 的安装配置

时间:2022-10-25 18:07:09

Ansible中文权威指南:https://ansible-tran.readthedocs.io

环境准备:

1 ansible      192.168.1.10 管理机器
2 web1         192.168.1.11 托管机器
3 web2         192.168.1.12 托管机器
4 db1            192.168.1.21 托管机器
5 db2            192.168.1.22 托管机器
6 cache         192.168.1.33 托管机器

一、在真机上ftp配置下配置ansible的yum源供ansible虚拟机使用:

 1 [root@ansible ~]# cat /etc/yum.repos.d/centos7.repo
 2 [centos]
 3 name=centos7
 4 baseurl=ftp://192.168.1.254/centos7
 5 enabled=1
 6 gpgcheck=0
 7 [ansible]
 8 name=ansible_repo
 9 baseurl=ftp://192.168.1.254/ansible
10 enabled=1
11 gpgcheck=0

二、在ansible管理机器上安装ansible

[root@ansible ~]# yum install ansible -y

三、查看ansible的版本信息

1 [root@ansible ~]# ansible --version
2 ansible 2.4.2.0
3   config file = /etc/ansible/ansible.cfg
4   configured module search path = [u'/root/.ansible/plugins/modules', u'/usr/share/ansible/plugins/modules']
5   ansible python module location = /usr/lib/python2.7/site-packages/ansible
6   executable location = /usr/bin/ansible
7   python version = 2.7.5 (default, Aug  4 2017, 00:39:18) [GCC 4.8.5 20150623 (Red Hat 4.8.5-16)]

四、配置主机名解析:

1 [root@ansible ~]# vim /etc/hosts
2 127.0.0.1   localhost localhost.localdomain localhost4 localhost4.localdomain4
3 ::1         localhost localhost.localdomain localhost6 localhost6.localdomain6
4 192.168.1.10     ansible
5 192.168.1.11     web1
6 192.168.1.12     web2
7 192.168.1.21     db1
8 192.168.1.22     db2
9 192.168.1.33     cache

[root@ansible ~]# for i in 11 12 21 22 33; do scp  /etc/hosts 192.168.1.${i}:/etc/; done
[root@ansible ~]# ssh-keygen -t rsa -b 2048 -N ''  

五、修改配置文件:

1 [root@ansible ~]# vim /etc/ssh/ssh_config 
2 StrictHostKeyChecking no           //禁止首次登录时交互验证
1  [root@ansible ~]# vim /etc/ansible/ansible.cfg 
2  inventory      = /etc/ansible/hosts     //去掉注释,指定主机分组的配置文件

六、指定ansible管理的主机分组:

 1 [root@ansible ~]# vim /etc/ansible/hosts
 2 [web]
 3 web[1:2]
 4 
 5 [db]
 6 db1
 7 db2
 8 
 9 [app:children]
10 web
11 db
12 
13 [app:vars]
14 ansible_ssh_user="root"            //授权远程登陆管理主机的用户
15 ansible_ssh_pass="123456"    //授权远程登陆管理主机的用户密码
16 ansible_ssh_port="22"             //端口设置
17 
18 [other]
19 cache   ansible_ssh_user="root" ansible_ssh_pass="123456"  

七、给所有主机部署密钥

1 [root@ansible ~]# ansible all -m authorized_key -a "user=root exclusive=true manage_dir=true key='$(< /root/.ssh/id_rsa.pub)'" -k

八、测试:

 1 [root@ansible ~]# ansible all -m ping
 2 db2 | SUCCESS => {
 3     "changed": false, 
 4     "ping": "pong"
 5 }
 6 web1 | SUCCESS => {
 7     "changed": false, 
 8     "ping": "pong"
 9 }
10 db1 | SUCCESS => {
11     "changed": false, 
12     "ping": "pong"
13 }
14 cache | SUCCESS => {
15     "changed": false, 
16     "ping": "pong"
17 }
18 web2 | SUCCESS => {
19     "changed": false,  

至此,ansible基本就部署完成了!!!