循环服务列表并从实际存在的不需要的服务列表中禁用这些服务

循环服务列表并从实际存在的不需要的服务列表中禁用这些服务

本文介绍了Ansible:循环服务列表并从实际存在的不需要的服务列表中禁用这些服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Ansible 从 RHEL7.5 的基础安装构建基础镜像我想做的一件事是禁用不需要的服务.所以我这样做:

I'm using Ansible to build a base image from a base installation of RHEL7.5One of the things I want to do is to disable unwanted services. So I do this:

- name: "| disable unwanted services"
  service:
    name: "{{ item }}"
    enabled: no
    state: stopped
  loop: "{{ disabled_services }}"
  when: disabled_services is defined

哪个工作正常,在本地主机上测试;然后我在测试版本上尝试它,它出错了,因为我试图管理的服务之一甚至不存在.

Which works fine, testing on localhost; then I try it on a test build, and it errors because one of the services I'm trying to manage isn't even present.

例如,disabled_services == "ntp postfix ip6tables",但未安装 ip6tables.我会从模块中收到这样的错误:

Say for example that disabled_services == "ntp postfix ip6tables", but ip6tables isn't installed. I'll get an error from the module like so:

ok: [udggsydasd48] => (item=postfix)
failed: [udggsydasd48] (item=ip6tables) => {"changed": false, "item":"ip6tables", "msg": "Could not find the requested service ip6tables: host"}

所以我调用 service_facts 模块来生成正在运行的服务列表.在这个循环中,我会将if service in services"条件放在这个循环中的什么(和哪里):

So I'm calling the service_facts module to generate a list of running services. What ( and where) in this loop would I put the "if service in services" conditional in this loop:

- name: "| disable unwanted services"
  service:
    name: "{{ item }}"
    enabled: no
    state: stopped
  loop: "{{ disabled_services }}"
  when: disabled_services is defined

如果软件存在,它只会尝试从disabled_services"中的阵列禁用服务?

So that it will only attempt to disable services from the array in "disabled_services" if the software is present?

我宁愿不使用fail_when:从不,因为这会隐藏其他错误.

I'd rather not use a fail_when: never, as this can hide other errors.

谢谢

推荐答案

在加载正在运行的 services 列表后,使用 union filter.

After you load the list of running services, use the union filter.

  loop: "{{ disabled_services | union(services) }}"

这篇关于Ansible:循环服务列表并从实际存在的不需要的服务列表中禁用这些服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 20:24