Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

loop over hosts in jinj2a template, respecting --limit

Tags:

ansible

jinja2

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?

like image 923
Dave Cohen Avatar asked Dec 19 '22 02:12

Dave Cohen


1 Answers

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"
like image 146
Vor Avatar answered Jan 10 '23 07:01

Vor