I'm aware than ansible supports loops in templates in this form:
{% for host in groups['all'] %}
"{{ host }}"{% if not loop.last %},{% endif %}
{% endfor %}
When I run ansible, this loops over everything in the hosts file, as one might expect.
When I run ansible with the --limit command line argument, I would like to loop over only the hosts that match the limit. Is there a way to express that loop in jinja2 templates?
You can use play_hosts
variable from vars
, for example:
{% for host in vars['play_hosts'] %}
"{{ host }}"{% if not loop.last %},{% endif %}
{% endfor %}
Imagine this setup:
# hosts
[all-hosts]
ansible ansible_ssh_host=192.168.42.2
webapp ansible_ssh_host=192.168.42.10
postgresql ansible_ssh_host=192.168.42.20
#playbook.yml
---
- hosts: all
gather_facts: no
tasks:
- name: Hosts
template: src=myhosts.j2 dest=./myhosts.json
delegate_to: 127.0.0.1
run_once: yes
then by running it with no limit would give you the same result as you have, but when you specify limit it would produce only "limited" host names:
ansible-playbook -i hosts playbook.yml --limit postgresql,ansible
Output:
"ansible", "postgresql"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With