top of page

Ansible Magic Variable


Ansible Magic Variable

In Ansible, magic variables are special variables that provide information about the current execution context, hosts, and other runtime details. These variables are automatically set by Ansible, and you can reference them in your playbooks and roles. Magic variables are prefixed with ansible_.


Here are some commonly used Ansible magic variables:


ansible_play_hosts:

Contains a list of all the hosts in the current play. This is useful when you want to loop through all hosts in a play.

[root@siddhesh ~]# cat ansible_play_hosts.yml
- name: Example using ansible_play_hosts
  hosts: all
  tasks:
    - debug:
        var: ansible_play_hosts
[root@siddhesh ~]#

ansible_hostname:


Represents the hostname of the current managed node.

[root@siddhesh ~]# cat ansible_hostname.yml
- name: Example using ansible_hostname
  hosts: all
  tasks:
    - debug:
        var: ansible_hostname
[root@siddhesh ~]#

ansible_distribution:

Provides the name of the distribution (e.g., Ubuntu, CentOS) on the target host.

[root@siddhesh ~]# cat ansible_distribution.yml
- name: Example using ansible_distribution
  hosts: all
  tasks:
    - debug:
        var: ansible_distribution
[root@siddhesh ~]#

ansible_facts:


Contains a dictionary of all facts about the current system.

[root@siddhesh ~]# cat ansible_facts.yml
- name: Example using ansible_facts
  hosts: all
  tasks:
    - debug:
        var: ansible_facts
[root@siddhesh ~]#

ansible_architecture:


Provides the architecture of the target host (e.g., x86_64).

[root@siddhesh ~]# cat ansible_architecture.yml
- name: Example using ansible_architecture
  hosts: all
  tasks:
    - debug:
        var: ansible_architecture
[root@siddhesh ~]#

ansible_env:


Contains a dictionary of environment variables on the Ansible control machine.

[root@siddhesh ~]# cat ansible_env.yml
- name: Example using ansible_env
  hosts: localhost
  tasks:
    - debug:
        var: ansible_env
[root@siddhesh ~]#

These are just a few examples, and there are many more magic variables available. You can find a comprehensive list in the official Ansible documentation: Magic Variables


bottom of page