\[10.Shell\]
环境:RHEL/CentOS Stream 10 / Rocky Linux,使用dnf包管理器,搭建 ansible 控制节点,需要三台虚拟机 管理 node1、node2 两台被管机器
配置本地域名解析,把 IP 和主机名做映射,后续直接写node1/node2代替 IP,不用每次输入长 IP。
shell
vim /etc/hosts
192.168.
132.130 node1
192.168.142.131 node2
免密登录设置
shell
ssh-keygen -t rsa
ls .ssh
shell
ssh-copy-id node1
ssh-copy-id node2
ssh-keygen -t rsa:生成 RSA 格式的 ssh 公私密钥对,一路回车即可,密钥默认存放在~/.ssh/目录。- 私钥:
id_rsa(控制节点保留,不要泄露) - 公钥:
id_rsa.pub(分发到被管理机器)
- 私钥:
ls .ssh:查看生成的密钥文件是否存在。ssh-copy-id node1:把本机公钥推送至 node1,写入 node1 的~/.ssh/authorized_keys,实现 ssh 免密码登录 node1。ssh-copy-id node2:同理,给 node2 配置免密。
安装源epel sshpass ansible
shell
dnf install https://mirrors.aliyun.com/epel/epel-release-latest-10.noarch.rpm
dnf repolist
dnf install ansible-core -y
yum install-y sshpass
初始化ansible配置创建目录
shell
ansible --version
ansible-config init --disabled > ./anaconda-ks.cfg
makdir ansible
cd ansible
ansible --version:查看 ansible 版本,验证安装是否成功。ansible-config init --disabled > ./anaconda-ks.cfg:导出一份全部默认禁用的 ansible 完整配置模板文件。mkdir ansible:创建 ansible 独立工作目录,隔离项目文件。cd ansible:进入工作目录,后续所有操作在此目录执行。
shell
vim ansible.cfg
[defaults]
inventory=inventory
shell
vim inventory
node1
node2
ansible.cfg是 ansible 主配置文件。inventory=inventory:指定主机清单文件名字叫inventory,存放在当前目录,inventory 文件定义要管理哪些机器。
连通性测试
shell
ansible all -k -m ping
all:代表清单里所有主机(node1+node2)-k:(ask_password) 提示输入 ssh 密码;如果已经配置 ssh 免密,这个参数可以去掉。-m ping:调用ping模块,ansible 内置模块,不是系统 ping 命令,用来检测 ansible 能不能连通目标主机。
✅成功返回:SUCCESS;失败返回报错,排查 ssh、网络、inventory、hosts 解析
例如:
shell
node2 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": false,
"ping": "pong"
}
node1 | SUCCESS => {
"ansible_facts": {
"discovered_interpreter_python": "/usr/bin/python3"
},
"changed": false,
"ping": "pong"
}