本文档将引导您完成在 CentOS 7.9 系统上安装 Ansible、设置 inventory 文件、配置 SSH 无密码登录等步骤。
安装 Ansible
-
使用 Yum 安装 Ansible:
sudo yum install ansible -y
配置 Ansible
-
创建 Ansible 工作目录:
mkdir -p ~/ansible
-
创建 Ansible 配置文件 ansible.cfg:
cat > ~/ansible/ansible.cfg << EOF [defaults] inventory = ./hosts remote_user = root host_key_checking = False EOF
-
创建 Inventory 文件 hosts:
cat > ~/ansible/hosts << EOF [all] 192.168.2.3 192.168.2.4 [master] 192.168.2.3 [worker] 192.168.2.4 EOF
SSH 无密码登录设置
-
生成 SSH 密钥:
ssh-keygen -t rsa -b 2048
按照提示操作,设置密码或保持空白以创建无密码密钥。
-
分发 SSH 公钥到所有主机:
ansible all -m authorized_key -a "user=root key='{{ lookup('file', '/root/.ssh/id_rsa.pub') }}' path=/root/.ssh/authorized_keys manage_dir=no" --ask-pass -c paramiko
输入 SSH 密码以完成分发。
修改 Ansible 全局配置(可选)
-
关闭主机密钥检查和设置日志路径:
sed -i "s@#host_key_checking = False@host_key_checking = False@g" /etc/ansible/ansible.cfg sed -i "s@#log_path = /var/log/ansible.log@log_path = /var/log/ansible.log@g" /etc/ansible/ansible.cfg
-
指定 Ansible 使用的私钥文件:
sed -i "s@#private_key_file = /path/to/file@private_key_file = /root/.ssh/id_rsa@g" /etc/ansible/ansible.cfg
测试 Ansible 配置
-
测试 Ansible 与所有主机的连接:
ansible all -m ping
这份文档涵盖了从安装 Ansible 到配置和测试 SSH 连接的基本步骤。请根据实际情况进行调整和优化。