Ansible: Loop over a list of services and disable

2019-08-24 04:12发布

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条回答
乱世女痞
2楼-- · 2019-08-24 04:53

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

  loop: "{{ disabled_services | union(services) }}"
查看更多
登录 后发表回答