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

使用Ansible win_service_info获取服务start_mode时变量未定义问题

问题与解决:Ansible访问Windows服务信息变量报错

问题详情

运行Ansible Playbook获取Windows服务信息时,调试services_Info.services能正常输出结果,但直接访问services_Info.services.start_mode却提示变量未定义。

我的Playbook

- name: Testing
  hosts: testing
  become: false
  gather_facts: false

  tasks:
    - name: Services Info
      ansible.windows.win_service_info:
        name: WSearch
      register: services_Info

    - name: Output Services
      debug:
        var: services_Info.services

    - name: Output Services
      debug:
        var: services_Info.services.start_mode

调试services_Info.services的输出

{"services_Info.services": [{"checkpoint": 0,"controls_accepted": [],"dependencies": ["RPCSS","BrokerInfrastructure"],"dependency_of": ["WMPNetworkSvc"],"description": "Provides content indexing, property caching, and search results for files, e-mail, and other content.","desktop_interact": false,"display_name": "Windows Search","error_control": "normal","failure_actions": [{"type": "restart","delay_ms": 30000},{"type": "restart","delay_ms": 30000},{"type": "restart","delay_ms": 30000},{"type": "restart","delay_ms": 30000},{"type": "restart","delay_ms": 30000},{"type": "none","delay_ms": 0}],"failure_actions_on_non_crash_failure": true,"failure_command": null,"failure_reboot_msg": null,"failure_reset_period_sec": 86400,"launch_protection": "none","load_order_group": "","name": "WSearch","path": "C:\\Windows\\system32\\SearchIndexer.exe /Embedding","pre_shutdown_timeout_ms": 10000,"preferred_node": null,"process_id": 0,"required_privileges": ["SeChangeNotifyPrivilege","SeManageVolumePrivilege","SeImpersonatePrivilege","SeAssignPrimaryTokenPrivilege","SeIncreaseQuotaPrivilege","SeTcbPrivilege"],"service_exit_code": 0,"service_flags": [],"service_type": "win32_own_process","sid_info": "unrestricted","start_mode": "disabled","state": "stopped","triggers": [],"username": "NT AUTHORITY\\SYSTEM","wait_hint_ms": 0,"win32_exit_code": 0}],"_ansible_verbose_always": true,"_ansible_no_log": null,"changed": false}

报错信息

尝试访问services_Info.services.start_mode时,得到报错:

"services_Info.services.start_mode": "VARIABLE IS NOT DEFINED!"


解决方法

原因

从输出可以明确看到,services_Info.services是一个列表(数组),哪怕只有一个服务对象,也不能直接通过.start_mode访问列表的属性,必须先定位到列表中的具体元素。

两种有效访问方式

  1. 通过索引直接访问
    当前结果只有一个服务,用索引[0]定位元素后再访问属性:
- name: Output Services start_mode
  debug:
    var: services_Info.services[0].start_mode
  1. 循环遍历服务列表
    如果后续可能返回多个服务,推荐用循环遍历每个服务的属性,适用性更广:
- name: Output each service's start_mode
  debug:
    var: item.start_mode
  loop: "{{ services_Info.services }}"

内容的提问来源于stack exchange,提问作者Joe M.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 20:34:53