Ansible实现批量服务器免密登录配置详解

Ansible实现批量服务器免密登录配置详解
在现代IT运维中,自动化管理工具的应用已经成为提高效率和减少人为错误的关键手段。Ansible作为一款广受欢迎的自动化运维工具,以其简洁、易用和强大的功能赢得了众多运维工程师的青睐。本文将详细介绍如何使用Ansible实现批量服务器的免密登录配置,帮助读者在实际工作中提高运维效率。
一、Ansible简介
Ansible是一款基于Python开发的自动化运维工具,它通过SSH协议与远程服务器进行通信,无需在目标服务器上安装任何代理软件。Ansible的核心组件包括:
Inventory文件
:用于定义和管理目标服务器列表。
Playbooks
:用于编写自动化任务和剧本。
Modules
:预定义的模块,用于执行各种操作。
二、准备工作
在开始配置免密登录之前,需要完成以下准备工作:
安装Ansible
:
sudo apt update
sudo apt install ansible
检查Ansible版本
:
ansible –version
生成SSH密钥
:
ssh-keygen -t rsa -b 4096
三、配置免密登录
编辑Inventory文件
:
Inventory文件用于定义目标服务器的分组和管理信息。默认情况下,Inventory文件位于
/etc/ansible/hosts
,也可以自定义Inventory文件。
[group1]
server1 ansible_ssh_host=192.168.1.1 ansible_ssh_user=root
server2 ansible_ssh_host=192.168.1.2 ansible_ssh_user=root

[group2]
server3 ansible_ssh_host=192.168.1.3 ansible_ssh_user=root
server4 ansible_ssh_host=192.168.1.4 ansible_ssh_user=root
复制SSH公钥到目标服务器
:
使用
ssh-copy-id
命令将本地生成的SSH公钥复制到目标服务器上。
ssh-copy-id root@192.168.1.1
ssh-copy-id root@192.168.1.2
ssh-copy-id root@192.168.1.3
ssh-copy-id root@192.168.1.4
也可以使用Ansible的
authorized_key
模块自动化这一过程:
– name: Add SSH key to remote servers
hosts: all
tasks:
– name: Add my public key to authorized_keys
authorized_key:
user: root
state: present
key: “{{ lookup(‘file’, ‘/home/youruser/.ssh/id_rsa.pub’) }}”
验证免密登录
:
通过Ansible的
ping
模块验证目标服务器是否可达。
ansible group1 -m ping
ansible group2 -m ping
四、编写Ansible Playbook
为了更高效地管理批量服务器的免密登录配置,可以编写一个Ansible Playbook。
—
– name: Configure SSH key-based authentication
hosts: all
become: yes
tasks:
– name: Ensure SSH directory exists
file:
path: /root/.ssh
state: directory
mode: ‘0700’

– name: Copy SSH public key to remote servers
copy:
src: /home/youruser/.ssh/id_rsa.pub
dest: /root/.ssh/authorized_keys
mode: ‘0600’

– name: Disable password authentication
lineinfile:
path: /etc/ssh/sshd_config
regexp: ‘^#?PasswordAuthentication’
line: ‘PasswordAuthentication no’
notify:
– Restart SSH service

– name: Disable root login via SSH
lineinfile:
path: /etc/ssh/sshd_config
regexp: ‘^#?PermitRootLogin’
line: ‘PermitRootLogin no’
notify:
– Restart SSH service

handlers:
– name: Restart SSH service
service:
name: sshd
state: restarted
五、执行Playbook
使用以下命令执行Playbook:
ansible-playbook -i /path/to/your/inventory/file configure_ssh.yml
六、常见问题与解决方案
SSH连接失败
:
确保目标服务器的SSH服务已启动。
检查Inventory文件中的主机地址和用户信息是否正确。
确保本地SSH密钥已正确生成并复制到目标服务器。
权限问题
:
确保目标服务器上的
.ssh
目录和
authorized_keys
文件的权限设置正确。
sshd_config配置错误
:
确保修改的
sshd_config
文件语法正确,并重启SSH服务使配置生效。
七、结语
通过本文的详细讲解,相信读者已经掌握了如何使用Ansible实现批量服务器的免密登录配置。这不仅大大提高了运维效率,还减少了因手动操作带来的错误风险。在实际应用中,可以根据具体需求对Playbook进行定制和扩展,进一步提升自动化管理的水平。
Ansible的强大功能和灵活性使其成为现代IT运维中不可或缺的工具之一。希望本文能为读者的实际工作带来帮助,开启高效自动化运维的新篇章。