一、实验环境
系统镜像:CentOS-7-x86_64-DVD-1810
VMware虚拟机:VMware® Workstation 16 Pro 16.1.0 build-17198959
Nginx源码包:nginx-1.23.4.tar.gz
Master:192.168.42.100 ##控制服务器
Web1:192.168.42.110 ##终端服务器
Web2:192.168.42.120 ##终端服务器
二、关闭防火墙、SELinux
systemctl stop firewalld ##临时关闭防火墙(重启失效)
systemctl disable firewalld ##关闭防火墙开机自启
setenforce 0 ##临时关闭SELINUX
vi /etc/selinux/config ##配置文件永久关闭SELINUX
SELINUX=disabled
getenforce ##验证SELINUX状态
Master:192.168.42.100 ##控制服务器
Web1:192.168.42.110 ##终端服务器
Web2:192.168.42.120 ##终端服务器
三、安装Ansible
yum search ansible ##搜索Ansible安装包
yum -y install centos-release-ansible-29.noarch ##安装最新版本
yum -y install ansible ##安装Ansible服务
ansible --version ##查看Ansible版本
四、Ansible配置清单(inventory)的使用
1、配置操作群组"Webs":vim /etc/ansible/hosts
格式1:
[Webs] ##自定义群组名"Webs"
192.168.42.110:22 ansible_ssh_user=root ansible_ssh_pass=redhat ##ip、账号、密码
192.168.42.120:22 ansible_ssh_user=root ansible_ssh_pass=redhat ##ip、账号、密码
格式2:
[Webs] ##自定义群组名"Webs"
192.168.42.110 ##终端服务器"Webs1"
192.168.42.120 ##终端服务器"Webs2"
[Webs:vars] ##群组"Webs"的"vars"变量
ansible_ssh_user=root ##终端服务器的ssh登录账号
ansible_ssh_pass=redhat ##终端服务器的ssh登录密码
格式3:
[Webs] ##自定义群组名"Webs"
beta.example.org ##终端服务器的主机域名
192.168.42.1[10:20] ##终端服务器的IP网段
2、关闭ssh登录验证提示:vim /etc/ansible/ansible.cfg
第5行:#forks=5 ##默认并发数为5
第26行:#remote_port = 22 ##默认通过ssh服务的22号端口访问终端服务器
第71行:#host_key_checking = False ##关闭ssh登录验证提示
第107行:#remote_user = root ##默认使用root账号ssh登陆终端服务器
ansible Webs -m ping ##测试连通性
3、配置ssh免密登录
ssh-keygen ##生成密钥对
ssh-copy-id root@192.168.42.110 ##复制公钥到终端服务器
ssh-copy-id root@192.168.42.120 ##复制公钥到终端服务器
ansible Webs -m ping ##测试终端服务器的连通性
五、Ansible的常用模块
ansible的命令格式
ansible 群组/主机(Webs/192.168.42.110) -m 模块(默认为command) -a 模块的参数 -f 并发数(默认为5) -i 清单(默认位置在“/etc/ansible/hosts”)
默认模块:command(可以直接在终端服务器上执行命令,并将结果返回控制服务器
不支持管道,重定向等shell的特性)
ansible-doc -l ##查看Ansible支持的所有模块列表
ansible-doc -s yum ##查看yum模块命令的配置参数信息
1、ping模块:测试控制服务器到终端服务器的连通性
ansible Webs -m ping
ansible 192.168.42.110 -m ping
2、shell模块:管理终端服务器执行shell命令
ansible Webs -m shell -a 'ip a' ##查看终端服务器的网卡信息
ansible Webs -m shell -a 'ip a s ens32' ## ##查看终端服务器"ens32"网卡信息
ansible Webs -m shell -a 'ss -ntl | grep 22' ## ##查看终端