Using ansible with a jump host

TL;DR - 配置Ansible通过jump host/jump server(跳板机)管理服务器

1.Ansible Playbook目录结构

jumphost_playbook/
├── ansible.cfg
├── inventory
└── ssh.config

2.Ansible配置

# vi ansible.cfg

[ssh_connection]
ssh_args = -F ssh.config # 指定ssh config(语法同~/.ssh/config)
control_path = ~/.ssh/mux-%%[email protected]%%h:%%p

# 配置文件读取优先级
* ANSIBLE_CONFIG (an environment variable)
* ansible.cfg (in the current directory)
* .ansible.cfg (in the home directory)
* /etc/ansible/ansible.cfg

3.Ansible inventory配置

# vi inventory

### 跳板机01
[jump01]
8.8.8.8.236


### 北京IDC
[bj-cyqz-all:children]
bj-cyqz-lvs
bj-cyqz-web


### 北京IDC-LVS
[bj-cyqz-lvs]
bj-cyqz-lvs[1:2]


### 北京IDC-Web
[bj-cyqz-web]
bj-cyqz-web[1:3]

# 参考:
http://docs.ansible.com/ansible/intro_inventory.html

4.ssh config 配置

# 跳板机和Real服务器均使用key登录
# vi ssh.config

# 定义跳板机
Host jump
        User Zer0d0y
        Hostname 8.8.8.236
        port 12345
        IdentityFile /home/zer0d0y/.ssh/Zer0d0y.rsa

# 定义Real服务器
Host bj-cyqz-lvs1
        User ring3
        Hostname 4.4.4.162
        Port 12345
        IdentityFile /home/zer0d0y/.ssh/ring3_id_rsa.rsa
        ProxyCommand ssh -W %h:%p jump

Host bj-cyqz-lvs2
        User ring3
        Hostname 4.4.4.174
        Port 12345
        IdentityFile /home/zer0d0y/.ssh/ring3_id_rsa.rsa
        ProxyCommand ssh -W %h:%p jump

Host bj-cyqz-web1
        User ring3
        Hostname 4.4.4.170
        Port 12345
        IdentityFile /home/zer0d0y/.ssh/ring3_id_rsa.rsa
        ProxyCommand ssh -W %h:%p jump

Host bj-cyqz-web2
        User ring3
        Hostname 4.4.4.171
        Port 12345
        IdentityFile /home/zer0d0y/.ssh/ring3_id_rsa.rsa
        ProxyCommand ssh -W %h:%p jump

Host bj-cyqz-web3
        User ring3
        Hostname 4.4.4.172
        Port 12345
        IdentityFile /home/zer0d0y/.ssh/ring3_id_rsa.rsa
        ProxyCommand ssh -W %h:%p jump

# 注意:以下两行必须加上,否则ansible.cfg配置中的-F参数不能正确处理此文件
Host *
    SendEnv LANG LC_*

5.验证

# ssh-add /home/zer0d0y/.ssh/Zer0d0y.rsa
# ssh-add /home/zer0d0y/.ssh/ring3_id_rsa.rsa

# ssh -F ssh.config bj-cyqz-lvs1
# ansible -i inventory bj-cyqz-all -m ping

6.安全问题

推荐使用ProxyCommand,切勿使用SSH Agent Forwarding方式
# 参考:
https://github.com/joushou/sshmuxd#but-agent-forwarding-is-dangerous
https://heipei.github.io/2015/02/26/SSH-Agent-Forwarding-considered-harmful/

7.参考资料:

Ansible
http://docs.ansible.com/ansible/faq.html#how-do-i-configure-a-jump-host-to-access-servers-that-i-have-no-direct-access-to
https://alexbilbie.com/2014/07/using-ansible-with-a-bastion-host/
https://blog.laisky.com/p/ansible/

SSH
https://wiki.gentoo.org/wiki/SSH_jump_host
https://ma.ttias.be/use-jumphost-ssh-client-configurations/
comments powered by Disqus

作者:Zer0d0y
微信关注:Zer0d0y
本文出处:https://www.zer0d0y.info/post/using-ansible-with-a-jump-host/
本站评论使用Disqus,如果长时间无法加载,请切换至“自由”互联网。
文章版权归本人所有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。