Search code examples
salt-project

salt stack if then else for service


I have a windows service which I deploy from salt stack. The state looks like this

create_executable:
   module.run:
     -  name:  service.create
     -  m_name:  SVC1
     -  bin_path:  d:\svc1.exe
     -  start_type:  auto

Now, when I redeploy the service, it says "Exception: Service Already Exists: SVC1". Is there a way to test if the service is running? If the s ervice is running, I would like to stop it, disable it, delete it and then recreate it.


Solution

  • Maybe module.wait together with a cmd.run that uses the unless feature might help in this case.

    You need a nice way to check that the service is not installed and use this in the unless test. The command itself might something like echo - it does not really matter. You can now use watch or watch_in to make the module.wait relying on cmd.run.

    untested draft (note that I don't know windows cli at all):

    check_if_service_installed:
      cmd.run:
        name: echo 'not installed'
        unless: 'if exists c:\svc1.exe'
    
    create_executable:
      module.wait:
        - name:  service.create
        - m_name:  SVC1
        - bin_path:  d:\svc1.exe
        - start_type:  auto
        - watch:
          - cmd: check_if_service_installed
    

    After writing I think that this looks a little complicated for what you try to achieve. Maybe a small batch or powershell script which takes care of being able to be executed again is more straight forward. But this is a matter of taste IMO.