Petr
Petr

Reputation: 14505

Ansible run playbook only for hosts that match some variables

I have a playbook that I want to execute on RHEL 6 servers only. I know I can put

when: ansible_distribution == "RedHat" and ansible_distribution_major_version == 6

Into every single task within the whole playbook, but that seems pretty inefficient to me.

Isn't there a way to limit whole playbook to these machines so that I don't have to put this line into every single task?

I suppose it would even execute much faster, because it wouldn't need to check if server is RedHat 6 in every single task.

Also, I assume that most performance-wise efficient way would be to store a list of RHEL 6 servers aside and execute this playbook on them only, as Ansible isn't really caching this information, so it would always have to connect to all servers just to figure out whether they are RHEL and version 6?

Upvotes: 1

Views: 4198

Answers (2)

Konstantin Suvorov
Konstantin Suvorov

Reputation: 68339

Use include with with_first_found:

- include: "{{ include_path }}"
  with_first_found:
   - "{{ ansible_distribution }}.yml"
   - "{{ ansible_os_family }}.yml"
   - "default.yml"
  loop_control:
    loop_var: include_path

Update: added loop_var to prevent possible item variable collision.

Upvotes: 3

Henrik Pingel
Henrik Pingel

Reputation: 3203

One strategy to deal with this problem is to include a task file with the task specific for a distribution version like this in the main task file:

- include: "{{ ansible_distribution }}-{{ ansible_distribution_major_version }}.yml"

The file tasks/RedHat-6.yml would than contain all tasks specific for RHEL6.

When you want to your playbook to fail when the distribution is not supported you could do something like this:

- include: RedHat6.yml
  when: ansible_distribution == "RedHat" and ansible_distribution_major_version == 6

- fail:
    msg: "Distribution not supported"
    when: ansible_distribution != "RedHat" or whatever conditions you want

Upvotes: 1

Related Questions