loop over hosts in jinj2a template, respecting --limit

笑着哭i 提交于 2021-01-23 06:10:12

问题


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?


回答1:


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"


来源:https://stackoverflow.com/questions/31282167/loop-over-hosts-in-jinj2a-template-respecting-limit

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!