一、什么是Ansible
Ansible是一个可以批量化、自动高效管理多台Linux主机的自动化运维工具,并且在被管理主机上无需安装代理,可直接通过ssh协议完成远程管理。
二、Ansible应用案例
通过Ansible批量部署nginx,并且自动化完成多台主机的nginx相关配置(端口号、站点根目录、权限等)
环境
Ansible管理主机:192.168.0.201
目标主机:192.168.0.172 192.168.0.173
三、关键步骤
1、配置ssh免密登录
参考本文 百哥:Linux批量免密码SSH登录案例
2、安装Ansible
yum install -y ansible
3、配置主机清单,也就是要管理的主机
vim /etc/ansible/hosts
[web-server]
192.168.0.172
192.168.0.173
在文件的末尾,写上主机组的名称和ip地址
4、测试连通性以及Ansible模块是否正常
这里使用Ansible的ping模块,如果收到pong的回应,说明被管理主机的连通性ok,且Ansible已经可以正常使用。
[root@localhost ~]# ansible web-server -m ping
192.168.0.173 | SUCCESS => {
"changed": false,
"ping": "pong"
}
192.168.0.172 | SUCCESS => {
"changed": false,
"ping": "pong"
}
这里测试shell模块,可以将shell命令推送至目标主机执行
5、远程批量安装nginx
5.1 所有主机安装nginx的官方yum源
ansible web-server -m shell -a "rpm -ivh http://nginx.org/packages/centos/7/noarch/RPMS/nginx-release-centos-7-0.el7.ngx.noarch.rpm"
5.2 安装nginx
[root@localhost ~]# ansible web-server -m shell -a "yum install nginx -y"
安装成功(返回信息较长,略去后面的部分)
6、配置nginx
管理主机上的nginx配置文件及测试主页文件如下图。
接下来要将这两个文件推送至所有目标主机,使用Ansible的copy模块即可。
[root@localhost ~]# ansible web-server -m shell -a "mkdir /web"
ansible web-server -m copy -a "src=/web/index.html dest=/web/index.html"
ansible web-server -m copy -a "src=/etc/nginx/conf.d/test-ansible.conf dest=/etc/nginx/conf.d/test-ansible.conf"
ansible web-server -m shell -a "systemctl start nginx"
完成nginx的批量部署,在所有主机均可访问到测试主页
点击了解更多技术资料和免费学习视频请加入讨论群:662736393
欢迎关注百哥IT技术专栏,联系QQ:1443262302
针对本技术点问题,欢迎加Q一起讨论学习