Search code examples
ansiblewindows-servicessystem-administration

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


I have a set of windows services and need to find out whether those services are running in the target windows host. If at least one of the services no running I need to start those services and need to set the start mode to auto.

- 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 >>

Solution

  • You don't need to find the service state beforehand. Just describe the state in which the service should be, ansible will report changed if it had to modify anything (start the service, change the start mode...) or ok if it was already in the expected state.

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

    Now if you still want to detect the service state prior to doing a specific task, you should simply debug your win_service_info.results variable to have a pretty good overview. I cannot test that myself since I don't have any windows box at hand. But if I believe the win_service_info module's returned values documentation, you can do something like the following:

    - 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 }}"