【问题标题】:add_host - divide by osadd_host - 除以操作系统
【发布时间】:2020-04-01 17:21:47
【问题描述】:

我想创建整个清单文件的剧本并将服务器分为 2 组:Windows 和 Linux(添加主机仅在 inv 上的第一台服务器上进行)

我试过这段代码:

   - name: Linux Group
     add_host:
       name: "{{ item }}"
       group: LinuxGroup
     when:  hostvars[" {{ item }} "]['ansible_system']  == 'Linux'
     with_items: "{{ ansible_play_hosts_all }} "
  • 此代码假设创建 linux 组 我尝试了其他条件,但没有成功。我想得到你的帮助。

PS:

我把代码改成这样:

    tasks:
   - name: Create linux group
     add_host:
       name: "{{ item }}"
       group: LinuxGroup
     when: hostvars[item].ansible_system == 'Linux'
     with_items: "{{ ansible_play_hosts_all }} "
     ignore_errors: yes

   - name: ping to Linux
     ping:
     with_items: LinuxGroup

当我运行代码时,windows 服务器在“创建 linux 组”任务中被跳过,但我使用模块调试打印到组的项目并且有 windows 服务器。

【问题讨论】:

    标签: ansible jinja2 ansible-inventory ansible-facts


    【解决方案1】:

    事实上ansible_system 是主机下的一个键,而不是一个键列表。此外,条件语句不应包含 jinja2 模板分隔符,例如 {{ }}{% %},使用 hostvars[item] 而不是 hostvars[ "{{ item }}" ]

    确保将gather_facts 设置为true

    请注意,add_host 模块不会更新清单文件,而是更新内存中的清单。我已经包含了一个debug 任务来打印ansible 内存清单中的组。

      gather_facts: true
      tasks:
        - name: Linux Group
          add_host:
            name: "{{ item }}"
            group: LinuxGroup
          when:  hostvars[item].ansible_system == 'Linux'
          with_items: "{{ ansible_play_hosts_all }}"
        - debug: msg="{{ groups }}"
    

    【讨论】:

    • 我使用了您之前建议的方式,但我收到此消息:“条件检查 'hostvars[item].ansible_system == 'Linux eventhoght 我检查了 moudle setup 并且此变量应该存在
    • 您能否提供完整的错误信息和您尝试过的剧本?
    最近更新 更多