四、搭建Ansible环境
4.1 安装ansible
-
yum安装
yum install ansible ansible version
-
源码编译安装
-
二进制安装
4.2 配置ansible
-
拷贝ansible目录(这里我们使用当前路径去加载ansible的配置文件)
cp -a /etc/ansible/ /opt
-
配置主机清单
[redhat@master ansible]$ cat hosts node1 node2
-
修改ansible配置文件
[redhat@master ansible]$ cat ansible.cfg [defaults] inventory = /opt/ansible/hosts ask_pass = False roles_path = /opt/ansible/roles remote_user = devops log_path = /opt/ansible/ansible.log [privilege_escalation] become=True become_method=sudo become_user=root become_ask_pass=False [ssh_connection] ssh_args = -C -o ControlMaster=auto -o ControlPersist=60s host_key_checking = False
4.3 环境配置
-
修改被控端主机名(实验环境下,生产环境一般都有主机名)
# node1 [root@node1 ~]# hostnamectl set-hostname node1.example.com # node2 [root@node2 ~]# hostnamectl set-hostname node2.example.com
-
配置hosts文件(ansible主控端)
[root@master ~]# echo "192.168.1.100 master.example.com master" >> /etc/hosts [root@master ~]# echo "192.168.1.101 node1.example.com node1" >> /etc/hosts [root@master ~]# echo "192.168.1.102 node2.example.com node2" >> /etc/hosts [root@master ~]# ping node1 [root@master ~]# ping node2
-
在被控端创建ansible远程用户
# node1 [root@node1 ~]# useradd devops [root@node1 ~]# echo "123456" | passwd --stdin devops # node2 [root@node2 ~]# useradd devops [root@node2 ~]# echo "123456" | passwd --stdin devops
-
配置ssh免密(ansible主控端)
[root@master ~]# ssh-keygen [root@master ~]# ssh-copy-id devops@node1 [root@master ~]# ssh-copy-id devops@node2
-
在被控端配置devops用户sudo提权
# node1 [root@node1 ~]# echo "devops ALL=(root) NOPASSWD: ALL" >> /etc/sudoers.d/devops # node2 [root@node2 ~]# echo "devops ALL=(root) NOPASSWD: ALL" >> /etc/sudoers.d/devops
-
检测连通性
[root@master ansible]# ansible all -m ping
全部返回绿色代表成功,Ansible环境就搭建好了。