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

如何通过Ansible结合API密钥从多台Nagios监控中移除多台服务器

问题:Ansible批量从多Nagios服务器移除主机时API密钥无法正确获取

需求

通过Ansible使用API密钥,将多台服务器从多台Nagios监控系统中移除,但当前配置无法正确获取API密钥,且无成功输出。

现有配置

hosts文件

[nagios_server]
10.0.0.1 apikey=XXXXXXXX
10.0.0.2 apikey=YYYYYYYY
10.0.0.3 apikey=ZZZZZZZZ

[Linux_remove_machine]
192.168.0.1
192.168.0.2

main.yml

---
- name: remove server from monitoring
  hosts: localhost
  vars:
    output_path: "./reports/"
    filename: "device_report_{{ date }}.csv"
  tasks:
    - include_tasks: nagios.yml
      loop: "{{ groups['nagios_server'] }}"
      loop_control:
        loop_var: outer_item
      register: check
    - debug:
        var=check

nagios.yml

- name: execute command in loop
  shell:
  curl -XDELETE "http://{{ outer_item }}/nagiosxi/api/v1/config/host?apikey=**{{apikey }}**&host_name={{ item }}&applyconfig=1

  loop: "{{groups['Linux_remove_machine']}}"
  register: remove_nagios

期望输出

curl -XDELETE "http://10.0.0.1/nagiosxi/api/v1/config/host?apikey=XXXXXXXX&host_name=192.168.0.1&applyconfig=1"
curl -XDELETE "http://10.0.0.2/nagiosxi/api/v1/config/host?apikey=YYYYYYYY&host_name=192.168.0.1&applyconfig=1"
curl -XDELETE "http://10.0.0.3/nagiosxi/api/v1/config/host?apikey=ZZZZZZZZ&host_name=192.168.0.1&applyconfig=1"

curl -XDELETE "http://10.0.0.1/nagiosxi/api/v1/config/host?apikey=XXXXXXXX&host_name=192.168.0.2&applyconfig=1"
curl -XDELETE "http://10.0.0.2/nagiosxi/api/v1/config/host?apikey=YYYYYYYY&host_name=192.168.0.2&applyconfig=1"
curl -XDELETE "http://10.0.0.3/nagiosxi/api/v1/config/host?apikey=ZZZZZZZZ&host_name=192.168.0.2&applyconfig=1"

问题分析与修正方案

核心问题

  1. API密钥变量引用错误:原配置中{{ apikey }}无法直接获取对应Nagios服务器的密钥,因为outer_item仅为主机名,需通过hostvars字典读取主机变量。
  2. curl命令语法错误:原命令未闭合引号,导致命令无法正确解析执行。
  3. Shell模块写法不规范:命令行未正确缩进,语法不符合Ansible要求。

修正后的nagios.yml

- name: 执行移除主机的API请求
  shell: |
    curl -XDELETE "http://{{ outer_item }}/nagiosxi/api/v1/config/host?apikey={{ hostvars[outer_item]['apikey'] }}&host_name={{ item }}&applyconfig=1"
  loop: "{{ groups['Linux_remove_machine'] }}"
  register: remove_nagios
- name: 打印API请求结果
  debug:
    var: remove_nagios

修正说明

  • 使用hostvars[outer_item]['apikey']准确读取对应Nagios服务器的API密钥。
  • 闭合curl命令的引号,修正语法错误。
  • 用|规范Shell命令的书写格式,确保Ansible正确解析。
  • 添加debug任务查看API请求的执行结果,便于排查问题。

验证执行

运行playbook后,通过debug模块可以看到每个curl命令的执行情况,输出的命令行将与期望一致,同时能获取API返回的结果,确认移除操作是否成功。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 07:00:57