Shashikant shah

Friday, 16 October 2020

What is Ansible facts and custom facts part-3

 What is Ansible facts.

Ansible facts is a term used for system information of the remote nodes. When running playbooks, the first task that Ansible does is the execution of setup task. Now the system information could be about OS distribution, release, processor, IP address, disk etc.

Ansible implements fact collecting through the use of a special module called the setup module. You don’t need to call this module in your playbooks because Ansible does that automatically when it gathers facts. The gather_facts is set to true by default.

First check remote node after that run task in remote node.

#  ansible -m setup hostname

# ansible server2 -m setup -a 'filter="ansible_kernel"'

1.  Fetch MAC address  from remote hosts.

# vi test.yml

- hosts: all
  gather_facts: true
  tasks:
    - name: Ansible fact for mac address
      debug:
        msg: "{{ ansible_default_ipv4.macaddress }}"




2. fetch OS details from remote hosts.

# vim  OS.yml

- hosts: all
  gather_facts: true
  tasks:
    - name: Ansible fact OS 
      debug:
        msg: "{{ ansible_distribution }}"

# ansible-playbook   OS.yml




How to create Custom/ local fact :-

Ansible also provides an additional mechanism for associating facts with a host. You can place one or more files on the host machine in the /etc/ansible/facts.d directory.

In .ini format

In JSON format

# cd  /etc/ansible/facts.d

# vim date_time.fact

#!/bin/bash

DATE=$(date)

cat << EOF

{ "remote": "$DATE" }

EOF

# chmod +x  date_time.fact

1. fetch variable from localhost.

# ansible localhost -m setup -a "filter=ansible_local"


1.       2. Run custom fact from remote server. (-b for root permission)

# ansible jenkins -m file -a "path=/etc/ansible/facts.d state=directory" -b
# ansible jenkins -m copy -a "src=/etc/ansible/facts.d/ date_time.fact dest=/etc/ansible/facts.d/ date_time.fact mode=0755" -b
#ansible  all -m setup -a "filter=ansible_local"



No comments:

Post a Comment