If you are not familiar with modules, check out Ansible - Getting Started with Modules.
The set_fact module is used to create your own variable or array. In this example, the "foo" variable contains a value of "Hello World".
---
- hosts: all
tasks:
- set_fact:
foo: "Hello World"
AVOID TROUBLE
The -e or --extra-vars command line option or Extra Variables in Tower will take precedence over set_fact.
The debug module can be used to print the variable.
- name: output the content of the 'foo' variable
debug:
var: foo
Which should produce the following.
TASK [output the content of the 'foo' variable]
ok: [server1.example.com] => {
"foo": "Hello World"
}
Redefine variable
Let's say you used the vars plugin to give the "foo" key a value of "Hello", like this.
vars:
foo: "Hello"
set_facts can be used to update the value of the "foo" key. In this example, the "foo" key will be updated to have a value of "World".
set_fact:
foo: "World"
Array
Refer to Ansible - set_facts module (array of values) for the steps on how to create an array.
From an Ansible Fact to a variable
Commonly, set_fact is used to create a variable of an Ansible Fact. For example, let's say the df command on server1 returns the following.
[john.doe@server1 ~]# df
Filesystem 1K-blocks Used Available Use% Mounted on
/dev/sda1 372607 170989 177862 50% /boot
/dev/sda2 129774 6994 122780 6% /
Here is how you would create a variable named foo that contains the available bytes of /dev/sda1 (177862).
---
- hosts: localhost
tasks:
- set_fact:
size: "{{ item.size_available }}"
with_items: "{{ ansible_mounts }}"
- debug:
var: size
...
Which should return the following.
TASK [debug]
ok: [localhost] => {
"size": "177862"
}
AVOID TROUBLE
Notice 177862 is wrapped in double quotes, meaning that the size variable contains a string, not an integer, which can be confirmed using the type_debug filter. This is because Jinja2 templating (the double curly braces) always returns a string. However, you can apply some of type filter, such as the bool or int filter in a when statement because Jinja2 templating cannot be used in a when statement.
---
- hosts: localhost
tasks:
- set_fact:
size: "{{ item.size_available }}"
with_items: "{{ ansible_mounts }}"
- debug:
msg: size is greater than 123456
when: size | int > 123456
...
when
The when module can be used to set facts when a condition evaluates to true or false, like this.
---
- hosts: all
tasks:
- set_fact:
env: "dev"
when: inventory_hostname is search ('dev')
- set_fact:
env: "prod"
when: inventory_hostname is search ('prod')