Nel mio Ansible ruoli, alcuni ruoli derivare impostazioni di configurazione specifiche da variabili globali le variabili globali possono essere indefinito. Il codice riportato di seguito viene illustrato lo schema:
- hosts: localhost
vars:
bar: '{{ foo }}'
tasks:
# Assume foo comes from an Ansible environment
- debug: var=foo
# Assume bar comes from a role default
- debug: var=bar
# Catched by the "is defined" condition
- debug: msg="foo is defined"
when: 'foo is defined'
# Cannot catch undefined exception?!
- debug: msg="bar is defined"
when: 'bar is defined'
Tutto funziona come previsto, ma l'ultima dichiarazione: Ansible solleva un'eccezione, perché foo
è indefinito (sì, non è definito).
PLAY [localhost] *********************************************************************************************************************************************************
TASK [Gathering Facts] ***************************************************************************************************************************************************
ok: [localhost]
TASK [debug] *************************************************************************************************************************************************************
ok: [localhost] => {
"foo": "VARIABLE IS NOT DEFINED!"
}
TASK [debug] *************************************************************************************************************************************************************
ok: [localhost] => {
"bar": "VARIABLE IS NOT DEFINED!"
}
TASK [debug] *************************************************************************************************************************************************************
skipping: [localhost]
TASK [debug] *************************************************************************************************************************************************************
fatal: [localhost]: FAILED! => {"msg": "The conditional check 'bar is defined' failed. The error was: error while evaluating conditional (bar is defined): {{ foo }}: 'foo' is undefined\n\nThe error appears to be in '.../test-undef.yml': line 9, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n when: 'foo is defined'\n - debug: msg=\"bar is defined\"\n ^ here\n"}
Quindi perché non bar
non “valutare” a undefined
come foo
? E come posso bloccare questa “multi-livello” undefinedness?