I have following playbook ~ # cat demo.yml:
- name: demo
hosts: localhost
gather_facts: no
vars:
set:
task:
type: var1
task:
- type: var1
- type: var2
- type: var3
tasks:
- debug:
var: set
- debug:
var: task
- set_fact:
task:
type: "{{set.task.type if item.type is search(set.task.type|join('|')) else 'absent'}}"
loop: "{{task}}"
- debug:
var: task
Output:
PLAY [demo] ************************************************************************************************************************************************************************************************
TASK [debug] ***********************************************************************************************************************************************************************************************
ok: [localhost] => {
"set": {
"task": {
"type": "var1"
}
}
}
TASK [debug] ***********************************************************************************************************************************************************************************************
ok: [localhost] => {
"task": [
{
"type": "var1"
},
{
"type": "var2"
},
{
"type": "var3"
}
]
}
TASK [set_fact] ********************************************************************************************************************************************************************************************
ok: [localhost] => (item={'type': 'var1'})
ok: [localhost] => (item={'type': 'var2'})
ok: [localhost] => (item={'type': 'var3'})
TASK [debug] ***********************************************************************************************************************************************************************************************
ok: [localhost] => {
"task": {
"type": "var1"
}
}
PLAY RECAP *************************************************************************************************************************************************************************************************
localhost : ok=4 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
As you could see this works great and new value for variable task.type is set to var1.
However the problem is when I provide set.task.type: var4 or any other variable.
Than task.type is set to var4 instead of absent.
Question:
How to set new value task.type: absent if set.task.type does not match any values from the array?
task. During the first execution,taskis a list that contains three items. After the first iteration of yourloop,taskis a dictionary. Don't try to re-use the variable name like that and you will probably see different behavior.absentstate if you can check foris defined?