Ansible: Loop over a list of services and disable those from a list of unwanted services which are actually present

别说谁变了你拦得住时间么 提交于 2019-12-24 22:43:41

问题


I'm using Ansible to build a base image from a base installation of RHEL7.5 One 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.

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

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

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

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

Thanks


回答1:


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

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


来源:https://stackoverflow.com/questions/51137660/ansible-loop-over-a-list-of-services-and-disable-those-from-a-list-of-unwanted

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!