Ansible機器的 /root/.ssh/config 配置如下即可:
Host 目標機器IP User root IdentityFile=/root/.ssh/xxx_id_rsa ProxyCommand ssh -qaY -i /root/.ssh/id_rsa root@跳板機IP 'nc -w 14400 %h %p' ~
Host 目標機器IP.*
IdentityFile=/root/.ssh/lan
ProxyCommand ssh root@跳板機IP -W %h:%p
ServerAliveInterval 30
ControlMaster no
ControlPath /tmp/%r@%h-%p.ssh
ControlPersist 600
Ansible結合跳板機控制遠程服務器
在ansible的使用過程中,存在這樣的場景,ansible所在的管理節點與被管理的機器需要 通過一個跳板機才能連接,無法直接連接。網上搜了一下,要解決這個問題,並不需要在 ansible里做什么處理,而是在ssh連接層面解決這個問題。
比如,
-
我們有三類節點:
-
管理節點,admin.example.com,是執行ansible命令的服務器
-
被管理的節點,internal1.example.com, internal2.example.com
-
跳板機,bastion.example.com
-
-
管理節點不能直連 internal1 & internal2,需要通過跳板機建立連接。
-
管理節點連接跳板機的方式如下:
ssh -i keyfile_bastion -p 12345 user@bastion.example.com -
從跳板機連接internal節點的方式如下:
ssh -i keyfile_internal -p 23456 user@internal1.example.com ssh -i keyfile_internal -p 23456 user@internal2.example.com
解決方案:
修改 ~/.ssh/config,加入如下的配置項,
Host internal1.example.com internal2.example.com
User user
Port 23456
IdentityFile=keyfile_internal
ProxyCommand ssh -qaY -i keyfile_bastion -p 12345 user@bastion.example.com 'nc -w 14400 %h %p'
這樣,就可以直接從節點 admin.example.com 執行下面的命令直接連接internal1.example.com了
ssh user@internal1.example.com
ansible中也可以將internal節點當做可以直接連接的機器來使用
ansible -i host -m setup internal1.example.com
參考文檔:
- Managing OpenStack instances with Ansible through an SSH bastion host
- Using Ansible with a bastion SSH host
- Configuring Ansible to run play books through a bastion host on aws/ec2
- Using SSH Through A Bastion Host Transparently
- SSH Agent Forwarding Configuration with Ansible and Tower
- Ansible with a bastion host / jump box?
- https://ouyang.me/blog/2015/08/31/using-ansible-with-a-bastion-host/
