Hi Guys
Can some one here help me on how to run a task if a variable is undefined.
I want to check if a variable exists or not and register that .
If Variable exists I want to run a task.
Has any one successfully done this ?
Hi Guys
Can some one here help me on how to run a task if a variable is undefined.
I want to check if a variable exists or not and register that .
If Variable exists I want to run a task.
Has any one successfully done this ?
Hi,
have you tried to use “undefined” in the when statement ?
Yes, I have used that.
But my task is being skipped , even when the variable is defined
Here is what I am doing
name: Check the variable value which is in dictionary
debug:
var: certs[a][b][c][d][‘certs’]
register: results
debug:
var: results
name: “set the value”
set_fact:
s_cert: [“{{ item }}”, ]
with_items:
“{{ certs[a][b][c][d][‘certs’] }}”
when: results is undefined
so , when I run it, in both cases where variable has some value and variable is undefined, the task is being skipped
Yes, I have used that.
I have know idea what you are trying to do, but you should probably try to explain in more detail and maybe show the output.
But my task is being skipped , even when the variable is defined
Here is what I am doing
- name: Check the variable value which is in dictionary
debug:
var: certs[a][b][c][d]['certs']
register: results
The variable result will always have a value...
- debug:
var: results- name: "set the value"
set_fact:
s_cert: ["{{ item }}", ]
with_items:
- "{{ certs[a][b][c][d]['certs'] }}"
when: results is undefined
...so the variable result will always be defined so this task will never run.
You probably just want to do this, delete the when and just use
{{ certs[a][b][c][d]['certs'] | default() }}
Sorry for not mentioning it clearly.
I got it fixed.
My issue was , I am taking the values of a.b,c,d dynamically.
so when I am checking for certs[a][b][c][d][‘certs’] , it will check until [‘certs’]., last of the nested dict
My variable is
certs:
host1:
host_type:
host_name:
host_flavor:
certs:
b:2
host2:
host_type:
host_name:
host_flavor:
certs:
b:2
so, when host3 doesn’t have entry, I wanted it to skip the task that I am running
so, when using { certs[a][b][c][d][‘certs’] | default() }} }
it errors out saying type ‘dict’ has no value u ‘host3’
Instead of checking for { certs[a][b][c][d][‘certs’] | default() }} }, Now I am doing
{ certs[a] | default({})} — > which solves my purpose.
when host3 is not present,it will skip the task
Thanks .