ansible.builtin.gather_facts – Gathers facts about remote hosts
This module is part of ansible-core and included in all Ansible installations. In most cases, you can use the short module name gather_facts even without specifying the collections: keyword. However, we recommend you use the FQCN for easy linking to the module documentation and to avoid conflicting with other collections that may have the same module name.
New in version 2.8: of ansible.builtin
Synopsis
This module takes care of executing the configured facts modules , the default is to use the ansible.builtin.setup module.
This module is automatically called by playbooks to gather useful variables about remote hosts that can be used in playbooks.
It can also be executed directly by /usr/bin/ansible to check what variables are available to a host.
Ansible provides many facts about the system, automatically.
This module has a corresponding action plugin .
Parameters
Parameter
Choices/ Defaults
Comments
Notes
This module is mostly a wrapper around other fact gathering modules.
Options passed to this module must be supported by all the underlying fact modules configured.
Facts returned by each module will be merged, conflicts will favor ‘last merged’. Order is not guaranteed, when doing parallel gathering on multiple modules.
Источник
gather_facts – Gathers facts about remote hosts¶
New in version 2.8.
Synopsis¶
This module takes care of executing the configured facts modules, the default is to use the setup module.
This module is automatically called by playbooks to gather useful variables about remote hosts that can be used in playbooks.
It can also be executed directly by /usr/bin/ansible to check what variables are available to a host.
Ansible provides many facts about the system, automatically.
Parameters¶
Parameter
Choices/ Defaults
Comments
Notes¶
This module is mostly a wrapper around other fact gathering modules.
Options passed to this module must be supported by all the underlying fact modules configured.
Facts returned by each module will be merged, conflicts will favor ‘last merged’. Order is not guaranteed, when doing parallel gathering on multiple modules.
Examples¶
Status¶
This module is not guaranteed to have a backwards compatible interface. [preview]
Red Hat Support¶
More information about Red Hat’s support of this module is available from this Red Hat Knowledge Base article.
Authors¶
Ansible Core Team
If you notice any issues in this documentation, you can edit this document to improve it.
Ansible facts are data gathered about target nodes (host nodes to be configured) and returned back to controller nodes. Ansible facts are stored in JSON format and are used to make important decisions about tasks based on their statistics. Facts are in an ansible_facts variable, which is managed by Ansible Engine. Ansible facts play a major role in syncing with hosts in accordance with real-time data.
What exactly are Ansible facts and how are they used?
More about automation
Ansible facts are the host-specific system data and properties to which you connect. A fact can be the IP address, BIOS information, a system’s software information, and even hardware information. Ansible facts help the admin to manage the hosts based on their current condition rather than taking the actions directly without having any info about the system’s health.
Here is a scenario: You have to install Apache webserver on all your Linux hosts. You know that Red Hat Enterprise Linux (RHEL)-based hosts work with the Red Hat Package Manager (RPM) and yum/dnf . Other Linux distributions use their own package managers and so it would not be feasible to perform the same task on different systems without modification and reference to those differences. Package names also differ among distributions. For example, on RHEL systems, the Apache web server package is httpd, while in other distributions it’s named apache2.
Here’s an Ansible playbook to demonstrate the issue:
Here, the script will collect information about the system using Ansible facts and then perform the operation accordingly. When installing on RHEL systems, it automatically skips the Ubuntu-based package and vice versa. Similarly, you can use the Ansible facts to perform an operation if the system has a minimal amount of resources available.
In short, using Ansible facts, a system admin can make Ansible smarter by specifying parameters for when to perform tasks and when not to.
Accessing the facts
Ansible facts use the setup module for gathering facts every time before running the playbooks.
Using the Ansible ad-hoc commands
1. Access Ansible facts using ad-hoc commands
The setup module fetches all the details from the remote hosts to our controller nodes and dumps them directly to our screen for the facts to be visible to users.
2. Filtering out a specific value from Ansible facts
Here, the setup module is used to fetch the facts about the system, and further, it will use the filter argument to display the value from the Ansible facts.
Note: Ansible facts are retrieved only when working with playbooks. To access the Ansible facts using ad-hoc commands, use the setup module.
Using the Ansible playbook
To access the variables from Ansible facts in the Ansible playbook, we need to use the actual name without using the ansible keyword.
The gather_facts module from the Ansible playbook runs the setup module by default at the start of each playbook to gather the facts about remote hosts.
3. Accessing facts using Ansible playbook
Fetch the Ansible facts and display them using a playbook.
4. Accessing a specific fact using an Ansible playbook
Fetching the Ansible facts, filtering them, and displaying them using a playbook.
Ansible facts and the datatype
Ansible facts are stored in JSON format and can be placed into three major categories:
List: Stores the list of items and the stored information is written inside square brackets []. These are mostly facts that can have multiple values, e.g., system_capablities . The list is accessed using square brackets and specifying the index.
Kubernetes and OpenShift
Dictionary: Stores the data as a collection of key-value pairs, and the information is stored inside curly brackets <>. These are mostly the facts that have sub-facts inside of them, e.g., memory_mb . Dictionary is accessed using the dot operator.
Ansible Unsafe Text: This type of variable doesn’t have any subpart and stores the data directly, e.g., machine . Ansible Unsafe Text can be accessed directly by using the fact name.
Use type_debug filter to check the datatype for the Ansible facts.
type_debug filter prompts the datatype for the specified fact without printing the value for the fact.
[ Looking for more on system automation? Get started with The Automated Enterprise, a free book from Red Hat. ]
Wrap up
Ansible facts are data about the system which you want to configure. These facts make your Ansible system intelligent by providing the conditions for when to process some task. You can also process by not specifying or using the Ansible facts, but that would make the job as a sysadmin more hectic as the script may fail or change some of the files that were never intended to be modified.
For more information on Ansible facts, please see the official documentation.
Источник
Модуль ios_facts¶
Модуль ios_facts собирает информацию с устройств под управлением IOS.
Информация берется из таких команд:
dir
show version
show memory statistics
show interfaces
show ipv6 interface
show lldp
show lldp neighbors detail
show running-config
Чтобы видеть, какие команды Ansible выполняет на оборудовании, можно настроить EEM applet, который будет генерировать лог сообщения о выполненных командах.
В модуле можно указывать, какие параметры собирать — можно собирать всю информацию, а можно только подмножество. По умолчанию модуль собирает всю информацию, кроме конфигурационного файла.
Какую информацию собирать, указывается в параметре gather_subset. Поддерживаются такие варианты (указаны также команды, которые будут выполняться на устройстве):
all
hardware
dir
show version
show memory statistics
config
show version
show running-config
interfaces
dir
show version
show interfaces
show ip interface
show ipv6 interface
show lldp
show lldp neighbors detail
Собрать все факты:
Собрать только подмножество interfaces:
Собрать всё, кроме hardware:
Ansible собирает такие факты:
ansible_net_all_ipv4_addresses — список IPv4 адресов на устройстве
ansible_net_all_ipv6_addresses — список IPv6 адресов на устройстве
ansible_net_config — конфигурация (для Cisco sh run)
ansible_net_filesystems — файловая система устройства
ansible_net_gather_subset — какая информация собирается (hardware, default, interfaces, config)
ansible_net_hostname — имя устройства
ansible_net_image — имя и путь ОС
ansible_net_interfaces — словарь со всеми интерфейсами устройства. Имена интерфейсов — ключи, а данные — параметры каждого интерфейса
ansible_net_memfree_mb — сколько свободной памяти на устройстве
ansible_net_memtotal_mb — сколько памяти на устройстве
ansible_net_model — модель устройства
ansible_net_serialnum — серийный номер
ansible_net_version — версия IOS
Использование модуля¶
Пример playbook 1_ios_facts.yml с использованием модуля ios_facts (собираются все факты):
Для того, чтобы посмотреть, какие именно факты собираются с устройства, можно добавить флаг -v (информация сокращена):
После того, как Ansible собрал факты с устройства, все факты доступны как переменные в playbook, шаблонах и т.д.
Например, можно отобразить содержимое факта с помощью debug (playbook 2_ios_facts_debug.yml):
Результат выполнения playbook:
Сохранение фактов¶
В том виде, в котором информация отображается в режиме verbose, довольно сложно понять какая информация собирается об устройствах. Для того, чтобы лучше понять, какая информация собирается об устройствах и в каком формате, скопируем полученную информацию в файл.
Для этого будет использоваться модуль copy.
Playbook 3_ios_facts.yml собирает всю информацию об устройствах и записывает в разные файлы (создайте каталог all_facts перед запуском playbook или раскомментируйте задачу Create all_facts dir, и Ansible создаст каталог сам):
Модуль copy позволяет копировать файлы с управляющего хоста (на котором установлен Ansible) на удаленный хост. Но так как в этом случае, указан параметр connection: local , файлы будут скопированы на локальный хост.
Чаще всего, модуль copy используется таким образом:
Но в данном случае нет исходного файла, содержимое которого нужно скопировать. Вместо этого, есть содержимое переменной ios_facts_result, которое нужно перенести в файл all_facts/<>_facts.json.
Для того, чтобы перенести содержимое переменной в файл, в модуле copy вместо src используется параметр content.
параметр to_nice_json — это фильтр Jinja2, который преобразует информацию переменной в формат, в котором удобней читать информацию
переменная в формате Jinja2 должна быть заключена в двойные фигурные скобки, а также указана в двойных кавычках
Так как в пути dest используются имена устройств, будут сгенерированы уникальные файлы для каждого устройства.
Результат выполнения playbook:
После этого в каталоге all_facts находятся такие файлы:
Сохранение информации об устройствах не только поможет разобраться, какая информация собирается, но и может быть полезным для дальнейшего использования информации. Например, можно использовать факты об устройстве в шаблоне.
При повторном выполнении playbook Ansible не будет изменять информацию в файлах, если факты об устройстве не изменились
Если информация изменилась, для соответствующего устройства будет выставлен статус changed. Таким образом, по выполнению playbook всегда понятно, когда какая-то информация изменилась.