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:


- name: "Setting place name of {{ country }}" 
     place: "get_place_name"

- name: "Setting places name of {{ country }}" 
     places: "get_places_name"

- name: Details of "{{ country }}"
    msg: "{{ item }}" 
    -  place in "{{ item.Other_Places }}" or places in "{{ item.Other_Places }}" 
  with_items: "{{ 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
    msg: "{{ capital }} not in {{ item.Capital }} " 
    -  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".

  • 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 4:00
  • BTW you have an extra } in the line Capital: "{{ capital}}}"
    – Vish
    Apr 25 '18 at 4: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 8:13

use the condition

- when: variable is defined


- name:
    - task1
    - task2
  when: variable is defined

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.