Ansible 有条件添加_主机模块

Ansible 有条件添加_主机模块,ansible,Ansible,我有一个需要添加条件的清单 我的代码: - name: Create memory inventory add_host: name: "{{ item.0.key }}" group: target_hosts with_nested: - "{{ lookup ('dict', hosts, wantlist=True) }}" -名称:创建内存资源清册 添加\u主机: 名称:“{item.0.key}}” 组:目标主机

我有一个需要添加条件的清单

我的代码:

- name: Create memory inventory add_host: name: "{{ item.0.key }}" group: target_hosts with_nested: - "{{ lookup ('dict', hosts, wantlist=True) }}" -名称:创建内存资源清册 添加\u主机: 名称:“{item.0.key}}” 组:目标主机 使用嵌套的\u: -{{lookup('dict',hosts,wantlist=True)} 但我想要的是:

- name: Create memory inventory add_host: name: "{{ item.0.key }}" {% if item.0.value.OS_Choice[:3] == 'win' %} group: - target_hosts - win {% else %} group: - target_hosts - linux {% endif %} with_nested: - "{{ lookup ('dict', hosts, wantlist=True) }}" -名称:创建内存资源清册 添加\u主机: 名称:“{item.0.key}}” {%if item.0.value.OS_Choice[:3]='win%} 组: -目标主机 -赢 {%else%} 组: -目标主机 -linux {%endif%} 使用嵌套的\u: -{{lookup('dict',hosts,wantlist=True)} 使用此配置,可能会出现以下错误:

The offending line appears to be: {% if item.0.value.OS_Choice[:3] == 'win' %} ^ here 令人不快的一行似乎是: {%if item.0.value.OS_Choice[:3]='win%} ^这里
有没有关于如何实现这个条件的想法?

你把Jinja2和YAML搞混了。给你:

-名称:赢时创建内存资源清册
添加\u主机:
名称:“{item.0.key}}”
使用嵌套的\u:
-{{lookup('dict',hosts,wantlist=True)}
时间:item.0.value.OS_Choice[:3]=“赢”
变量:
组:
-目标主机
-赢
-名称:不赢时创建内存资源清册
添加\u主机:
名称:“{item.0.key}}”
使用嵌套的\u:
-{{lookup('dict',hosts,wantlist=True)}
时间:item.0.value.OS_选项[:3]!='赢
变量:
组:
-目标主机
-linux

然而,Ansible。也许您想使用这些,而不是自己配置这样的东西。

您将Jinja2与YAML混为一谈。给你:

-名称:赢时创建内存资源清册
添加\u主机:
名称:“{item.0.key}}”
使用嵌套的\u:
-{{lookup('dict',hosts,wantlist=True)}
时间:item.0.value.OS_Choice[:3]=“赢”
变量:
组:
-目标主机
-赢
-名称:不赢时创建内存资源清册
添加\u主机:
名称:“{item.0.key}}”
使用嵌套的\u:
-{{lookup('dict',hosts,wantlist=True)}
时间:item.0.value.OS_选项[:3]!='赢
变量:
组:
-目标主机
-linux

然而,Ansible。也许你想使用这些,而不是自己配置类似的东西。

以Kevin的答案为基础(并修复一些错误放置的参数)

您肯定应该以不同的方式执行此操作,例如根据facts中检测到的操作系统创建动态组。见:

  • ansible\u发行版*
    事实,您可以使用它作为示例进行探索
    ansible localhost-m setup-a filter=“ansible\u分布*
    
同时,根据您当前的逻辑,您仍然可以在单个任务中执行此操作:

-名称:创建内存资源清册
变量:
附加组:>-
{{(item.0.value.OS_Choice[:3]='win')|三元('win','linux')}
添加\u主机:
名称:“{item.0.key}}”
组:
-目标主机
-“{{附加组}”
使用嵌套的\u:
-{{lookup('dict',hosts,wantlist=True)}

以凯文的答案为基础(并修正一些错误设置的参数)

您肯定应该以不同的方式执行此操作,例如根据facts中检测到的操作系统创建动态组。见:

  • ansible\u发行版*
    事实,您可以使用它作为示例进行探索
    ansible localhost-m setup-a filter=“ansible\u分布*
    
同时,根据您当前的逻辑,您仍然可以在单个任务中执行此操作:

-名称:创建内存资源清册
变量:
附加组:>-
{{(item.0.value.OS_Choice[:3]='win')|三元('win','linux')}
添加\u主机:
名称:“{item.0.key}}”
组:
-目标主机
-“{{附加组}”
使用嵌套的\u:
-{{lookup('dict',hosts,wantlist=True)}

不应该
group
groups
并作为模块参数而不是
vars
?非常感谢,我应该想到这一点。此时我无法使用Ansible facts,因为主机尚未设置。不应该将
group
设置为
groups
并作为模块参数而不是
vars
?非常感谢,我应该想到这一点。此时无法使用Ansible事实,因为尚未设置主机。此时无法使用检测到的事实,因为主机不存在于数据字典之外。这是AWX系列中的一个剧本,它采用主机和属性字典,并在oVirt中构建这些主机,ForemanI无法使用检测到的事实,因为此时主机不存在于数据字典之外。这是AWX系列中的一个剧本,它采用主机和属性字典,并在oVirt和Foreman中构建这些主机