Ansible - Getting Started with Magic Variables
by
Jeremy Canfield |
Updated: January 31 2022
| Ansible articles
In Ansible, there are three types of Special Variables.
- Connection Variables
- Magic Variables (this article)
- Facts
A magic variable are variables that are built into Ansible. Following are the magic variables.
- ansible_check_mode
- ansible_config_file
- ansible_dependent_role_names
- ansible_diff_mode
- ansible_forks
- ansible_inventory_sources
- ansible_limit
- ansible_loop
- ansible_loop_var
- ansible_index_var
- ansible_parent_role_names
- ansible_parent_role_paths
- ansible_play_batch
- ansible_play_hosts
- ansible_play_hosts_all
- ansible_play_name
- ansible_play_role_names
- ansible_playbook_python
- ansible_role_names
- ansible_collection_name
- ansible_run_tags
- ansible_search_path
- ansible_skip_tags
- ansible_verbosity
- ansible_version
- group_names
- groups
- hostvars
- inventory_hostname
- inventory_hostname_short
- inventory_dir
- inventory_file
- omit
- play_hosts
- playbook_dir
- role_name
- role_names
- role_path
For example, let's say you have a playbook named version.yml and version.yml contains the following.
---
- hosts: localhost
tasks:
- debug:
var: ansible_version
...
You can run the version.yml playbook using the ansible-playbook command.
ansible-playbook version.yml
Which should return something like this.
TASK [debug]
ok: [localhost] => {
"ansible_version": {
"full": "2.9.27",
"major": 2,
"minor": 9,
"revision": 27,
"string": "2.9.27"
}
}
Did you find this article helpful?
If so, consider buying me a coffee over at
Comments
January 31 2022 by vergissmiNET
Sorry but this article is a complete mess. You start talking about magic variables and give a (completely different) fact as an example. And what has 'gather_facts' to do with magic vars?
[ansible@ansible-control http]$ cat magiclocal.yml
---
- name: test
hosts: localhost
gather_facts: False
tasks:
- debug:
var: ansible_version
[ansible@ansible-control http]$ ap magiclocal.yml
PLAY [test] *********************************************************************************************
TASK [debug] ********************************************************************************************
ok: [localhost] => {
"ansible_version": {
"full": "2.9.27",
"major": 2,
"minor": 9,
"revision": 27,
"string": "2.9.27"
}
}
PLAY RECAP **********************************************************************************************
localhost : ok=1 changed=0 unreachable=0 failed=0 skipped=0 rescued=0 ignored=0
January 31 2022 by Jeremy (moderator)
Yeah, this article was confusing. I was way overdue to clean up this article. I got this article cleaned up so that it makes sense now.