根据主机变量从清单组中选择主机

时间:2019-09-23 11:18:01

标签: ansible yaml jinja2

我有一个类似的库存文件:

[web]
web1.so.com tech=apache
web2.so.com tech=nginx

仅当技术为nginx时,我才想在配置文件中列出虚拟主机。因此,在这种情况下,我希望ansible模板在配置文件中生成以下内容。

server: web2.so.com

仅当tech = nginx时,如何才能插入虚拟主机?

我通常会通过使用ansible模板中的组进行设置来访问主机:

server: "{{groups['web']}}"

但是我知道这将列出该Web组中的所有主机。

我无法弄清楚如何仅选择具有tech=nginx的主机,在这种情况下,无法将其分为web-nginx和web-apache组。

也无法对其进行硬编码以使用web2,因为apache主机可能会在每次重建时更改。

2 个答案:

答案 0 :(得分:1)

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

在您的情况下,按照以下示例使用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 }}"

当然,完成此操作后,您可以在剧本的其他位置使用groups['tech_nginx']来获取该组中的主机列表。

答案 1 :(得分:0)

  

Q:“仅当技术人员为nginx时,才在配置文件中列出网络主机。”

A:可以使用 json_query 。例如下面的播放

- 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"
    ]
}

例如下面的 lineinfile

- 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