I try to set default value for hosts field in playbook with Jinja2 filter, but it doesn’t work:
hosts: “{{ host | default(localhost) }}”
tasks:
name: show OS version info
debug: msg=“{{ansible_distribution}} {{ansible_distribution_version}}”
ansible-playbook -i hosts dist.yml
PLAY [{{host | default(localhost)}}] ******************************************
skipping: no hosts matched
But when I execute it with command line parameter, it works ok:
ansible-playbook -i hosts dist.yml --extra-vars ‘host=localhost’
PLAY [localhost] **************************************************************
…
???
Change to default(‘localhost’).
Found the reason myself:
hosts: “{{ host | default(localhost) }}”
This should be:
hosts: “{{ host | default(‘localhost’) }}”
Still would be nice to get more valuable error message. I guess Jinja2 translates bare localhost to variable name, which in turn is translated to empty string, but why the Ansible shows PLAY [{{host | default(localhost)}}] **** and not PLAY **** or PLAY [error ] **** ?
@Scott , thanks. Trial and error told me that way too.
If you are attempting to drive the host spec based on inventory variables, this won’t work.
If you drive it with input from -e, it will.
You can’t use inventory variables to drive the host spec.
Why? Isn’t the initialization order sets inventory variables first?