Suren A
Suren A

Reputation: 87

How to show all the host names of hosts within a specific OS in Ansible

Is there any command in Ansible to collect the hostnames of hosts with OS Debain? The file hosts contains no groups!

So a simple command to see the hostnames of hosts containing Debain.

Upvotes: 2

Views: 1190

Answers (2)

MrJohnBBQ
MrJohnBBQ

Reputation: 313

I would add that if you want to target distribution and minimum version (often the case), you could do that with a dictionary. I often use this snippet:

---
- hosts: localhost
  vars:
    minimum_required_version:
      CentOS: 7
      Debian: 11
      Fedora: 31
      RHEL7: 7
      Ubuntu: 21.10

  - name: set boolean fact has_minimum_required_version
    set_fact:
      has_minimum_required_version: "{{ ansible_distribution_version is version(minimum_required_version[ansible_distribution], '>=') | bool }}"

  tasks:
  - name: run task when host has minimum version required
    debug:
      msg: "{{ ansible_distribution }} {{ ansible_distribution_version }} >= {{ minimum_required_version[ansible_distribution] }}"
    when: has_minimum_required_version

You could also dynamically include a playbook fragment that targets specific distributions or versions like so:

- name: Include task list in play for specific distros
  include_tasks: "{{ ansible_distribution }}.yaml"

Which assumes you'd have Debian.yaml, Ubuntu.yaml, etc. defined for each distro you want to support.

Upvotes: 0

Thomas Hirsch
Thomas Hirsch

Reputation: 2318

The setup module, which is implicitly called in any playbook via the gather_facts mechanism, contains some output that you could use.
Look for example for the ansible_distribution fact, which should contain Debian on the hosts you are looking for.

If all you want is that list once, you could invoke the module directly, using the ansible command and grep:

ansible all -m setup -a 'filter=ansible_distribution' | grep Debian

If you want to use that information dynamically in a playbook, you could use this pattern:

---
 - hosts: all
   tasks:
     - name: Do something on Debian
       debug:
         msg: I'm a Debian host
       when: ansible_distribution == 'Debian'

Upvotes: 1

Related Questions