如何在Ansible Playbook中获取各主机组名并实现分组统计?
Ansible Playbook Audit with Group-wise Stats & Jinja2 HTML Dashboard
Hey there! I’ve built similar audit dashboards before, so let’s break down how to solve your problem—especially the key part of grabbing each host’s group membership and calculating those group-specific stats.
Step 1: Core Ansible Variables You’ll Depend On
First, let’s clarify the variables that make this possible:
groups['<group_name>']: Returns a list of all hosts in a specific group. Usegroups['Ubuntu16'] | lengthto get the total count for that group.group_names: For every host, this is a list of all groups it belongs to—this is exactly how you’ll map a host to its group.ansible_play_hosts: The list of hosts that successfully connected (alive hosts) in the current play.ansible_play_hosts_all: The full list of hosts targeted by the play (total hosts in scope).
Step 2: Complete Playbook Implementation
Here’s a playbook that will:
- Verify host connectivity
- Track alive hosts and their group info
- Calculate total/alive counts per group
- Generate the HTML dashboard via Jinja2
--- - name: Audit host connectivity and collect group data hosts: all gather_facts: false tasks: - name: Check if host is reachable ping: register: ping_status - name: Record alive host + its groups set_fact: alive_hosts: "{{ alive_hosts | default([]) + [{'host': inventory_hostname, 'groups': group_names}] }}" when: ping_status is succeeded delegate_to: localhost run_once: false - name: Calculate group stats and build dashboard hosts: localhost gather_facts: false vars: target_groups: ["Ubuntu16", "CentOS7"] # Match your inventory groups tasks: - name: Initialize group stats with total host counts set_fact: group_stats: "{{ group_stats | default({}) | combine({ item: {'total': groups[item] | length, 'alive': 0} }) }}" loop: "{{ target_groups }}" - name: Update alive counts for each group set_fact: group_stats: "{{ group_stats | combine({ host_group: {'alive': group_stats[host_group]['alive'] + 1} }, recursive=True) }}" loop: "{{ alive_hosts }}" vars: host_group: "{{ item.groups[0] }}" # Assumes 1 group per host; adjust if multi-group - name: Generate HTML audit dashboard template: src: audit_dashboard.j2 dest: ./audit_results.html
Step 3: Jinja2 Template Example (audit_dashboard.j2)
This template will turn your stats into a clean, readable dashboard:
<!DOCTYPE html> <html> <head> <title>Host Audit Dashboard</title> <style> .group-container { border: 1px solid #ddd; padding: 18px; margin: 12px; width: 320px; float: left; border-radius: 8px; } .stat-label { font-weight: bold; margin-right: 8px; } .alive-count { color: #2ecc71; font-size: 1.3em; } .total-count { color: #34495e; } </style> </head> <body> <h1>Host Connectivity Audit Results</h1> {% for group, stats in group_stats.items() %} <div class="group-container"> <h2>{{ group }}</h2> <p><span class="stat-label">Total Hosts:</span> <span class="total-count">{{ stats.total }}</span></p> <p><span class="stat-label">Alive Hosts:</span> <span class="alive-count">{{ stats.alive }}</span></p> <p><span class="stat-label">Availability:</span> {{ (stats.alive / stats.total * 100) | round(2) }}%</p> </div> {% endfor %} </body> </html>
Key Adaptations for Your Setup
- Multi-group hosts: If your hosts belong to multiple groups, adjust the
host_groupvariable (e.g., filter for a primary group or loop through all groups the host is in). - Dynamic group detection: Instead of hardcoding
target_groups, usegroups.keys() | list | difference(['all', 'ungrouped'])to auto-detect all custom groups in your inventory. - Extended audit data: Add more metrics (like OS version, disk usage) by enabling
gather_facts: trueor running custom tasks, then pass that data to the Jinja2 template for richer dashboards.
How It All Comes Together
- In the first play, we ping each host, and for successful connections, we send the host’s name and its groups to a list stored on localhost (
alive_hosts). - In the localhost play, we first calculate total hosts per group using the
groupsvariable. Then we iterate over alive hosts and increment the alive count for their respective group. - Finally, we pass the
group_statsdictionary to the Jinja2 template to generate the HTML dashboard.
内容的提问来源于stack exchange,提问作者Rick_y
相关产品推荐
相关产品推荐

