Variables in Ansible can be defined in many different places, such as in inventory, in playbooks, in reusable files, in roles, and at the command-line.
Ansible also allows to set variables directly in a task by using the set_fact module.
Variables defined using the set_fact
become associated with the host that the task is running against, that makes them available across subsequent tasks for the entire duration of the play.
Cool Tip: Ansible Playbook – Print Variable & List All Variables! Read more →
Set Variable In Task
Variable Precedence: Per the standard Ansible variable precedence rules, other types of variables have a higher priority, so a variable defined using the set_fact
module may be overridden.
Below you will find an example of how to set and use variables in Ansible tasks using the set_fact
module:
# roles/ansible_variables/tasks/main.yml
---
- name: "Set variables"
set_fact:
user_name: "admin"
user_permissions: "rwx"
- debug:
msg: "The user '{{ user_name }}' has permissions '{{ user_permissions }}'"
Sample output:
TASK [ansible_variables : Set variables] ********************************* ok: [127.0.0.1] => { "ansible_facts": { "user_name": "admin", "user_permissions": "rwx" }, "changed": false } TASK [ansible_variables : debug] ****************************************** ok: [127.0.0.1] => { "msg": "The user 'admin' has permissions 'rwx'" }
Cool Tip: How to set default values for variables in Ansible! Read more →