有条件的add_host模块

时间:2020-09-16 07:19:49

标签: ansible

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

我的代码:

    - name: Create memory inventory
      add_host:
        name: "{{ item.0.key }}"
        group: target_hosts
      with_nested:
        - "{{ 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) }}"

使用此配置,Ansible错误:

The offending line appears to be:
        {% if item.0.value.OS_Choice[:3] == 'win' %}
         ^ here

关于如何实现此条件的任何想法?

2 个答案:

答案 0 :(得分:1)

您正在将Jinja2与YAML混合使用。在这里,您去了:

    - name: Create memory inventory when win
      add_host:
        name: "{{ item.0.key }}"
      with_nested:
        - "{{ lookup ('dict', hosts, wantlist=True) }}"
      when: item.0.value.OS_Choice[:3] == 'win'
      vars:
        group: 
          - target_hosts
          - win

    - name: Create memory inventory when not win
      add_host:
        name: "{{ item.0.key }}"
      with_nested:
        - "{{ lookup ('dict', hosts, wantlist=True) }}"
      when: item.0.value.OS_Choice[:3] != 'win'
      vars:
        group: 
          - target_hosts
          - linux

但是,Ansible gather facts about the OS already。也许您想使用它们,而不是自己配置类似的东西。

答案 1 :(得分:1)

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

您绝对应该以不同的方式执行此操作,例如实际上基于检测到的OS创建动态组。参见:

  • group_by module
  • 您可以通过以下示例来了解
  • ansible_distribution*个事实
    ansible localhost -m setup -a filter="ansible_distribution*"
    

同时,根据您当前的逻辑,您仍然可以在单个任务中执行此操作:

- name: Create memory inventory
  vars:
    additional_group: >-
      {{ (item.0.value.OS_Choice[:3] == 'win') | ternary('win', 'linux') }}
  add_host:
    name: "{{ item.0.key }}"
    groups:
      - target_hosts
      - "{{ additional_group }}"
  with_nested:
    - "{{ lookup ('dict', hosts, wantlist=True) }}"