【问题标题】:Choosing host from inventory group based on a host variable根据主机变量从清单组中选择主机
【发布时间】:2019-09-23 11:18:01
【问题描述】:

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

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

我只想在技术是 nginx 的情况下在配置文件中列出 web 主机。所以在这种情况下,我希望 ansible 模板在配置文件中生成以下内容。

server: web2.so.com

只有在 tech=nginx 的情况下,我如何才能插入 web 主机?

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

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

但我知道这将列出网络组中的所有主机。

我不知道如何只选择具有tech=nginx 的主机,在这个用例中,无法将它们分成 web-nginx 和 web-apache 组。

也不可能对其进行硬编码以使用 web2,因为每次重建时 apache 主机都会发生变化。

【问题讨论】:

    标签: ansible yaml jinja2


    【解决方案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 }}"
    

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

    【讨论】:

      【解决方案2】:

      问:“仅当技术是 nginx 时,才在配置文件中列出 Web 主机。”

      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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-09-08
        • 2018-02-17
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多