FreeKB - set_fact module
Ansible - set_fact module

This assumes you have installed Ansible, are familiar with the ansible-playbook command and facts, and have created a playbook. If you are not familiar with variables, check out our article Getting Started with variables.

The set_fact module is used to create your own facts. In this example, a fact named "foo" is created with a value of "Hello World".

---
- hosts: all
  tasks:
    - set_fact: 
        foo: "Hello World"

 

The debug module can be used to print the variable.

- debug:
    msg: "{{ foo }}"

 

Which should produce the following.

TASK [debug]
ok: [server1.example.com] => {
    "msg": "Hello World"
}

 


Redefine variable

Let's say you used the vars module 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.

 


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')

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




Please enter a18e5 in the box below so that we can be sure you are a human.




Comments