6

我正在尝试构建一种自包含系统,在其中我将我的应用程序可执行文件复制到一个地方并将服务作为独立应用程序运行,无需安装。我正在使用 NSSM 可执行文件在 Windows Server 2012 R2 中创建服务,并且在一台机器上,会有很多可部署的。我的问题是,在使用 Ansible 自动部署时,我被困在我需要知道给定服务名称是否已经存在的点上,如果是,它的状态是什么?NSSM 中似乎没有任何 API 可以检查这一点。我如何通过命令行询问 NSSM 是否存在服务?我可以通过命令行(无 powershell)检查服务的存在和状态吗?

4

1 回答 1

14

好吧,没有办法仅通过 NSSM 获取服务详细信息,所以我想出了一些其他方法来获取 ansible 中的 Windows 服务详细信息:

1)使用 sc.exe 命令 util sc 实用程序可以查询 windows 机器以获取有关给定服务名称的详细信息。我们可以在变量中注册这个查询的结果,并在条件中的其他任务中使用它。

---
- hosts: windows
  tasks:
    - name: Check if the service exists
      raw: cmd /c sc query serviceName
      register: result

    - debug: msg="{{result}}"

2)使用Get-Service Powershell命令'Get-Service'可以像sc util一样为您提供有关服务的详细信息:

---
- hosts: windows
  tasks:
    - name: Check if the service exists
      raw: Get-Service serviceName -ErrorAction SilentlyContinue
      register: result

    - debug: msg="{{result}}"

3) win_service 模块(推荐) Ansible 的模块 win_service 可以通过不指定任何操作来简单地获取服务详细信息。唯一的问题是服务不存在的情况,它会使任务失败。这可以使用 failed_when 或 ignore_errors 来解决。

---
- hosts: windows
  tasks:
     - name: check services
      win_service:
          name: serviceName
      register: result
      failed_when: result is not defined
      #ignore_errors: yes

    - debug: msg="{{result}}"

    - debug: msg="running"
      when: result.state is not defined or result.name is not defined
于 2016-03-22T07:00:13.110 回答