【问题标题】:Finding Which services are running in target windows host based on given service list and start if the service is not running根据给定的服务列表查找目标 Windows 主机中正在运行的服务,并在服务未运行时启动
【发布时间】:2021-08-21 03:13:29
【问题描述】:

我有一组 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 windows-services system-administration


    【解决方案1】:

    您无需事先查找服务状态。只需描述服务应该处于的状态,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 }}"
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-05
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      • 1970-01-01
      相关资源
      最近更新 更多