根据给定的服务列表查找目标 windows 主机中的哪些服务 运行,如果服务不是 运行 则启动

Finding Which services are running in target windows host based on given service list and start if the service is not running

我有一组 windows 服务,需要查明这些服务是否在目标 windows 主机中 运行。如果至少有一项服务没有 运行 我需要启动这些服务并且需要将启动模式设置为自动。

- name: Check weather service is running or not
    ansible.windows.win_service_info:
      name: "{{ item }}"
    register: win_service_info
    with_items:
      - BrokerInfrastructure #Background Tasks Infrastructure (BrokerInfrastructure) Service
      - DcomLaunch #DCOM Server Process Launcher Service
      - gpsvc #Group Policy Client Service
      
  - name: Start the services
    ansible.windows.win_service:
      name: << don't know how to write this part >>
      start_mode: auto
      state: started
    register: service_startup 
    with_items: "{{ win_service_info.results }}"
    when: << don't know how to write this part >>

您不需要事先找到服务状态。只需描述服务应该处于的状态,ansible 将报告 changed 如果它必须修改任何东西(启动服务,更改启动模式...)或 ok 如果它已经在预期状态。

  - name: Start/modify the services if needed
    ansible.windows.win_service:
      name: "{{ item }}"
      start_mode: auto
      state: started
    with_items:
      - BrokerInfrastructure 
      - DcomLaunch
      - gpsvc

现在,如果您仍想在执行特定任务之前检测服务状态,您应该简单地调试 win_service_info.results 变量以获得一个很好的概览。我无法自己测试,因为我手边没有 windows 盒子。但是如果我相信win_service_info module's returned values documentation,你可以这样做:

- name: do something depending on service state
  debug:
    msg: "I would do something because service {{ item.services.0.name }}
           is in state {{ item.services.0.state }}"
  when:
    - item.exists
    - item.services.0.state in ['stopped', 'paused']
  loop: "{{ win_service_info }}"