(四)ansible 通过堡垒机访问内网服务器
场景:
在ansible的使用过程中,存在这样的场景,ansible所在的管理节点与被管理的机器需要 通过一个跳板机才能连接,无法直接连接。要解决这个问题,并不需要在 ansible里做什么处理,而是在ssh连接层面解决这个问题。
1,ansible服务器公钥至堡垒机
2,导出堡垒机公钥至内网机
3,配置/root/.ssh/config
Host bastion
HostName xx.xx.xx.xx
Port 7022
IdentityFile /root/.ssh/id_rsa
ProxyCommand none
User xiaoer
Host mtr_ops
HostName 192.168.4.241
ServerAliveInterval 60
TCPKeepAlive yes
#ProxyCommand connect-proxy -S 192.168.1.126:1080 %h %p #这种方法需要安装connect-proxy,并配置ssh端口转发:ssh -NfD 0.0.0.0:1080 bastion
ProxyCommand ssh bastion -W %h:%p # bastion对应 Host bastion
ControlMaster auto
ControlPersist 600
User opadmin
IdentityFile /root/.ssh/id_rsa_aly_opadmin
Port 22
4,配置/etc/ansible/ansible.cfg
[defaults]
transport = ssh #通信机制.默认 值为smart,如果本地系统支持 ControlPersist技术的话,将会使用(基于OpenSSH)'ssh',如果不支持将使用'paramiko',其他传输选项‘local’,‘chroot’,’jail’等等
ssh_args = -o ControlMaster=auto -o ControlPersist=5d
host_key_checking = False
remote_user = root
private_key_file = /root/.ssh/id_rsa_aly_opadmin #指定用来访问服务器的私钥
deprecation_warnings = False
[ssh_connection]
ssh_args = -F /root/.ssh/config #指定ssh配置文件
pipelining = True
scp_if_ssh = True
5,hosts配置
[mtr]
x.x.x.x ansible_ssh_host=mtr_ops #mtr_ops 对应/root/.ssh/config 中的Host mtr_ops
6,测试
ansible x.x.x.x -m ping
x.x.x.x | SUCCESS => {
"changed": false,
"ping": "pong"
}
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步