what is set_fact
Set fact is a module which allows setting new variables. These variables are set on a host-by-host base just like facts discovered by the setup module.
In ansible, there are some default info of hosts in hostvars
variable, such as “ansible_check_mode”, “group_names” etc, and also the “ansible_facts”, which is not default show up, only when gather_facts
is set to “yes”, it will show the details of ansible_fact. Except these two kinds of info, I can also use set_fact module to create my own info pair.
1 | - name: set fact |
Let’s look at he output of this playbook,
1 | anna@ansible-controller:~/Desktop/ansible-code/inventory/modules/set-fact module$ ansible-playbook site.yml |
eventhought gather_facts
is “no”, ansible still show some basic info of every hosts.
If gather_facts
is “yes”, except the default info, ansible will show ansible-facts
info which included a lots of system info of every hosts.
If I add set_fact
module, and create a variable named test_set_fact
, it will show in the output of hostvars, notice line 56 and line 105
1 | - name: set fact |
Let’s look at the output
1 | anna@ansible-controller:~/Desktop/ansible-code/inventory/modules/set-fact module$ ansible-playbook site.yml |
At last line of every hosts,I can see the "test_set_fact": "variable from set fact"
, which is the variable and value I set in the playbook before.
How to use set_fact varible
I can call this variable directly in playbook
1 | tasks: |
debug module will show only test_set_fact variable
1 | anna@ansible-controller:~/Desktop/ansible-code/inventory/modules/set-fact module$ ansible-playbook site.yml |
another example
I am going to get the every hosts’s hostname info.
1 | tasks: |
I put all the output of command cat /etc/hosts
into variable named hosts_result
, then it will show like this
1 | anna@ansible-controller:~/Desktop/ansible-code/inventory/modules/set-fact module$ ansible-playbook site.yml |
but I only want the “stdout_lines” info, so I am going to set “stdout_lines” to a variable named host_ip
, and use set_fact module to do this, modified the playbook like this:
1 | tasks: |
So the output will be like this
1 | anna@ansible-controller:~/Desktop/ansible-code/inventory/modules/set-fact module$ ansible-playbook site.yml |
It will show only the host ip which I want.