使用服务与命令时失败

3 ansible ansible-playbook

我想确保在系统上存在服务列表时禁用它们.默认情况下,其中许多服务不存在,但在安装服务的情况下,我希望它被禁用.

如果服务不存在,ansible会抛出错误.虽然我可以使用ignore_error继续执行任务,但我对此并不满意,因为它不仅掩盖了真正的问题,而且错误仍然显示在ansible输出中,我更喜欢团队不习惯忽略错误.

我尝试过使用failed_when,但我似乎无法使用服务,并且所有示例都使用命令,而不是服务.这是任务 - disable_services是在别处声明的列表.

- name: "Stop and disable unneeded services"
  service: name={{ item }} enabled=no status=stopped
  failed_when: "'service not loaded' not in stderr"
  with_items: disable_services
Run Code Online (Sandbox Code Playgroud)

它失败并带有以下输出:

TASK: [hardening | Stop and disable unneeded services] ************************ 
fatal: [host.example.com] => error while evaluating conditional: 'service not loaded' not in stderr  
Run Code Online (Sandbox Code Playgroud)

我已经尝试注册变量service_output,并检查是否在service_output.stderr中看到"service not loaded",但是具有相同的错误.

是否可以在服务上使用failed_when,如果是,我在这里遇到的第8层问题是什么?

小智 11

有一些问题:

  1. state,不是status.
  2. 您需要使用register将结果绑定到变量,然后使用该变量failed_when.
  3. 小问题:你只检查一种失败(在这种情况下应该没问题,但要注意这一点).

这应该工作:

- name: "Stop and disable unneeded services"
  service: name={{ item }} enabled=no state=stopped
  failed_when: "stop_disabled_services | failed and 'service not found' not in stop_disabled_services.msg"
  register: stop_disabled_services
  with_items: disable_services
Run Code Online (Sandbox Code Playgroud)

并且说明了我如何使用此代码:我已经使用ignore_errorsdebug: var=stop_disable_services查找service失败的返回值.最有趣的部分是的物品stop_disabled_services.results清单,因为这是价值stop_disable_servicesfailed_when将拭目以待.从那里只有一些Jinja2确保只有一些失败被忽略.