Ansible 基于主机变量从库存组中选择主机

Ansible 基于主机变量从库存组中选择主机,ansible,yaml,jinja2,Ansible,Yaml,Jinja2,我有一个ansible库存文件,如下所示: [web] web1.so.com tech=apache web2.so.com tech=nginx 我只想在配置文件中列出web主机,如果技术是nginx。因此,在本例中,我希望ansible模板在配置文件中生成以下内容 服务器:web2.so.com 只有当tech=nginx时,我如何才能插入web主机 我通常通过在ansible模板中设置使用组来访问主机: 服务器:{{groups['web']} 但我知道这将列出web组中的所有主机 我

我有一个ansible库存文件,如下所示:

[web]
web1.so.com tech=apache
web2.so.com tech=nginx
我只想在配置文件中列出web主机,如果技术是nginx。因此,在本例中,我希望ansible模板在配置文件中生成以下内容

服务器:web2.so.com

只有当tech=nginx时,我如何才能插入web主机

我通常通过在ansible模板中设置使用组来访问主机:

服务器:{{groups['web']}

但我知道这将列出web组中的所有主机

我不知道如何只选择tech=nginx的主机,在这个用例中,不可能将它们划分为webnginx和webapache组


也不可能将其硬编码为使用web2,因为apache主机可能会随着每次重建而更改。

您可以使用或模块动态创建组

在您的情况下,使用以下示例中的group_by应满足您的要求:

---
- name: Create dynamic tech groups
  hosts: all
  gather_facts: false

  tasks:
    - name: Create the groups depending on tech
      group_by:
        key: "tech_{{ tech }}"
      when: tech is defined

- name: Do something on nginx group
  hosts: tech_nginx
  gather_facts: false

  tasks:
    - name: Show it works
      debug:
        msg: "I'm running on {{ inventory_hostname }}"
当然,一旦这样做了,您就可以在playbook的其他地方使用组['tech_nginx'],以获得该组中的主机列表

问:仅当技术为nginx时,才在配置文件中列出web主机

答:可以使用json_查询。例如下面的剧本

- hosts: all
  tasks:
    - set_fact:
        nginx_list: "{{ hostvars|dict2items|
                        json_query('[?value.tech==`nginx`].key') }}"
      run_once: true
    - debug:
        var: nginx_list
给出可在配置中使用的变量nginx_list

ok: [web1.so.com] => {
    "nginx_list": [
        "web2.so.com"
    ]
}
ok: [web2.so.com] => {
    "nginx_list": [
        "web2.so.com"
    ]
}
例如,下面的lineinfle

给予

- lineinfile:
    path: /tmp/webservers.cfg
    regex: "^nginx\\s*=(.*)$"
    line: "nginx = {{ nginx_list|join(', ') }}"
    create: true
  delegate_to: localhost
$ cat /tmp/webservers.cfg 
nginx = web2.so.com