在尝试连接到主机之前根据清单中的变量值设置连接变量?

问题描述 投票:0回答:1

我有一个混合 RHEL 和 Windows 主机的清单,需要不同的连接变量值。这些主机被分为父组(他们的团队)和子组(他们的应用程序)。

我可以将他们分为多个组:“RHEL”/“Windows”和他们的团队。但我希望将它们列在我的库存中一次。我还希望避免在主机级别为每个 RHEL 主机或 Windows 主机定义相同的连接变量集。有一组适用于 rhel 主机的变量,以及一组适用于 windows 主机的变量。我不想为操作系统创建子组,因为我已经有主机应用程序的子组。

我可以简单地在主机级别设置一个变量(os: rhel 或 os: windows),然后根据此“os”变量的值分配连接变量吗?这需要在 ansible 尝试连接到主机之前完成。

所以我认为逻辑看起来像这样?:

  1. ansible 根据主机模式读取库存主机
  2. 准备在host1上执行
  3. 读取主机1上的操作系统值
  4. 根据主机 1 的操作系统值为主机 1 分配 ansible 连接变量
  5. 使用这些新分配的变量连接到 host1
  6. 在主机1上执行剧本

如果我可以做这样的事情,该怎么做?

ansible
1个回答
0
投票

我在我的剧本中做了以下操作来实现这一目标。关键点是在游戏级别禁用

gather_facts
,根据库存中的变量使用
set_facts
设置 ansible 连接变量,然后使用
gather_facts
模块手动运行
setup
。之后你就可以写剩下的剧本了。

- name: playbook name
  hosts: TeamGroupName
  gather_facts: no
  tasks:
    - name: If os is RHEL, assign RHEL connection variables
      when: os == 'rhel'
      set_fact:
        ansible_connection: ssh
        ansible_become_method: dzdo
    - name: If OS is Windows, assign Windows connection variables
      when: os == 'windows'
      set_fact:
        ansible_connection: winrm
        ansible_port: 5985
    - name: Gathering facts
      setup:
    ...rest of the playbook can now be added here...
© www.soinside.com 2019 - 2024. All rights reserved.