通过跳板执行Ansible
首先
这篇文章是Ansible Advent Calender 2018第13天的内容。
本文将介绍当Ansible的目标执行服务器位于跳板服务器的另一侧时,关于如何执行Ansible的方法。
Ansible机制的复习
为了在Ansible中管理服务器的状态,我们可以使用SSH登录目标服务器并执行Python脚本。因此,如果我们想要通过跳板服务器来执行Ansible,则需要使用多层SSH机制。
执行环境
我想象了如下图所示的环境。

提前针对上述服务器设置。
-
- Ansible実行サーバ -> 踏み台サーバの公開鍵認証でのSSH設定
- 踏み台サーバ -> 実行対象サーバへの公開鍵認証でのSSH設定
在设置中,我们将在Ansible执行服务器上配置并存放私钥(id_rsa)和跳板服务器的私钥(id_rsa.bastion)。
此外,为了确认是否可以配置跳板服务器,我们事先要确认控制器无法直接与目标进行通信。
vagrant@controller:~$ cat host_list
bastion
target
vagrant@controller:~$ ansible -m shell -a "uname -n" -i host_list target
target | UNREACHABLE! => {
"changed": false,
"msg": "ERROR! SSH encountered an unknown error during the connection. We recommend you re-run the command using -vvvv, which will enable SSH debugging output to help diagnose the issue",
"unreachable": true
}
SSH的多段设置
要使用Ansible进行多段SSH,有以下两种主要模式,我们将分别介绍其配置方法。
-
- OSレベルでの設定
- Ansibleでの設定
操作系统级别的设置
将多段SSH的配置放入操作系统的SSH配置文件(例如~/.ssh/config, /etc/ssh/config),这样Ansible可以读取该配置并执行多段SSH。
需要注意的是,但当您更改操作系统的SSH设置时,请注意可能会影响到除Ansible之外的其他程序。
以下是实际的设定示例。
vagrant@controller:~/.ssh$ cat config
Host bastion
User vagrant
IdentityFile ~/.ssh/id_rsa
Host target
User vagrant
IdentityFile ~/.ssh/id_rsa.bastion
ProxyCommand ssh -W %h:%p bastion
在这种状态下执行,并确认通信通畅。
vagrant@controller:~$ ansible -m shell -a "uname -n" -i host_list target
target | SUCCESS | rc=0 >>
target
用Ansible进行配置
如果按照上述所述,在操作系统级别进行设置,将会对使用其他SSH程序产生影响。如果只想在执行Ansible时进行多段SSH,可能更好地在这里进行设置。
为了确认 ansible.cfg 的操作,我会删除上面设定的 ~/.ssh/config ,以保持无法连接状态。
vagrant@controller:~$ ansible -m shell -a "uname -n" -i host_list target
target | UNREACHABLE! => {
"changed": false,
"msg": "ERROR! SSH encountered an unknown error during the connection. We recommend you re-run the command using -vvvv, which will enable SSH debugging output to help diagnose the issue",
"unreachable": true
}
我們試著將設定放在 ansible.cfg 中。
基本上,您只需将您在 ~/.ssh/config 中进行的设置写入 ansible.cfg。将以上相同的设置写入 ansible.cfg 后将如下所示。
[ssh_connection]
ssh_args = -o ProxyCommand="ssh -i ~/.ssh/id_rsa bastion -W %h:%p" -i ~/.ssh/id_rsa.bastion
此外,您也可以通过环境变量(ANSIBLE_SSH_ARGS)进行相同的配置设置。
vagrant@controller:~$ export ANSIBLE_SSH_ARGS='-o ProxyCommand="ssh -i ~/.ssh/id_rsa bastion -W %h:%p" -i ~/.ssh/id_rsa.bastion'
在进行了上述设定的情况下执行,可以确认如下所示的连接。
vagrant@controller:~$ ansible -m shell -a "uname -n" -i host_list target
target | SUCCESS | rc=0 >>
target
顺便提一下,ansible.cfg 的设置以以下优先顺序进行读取。
-
- ANSIBLE_CONFIG (環境変数)
-
- ansible.cfg (カレントディレクトリ)
-
- ~/ansible.cfg (ホームディレクトリ)
- /etc/ansible/ansible.cfg
举个例子,如果想要根据Playbook的不同来进行设置,可以为每个Playbook的配置生成一个 ansible.cfg 文件,并事先进行配置,这样会更好。
最後に yī)
阅读《Ansible Advent Calendar》第12天的文章后,我有些模糊地想要为开源软件做出贡献。明年我希望能努力写出一篇名为“尝试创建Ansible模块并做出贡献”的文章。
请参考这篇文章。
- 多段SSHの設定を.ssh/configにまとめる