Use default(None) to avoid error "'slackchannel1' is undefined"
slack:
- slack_channel: '#mychannel'
- slack_channel: '{{ slackchannel1|default(None) }}'
- slack_channel: '{{ slackchannel2|default(None) }}'
Then, select defined items
loop: "{{ slack | default([]) | selectattr('slack_channel') | list }}"
Quoting from selectattr
If no test is specified, the attribute’s value will be evaluated as a boolean.
For example, the playbook
shell> cat playbook.yml
- hosts: localhost
vars:
slack:
- slack_channel: '#mychannel'
- slack_channel: '{{ slackchannel1|default(None) }}'
- slack_channel: '{{ slackchannel2|default(None) }}'
tasks:
- debug:
msg: "{{ item.slack_channel }}"
loop: "{{ slack | default([]) | selectattr('slack_channel') | list }}"
shell> ansible-playbook playbook.yml
gives
ok: [localhost] => (item={'slack_channel': '#mychannel'}) =>
msg: '#mychannel'
When the variable is defined
shell> ansible-playbook playbook.yml -e slackchannel2=test
the playbook gives
ok: [localhost] => (item={'slack_channel': '#mychannel'}) =>
msg: '#mychannel'
ok: [localhost] => (item={'slack_channel': 'test'}) =>
msg: test
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…