3

This question may look strange as something like this is not implemented in real life. I have tried to make it very general.

Here is my 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']

Here if "place" variable is defined as "place1" then it will run and output will be something as below:

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

The problem is I am confused on how to handle something that is not listed in "Other_Places"? Suppose I input "place10" as variable name "Capital" then it is not defined then it should simply output "Sorry, no matching place found."

If we do something like below :

- 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 }}"

This will output all at once because "place" is not defined in "capital".

Prakash
  • 349
  • 4
  • 5
  • 16
  • 3
    In its current form, I found your question unclear. Can you make your code short and self-contained - so that it should run simply by copying and pasting it into a playbook. This way the community will be able to help you better. – Vish Apr 25 '18 at 04:00
  • BTW you have an extra } in the line Capital: "{{ capital}}}" – Vish Apr 25 '18 at 04:01
  • well this is just a common example I gave. I want to show msg like "Place not found" when there is no place(s) defined in "Other_Places" variable. – Prakash Apr 25 '18 at 08:13

1 Answers1

3

use the condition

- when: variable is defined
  run_module_when_defined:

or

- name:
  block:
    - task1
    - task2
  when: variable is defined
Zohaib Amanzai
  • 171
  • 1
  • 3