Ansible — Nested when statement using the playbook block
Don’t be afraid to be confused.
Most of the time I confused and struggled using If
else
condition in ansible-playbook, It’s really very easy in other programming language and it’s straightforward synthetically. I found when
which is useful for conditioning statements like if
But I didn't find any else
part usage in ansible-playbook.
Playbook block
is another usage that allows logical grouping of tasks in play error handling. filter
data from a complex dynamic json
structure with limited dynamic condition statements is a frustrating task for developers. In the case of the dynamic condition, this nested when
may help sometimes but still else
is a blocker.
Here is an example for nested when
statement using block
,
---
--
connection: local
gather_facts: false
hosts: hosts
vars:
complex_json: {
"status": {
"name": "nested condition ",
"details": {
"data": {
"data_details": [{"Id": 1}, {"Id": 2}]
}
}
}
}
tasks:
- block:
- block:
- debug:
msg: "{{ complex_json.status.detils }}"
when: "'data2' not in complex_json.status.details"
when: "'data1' not in complex_json.status.details"
I hope this example may help to get rid of complex structures with a nested condition statement. If any more clear document please leave it into the comment box.