循环遍历jinj2a模板中的主机,尊重--limit

Dav*_*hen 4 jinja2 ansible

我知道,ansible支持这种形式的模板中的循环:

{% for host in groups['all'] %}
  "{{ host }}"{% if not loop.last %},{% endif %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

当我运行ansible时,这会循环遍历hosts文件中的所有内容,正如人们所期望的那样.

当我使用--limit命令行参数运行ansible时,我想只遍历符合限制的主机.有没有办法在jinja2模板中表达这个循环?

Vor*_*Vor 8

您可以使用play_hosts变量from vars,例如:

{% for host in vars['play_hosts'] %}
  "{{ host }}"{% if not loop.last %},{% endif %}
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

想象一下这个设置:

# 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
Run Code Online (Sandbox Code Playgroud)

然后通过无限制地运行它会得到与你相同的结果,但是当你指定限制时它只会产生"有限"的主机名:

ansible-playbook -i hosts playbook.yml --limit postgresql,ansible
Run Code Online (Sandbox Code Playgroud)

输出:

"ansible",  "postgresql"
Run Code Online (Sandbox Code Playgroud)