在Ansible中处理未在列表中的项

45次阅读
没有评论

问题描述

在使用Ansible时遇到了一个问题,他想知道如何处理在变量列表中未列出的项。具体情况如下:

用户有一个Ansible playbook,其中包含一些任务。这些任务涉及到一个名为place的变量,用户希望在变量place不在Other_Places列表中时输出”Sorry, no matching place found.”。用户尝试了一些方法,但是仍然感到困惑,不知道如何实现这个功能。

以下是用户提供的Ansible playbook的简化示例:

# tasks/main.yml
- name: "Setting place name of {{ country }}"
  set_fact:
    place: "get_place_name"
- name: "Setting places name of {{ country }}"
  set_fact:
    places: "get_places_name"
- name: Details of "{{ country }}"
  debug:
    msg: "{{ item }}"
  when:
    - place in "{{ item.Other_Places }}" or places in "{{ item.Other_Places }}"
  with_items: "{{ Places }}"

# vars/main.yml
---
Places:
  - Country: "United States of America"
    Capital: "{{ capital }}"
    Other_Places: ['place1', 'place2']
  - Country: "China"
    Capital: "{{ capital }}"
    Other_Places: ['places1', 'places2', 'places3', 'places4']

用户想要的效果是,当变量Capital不在Other_Places列表中时,输出”Sorry, no matching place found.”。

解决方案

在Ansible中,你可以通过添加额外的任务来处理在列表中未列出的项。以下是解决这个问题的方法:

方案

请注意以下操作可能需要根据版本和需求进行调整。
1. 在你的Ansible playbook中,添加一个新的任务,用于处理未匹配到的情况。
2. 在这个任务中,使用条件判断来检查变量是否在Other_Places列表中。
3. 如果变量不在列表中,输出”Sorry, no matching place found.”。

下面是示例代码:

# tasks/main.yml
- name: "Setting place name of {{ country }}"
  set_fact:
    place: "get_place_name"
- name: "Setting places name of {{ country }}"
  set_fact:
    places: "get_places_name"
- name: Details of "{{ country }}"
  debug:
    msg: "{{ item }}"
  when:
    - place in "{{ item.Other_Places }}" or places in "{{ item.Other_Places }}"
  with_items: "{{ Places }}"

# 添加一个新的任务用于处理未匹配到的情况
- name: Handle unmatched place
  debug:
    msg: "Sorry, no matching place found."
  when:
    - place not in item.Other_Places and places not in item.Other_Places
  with_items: "{{ Places }}"

在上面的代码中,我们添加了一个名为”Handle unmatched place”的新任务。这个任务使用条件判断来检查place是否不在Other_Places列表中,以及places是否不在Other_Places列表中。如果条件满足,就会输出”Sorry, no matching place found.”。

注意事项

  • 请根据实际情况修改变量名和逻辑,确保代码适用于你的Ansible playbook。
  • Ansible的版本可能会影响某些语法和功能的可用性,你可能需要根据实际情况进行调整。

这样,你就可以在Ansible中处理未在列表中的项,并根据需求输出相应的信息。

如果你想要更加简洁的解决方案,你可以尝试使用Ansible的一些内置函数和过滤器来实现条件判断。不过,由于你的问题比较特殊,需要根据变量是否在列表中进行判断,可能需要一些额外的处理。

正文完