Ansible Playbooks
Let's first change the message of the day on centos hosts.
First let's create our ansible.cfg file,
[defaults]
inventory = hosts
host_key_checking = FalseNext the message of the day itself in a file with the the name centos_motd,
Welcome to CentOs Linux - Ansible RocksNext out inventory file hosts,
[control]
ubuntu-c ansible_connection=local
[centos]
centos1 ansible_port=2222
centos[2:3]
[centos:vars]
ansible_user=root
[ubuntu]
ubuntu[1:3]
[ubuntu:vars]
ansible_become=true
ansible_become_pass=password
[linux:children]
centos
ubuntuFinally our playbook motd_playbook.yaml,
Let's run our playbook now,
This playbook can further improve like below,
So in here I've specified hosts as linux so that it will pick both centos and ubuntu hosts. And the motd has been defined as a variable for each os. Then I've added two tasks with a condition to execute based on the ansible_distribution. Finally a handler to inform us after exeuting each task.
Facts
Ansible facts are host specific confiruations presented to us as variables. Basically when ansible executes it's setup module we can usually notice that it collects facts. In order to get an understanding of how the facts are collected let's execute this command.
In the output of above command you can notice that there's a root dictionary named ansible_facts. Ansible itself will populate all the key value pairs of this dictionary at the root of each hosts variable section, so that these are accessible without any prefix. For example, if we create a file like below,
You can notice that the IPv4 address of the host is accessed in ansible_default_ipv4.address form, where it actually is represented in ansible_facts.ansible_default_ipv4.address in the facts. Now if we run the playbook we might be able to see the IPv4 address of each host specified in our host file.
Custom facts
It is also possible to define custom facts in ansible that will be gatherred during the fact gathering. A custom fact can be any script that returns a JSON structure or ini file. By default it expects to keep these custom facts in /etc/ansible/facts.d/.
In order to try this our let's create two files inside /etc/ansible/facts.d/.
getdate1.fact:
and
gatedate2.fact:
Now if we execute below,
We'll get the data output from the ansible_local section.
Last updated
Was this helpful?