Ansible: set_fact after successful variable match in array
1
vote
1
answer
2974
views
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?
Asked by Rafal Niznik
(333 rep)
Aug 10, 2022, 06:11 PM
Last activity: Aug 18, 2022, 02:52 PM
Last activity: Aug 18, 2022, 02:52 PM