首页 > 解决方案 > “ansible_ssh_common_args”变量可以用于库存文件中的不同子组吗?

问题描述

我正在尝试从 2 个不同的 ProxyJumpHost 连接到 2 个主机。

例如:hostname1 只能通过 ProxyJumpHost1 访问 hostname2 只能通过 ProxyJumpHost2 访问

当我为组单独提供“ansible_ssh_common_args”变量时,ansible 只选择一个 ProxyJumpHost 信息并尝试从那里连接两个主机。

我的库存 yaml 文件如下所示

all_nodes:
  children:
    preprod:
      children:
        PRE_CH:
          vars:
            ansible_ssh_common_args: '-o ProxyCommand="sshpass -p {{ password }} ssh -W %h:%p -q {{ user }}@<ProxyJumpHost1>"'
          hosts:
            hostname1:
              ansible_host: <IP_Address>
            hostname2:
              ansible_host: <IP_Address>
        PRE_NL:
          vars:
            ansible_ssh_common_args: '-o ProxyCommand="sshpass -p {{ password }} ssh -W %h:%p -q {{ user }}@<ProxyJumpHost1>"'
          hosts:
            hostname3:
              ansible_host: <IP_Address>
            hostname4:
              ansible_host: <IP_Address>

我的期望是通过正确的 ProxyJumpHost 连接正确的主机。

但实际上它只需要一个 ProxyJumpHost 值并尝试通过它连接所有主机。

标签: ansible

解决方案


在您的示例中,两个变量都是相同的。

    PRE_CH:
      vars:
        ansible_ssh_common_args: '-o ProxyCommand="sshpass -p {{ password }} ssh -W %h:%p -q {{ user }}@<ProxyJumpHost1>"'

    PRE_NL:
      vars:
        ansible_ssh_common_args: '-o ProxyCommand="sshpass -p {{ password }} ssh -W %h:%p -q {{ user }}@<ProxyJumpHost1>"'

问:例如:hostname1 只能通过 ProxyJumpHost1 访问 hostname2 只能通过 ProxyJumpHost2 访问。我的期望是通过正确的 ProxyJumpHost 连接正确的主机

A:为每个主机设置ansible_ssh_common_args

      hosts:
        hostname1:
          ansible_host: <IP_Address>
          ansible_ssh_common_args: '... {{ user }}@<ProxyJumpHost1>"'
        hostname2:
          ansible_host: <IP_Address>
          ansible_ssh_common_args: '... {{ user }}@<ProxyJumpHost2>"'

问:“如果我还有 2 台主机可以通过 ProxyJumpHost1 连接,另外 2 台可以通过 ProxyJumpHost2 连接,该怎么办?总共有 3 台主机通过 ProxyJumpHost1,3 台主机通过 ProxyJumpHost2”

答:例如(为了简单和模块化)创建库存文件 gates.ini,其中包含两个额外的组 gate1 和 gate2。在配置或命令行中将此文件添加到清单中。从其他清单文件中删除ansible_ssh_common_args 。

[gate1]
hostname1
hostname2
hostname3
[gate1:vars]
ansible_ssh_common_args='-o ProxyCommand="sshpass -p {{ password }} ssh -W %h:%p -q {{ user }}@<ProxyJumpHost1>"'

[gate2]
hostname4
hostname5
hostname6
[gate2:vars]
ansible_ssh_common_args='-o ProxyCommand="sshpass -p {{ password }} ssh -W %h:%p -q {{ user }}@<ProxyJumpHost2>"'


推荐阅读