如何通过Ansible经跳转服务器连接需sudo权限的内部远程主机?
解决方案:通过Ansible实现多级SSH跳转并获取内部服务器root权限
问题分析
你当前的playbook卡顿是因为嵌套的ssh+sudo su -存在交互逻辑问题:
sudo su -启动新登录shell后,后续命令没有正确传入该shell上下文- SSH连接内部主机时未自动跳过无密码登录的验证环节
- 嵌套shell的TTY控制逻辑混乱导致操作挂起
方案一:利用Ansible原生SSH跳转(推荐)
Ansible支持通过inventory配置跳转主机(bastion),无需手动编写嵌套shell脚本:
1. 配置Inventory
在你的inventory文件中添加跳转主机与内部服务器的条目:
[remote_host] bastion.example.com ansible_user=非root用户 ansible_password=你的登录密码 ansible_become=yes ansible_become_user=root ansible_become_method=sudo [internal_servers] 1.1.1.1 ansible_user=adm ansible_become=yes ansible_become_user=root ansible_become_method=sudo ansible_ssh_common_args="-o ProxyJump=root@bastion.example.com"
2. 编写简化Playbook
直接针对内部服务器编写任务,Ansible会自动处理多级跳转:
--- - name: 在内部服务器执行目标操作 hosts: internal_servers tasks: - name: 执行目标Linux命令 command: 你的目标命令 - name: 运行指定playbook command: ansible-playbook /path/to/run_role.yml
关键配置说明
ProxyJump:自动完成ansible -> root@bastion -> adm@1.1.1.1的跳转流程ansible_become:在内部服务器上自动通过sudo切换到root,前提是adm用户在内部服务器的/etc/sudoers中配置了NOPASSWD: ALL
方案二:修正现有Shell脚本
如果必须保留原有嵌套shell的方式,需调整命令逻辑解决交互问题:
--- - name: Connect to remote host and execute commands on internal server hosts: remote_host become: yes become_user: root tasks: - name: SSH到内部服务器并以root身份执行命令 shell: | ssh -o StrictHostKeyChecking=no -tt adm@1.1.1.1 'sudo -i ansible-playbook /path/to/run_role.yml' args: executable: /bin/bash
修正点说明
sudo -i:直接以root登录shell执行命令,替代sudo su -后输入命令的方式,避免上下文丢失-o StrictHostKeyChecking=no:跳过首次连接的主机密钥确认,避免交互卡顿- 将命令直接作为SSH参数传递,确保命令在目标shell中正确执行
前置条件验证
确保以下配置已完成:
- bastion主机的非root用户可无密码
sudo su -到root(/etc/sudoers添加:非root用户 ALL=(ALL) NOPASSWD: ALL) - bastion主机的root用户可无密码SSH到内部服务器的
adm用户(将bastion的root公钥添加到内部服务器adm用户的~/.ssh/authorized_keys) - 内部服务器的
adm用户可无密码sudo -i到root(/etc/sudoers添加:adm ALL=(ALL) NOPASSWD: ALL)
内容的提问来源于stack exchange,提问作者amitk
相关产品推荐
相关产品推荐

