一千萬個為什麽

搜索

如何處理ansible變量中不在列表中的項目?



這個問題可能看起來很奇怪,因為這樣的事情並沒有在現實生活中實現。我試圖讓它變得非常籠統。

這是我的ansible-playbook:

任務/ 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 }}"

乏/ main.yml </強>

---
Places:
- Country: "United States of America"
  Capital: "{{ capital }}"
  Other_Places: ['place1', 'place2']

- Country: "China"
  Capital: "{{ capital }}"
  Other_Places: ['places1', 'places2', 'places3', 'places4']

如果“place”變量被定義為“place1”,那麽它將運行並輸出如下所示:

"msg": {
        "Country": "United States of America", 
        "Capital": "place1", 
        "Other_Places": "['place1', 'place2']"
    }

問題是我對如何處理“Other_Places”中未列出的內容感到困惑?假設我輸入“place10”作為變量名稱“Capital”然後它沒有被定義,那麽它應該只輸出“抱歉,找不到匹配的地方”。

如果我們做以下事情:

- name: Exceptional case
  debug:
    msg: "{{ capital }} not in {{ item.Capital }} " 
  when:
    -  place not in "{{ item.Other_Places }}" and places not in "{{ item.Other_Places }}" 
  with_items: "{{ Places }}"

這將一次輸出所有因為“地點”沒有在“大寫”中定義。

轉載註明原文: 如何處理ansible變量中不在列表中的項目?

一共有 0 個回答: