snippetMinor
How to handle item not in list in ansible variable?
Viewed 0 times
itemvariablehandlehowlistnotansible
Problem
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
vars/main.yml
Here if "place" variable is defined as "place1" then it will run and output will be something as below:
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 :
This will output all at once because "place" is not defined in "capital".
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".
Solution
use the condition
or
- when: variable is defined
run_module_when_defined:or
- name:
block:
- task1
- task2
when: variable is definedCode Snippets
- when: variable is defined
run_module_when_defined:- name:
block:
- task1
- task2
when: variable is definedContext
StackExchange DevOps Q#3947, answer score: 3
Revisions (0)
No revisions yet.