You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过SaltStack mine.get获取Minion grains的目标值?

解决SaltStack Mine.get提取Minion Grains值的问题

问题分析

你遇到的核心问题是:mine.get返回的结果是以Minion主机名为键的字典结构,而非列表,所以用索引[1]取值会报错。比如:

  • ipv4返回{'HOSTNAME': 'IP_ADDRESS'},键是目标Minion的主机名,值是IP
  • monitoring返回{'HOSTNAME': {'probe': {...}}},键是主机名,值是包含探针配置的字典

你需要通过当前节点的host变量作为键,提取对应的值。

解决方案

1. 修改Nagios配置模板(node.cfg.j2)

直接通过host变量作为字典键,提取IP和探针配置,同时遍历探针生成Nagios的service定义:

{% set monitoring = salt['mine.get']('fqdn:' + host, 'monitoring', tgt_type='grain') %}
{% set ipv4 = salt['mine.get']('fqdn:' + host, 'ip', tgt_type='grain') %}

{# 提取当前节点的IP和探针配置 #}
{% set node_ip = ipv4[host] %}
{% set node_probes = monitoring[host]['probe'] %}

define host {
  use linux-server
  host_name {{host}}
  alias {{host}}
  address {{node_ip}}
  max_check_attempts 5
  check_period 24x7
  notification_interval 30
  notification_period 24x7
}

{# 遍历探针生成Nagios服务监控配置 #}
{% for probe_name, probe_config in node_probes.items() %}
{% set check_command = probe_config.keys()|first %}
define service {
  use generic-service
  host_name {{host}}
  service_description {{probe_name}}
  check_command {{check_command}}{% for param, val in probe_config[check_command].items() %}!{{val}}{% endfor %}
  max_check_attempts 3
  check_period 24x7
  notification_interval 30
  notification_period 24x7
}
{% endfor %}

2. 优化Mine调用(减少网络请求)

可以一次性获取ip和monitoring两个grains,减少mine.get的调用次数:

{% set node_data = salt['mine.get']('fqdn:' + host, ['ip', 'monitoring'], tgt_type='grain') %}

{% set node_ip = node_data[host]['ip'] %}
{% set node_probes = node_data[host]['monitoring']['probe'] %}

{# 后续host和service定义代码同上 #}

关键说明

  • 字典取值必须用键名,不能用列表索引:因为mine.get针对单Minion查询时,返回的是{主机名: 对应grains值}的结构,所以用当前循环的host变量作为键,就能直接拿到目标值。
  • 探针配置需要遍历解析:你的monitoring grains里的探针是嵌套字典,通过for循环可以逐个生成Nagios的service块,自动带上阈值参数。

内容的提问来源于stack exchange,提问作者rondavel85

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.29 11:57:38