FreeKB - Ansible Getting Started with Magic Variables
Ansible - Getting Started with Magic Variables

A magic variable is some piece of information about the control node (that's the Ansible server), such as the version of Ansible or the hosts in inventory. A magic variable is one of the three types of special variables. The other two special variables are facts and connection variables. For example, the ansible_version magic variable contains the version of Ansible, like this.

- name: output the 'ansible_default_ipv4' magic variable
    msg: "{{ ansible_default_ipv4 }}"


Which should return something like this.

TASK [output the 'ansible_default_ipv4' magic variable]
ok: [] => {
    "msg": {
        "address": "",
        "alias": "eno16777984",
        "broadcast": "",
        "gateway": "",
        "interface": "eno16777984",
        "macaddress": "00:0c:29:fc:f5:79",
        "mtu": 1500,
        "netmask": "",
        "network": "",
        "type": "ether"


Be aware that if the gather_facts plugin is set to false, the magic variables will be undefined, and something like will be returned. Likewise, if the gather facts plugin is set to true but setup gather_subset has !network, the same fatal error will be returned.

TASK [output the 'ansible_default_ipv4' magic variable]
fatal: []: FAILED! => {"msg": "The task includes an option with an undefined variable. The error was: 'ansible_default_ipv4' is undefined\n\nThe error appears to be in '/home/jeremy.canfield/testing.yml': line 11, column 7, but may\nbe elsewhere in the file depending on the exact syntax problem.\n\nThe offending line appears to be:\n\n\n    - name: output the 'ansible_default_ipv4' magic variable\n      ^ here\n"}


Magic variables are reserved. When using the vars or set_fact module, you shouldn't create a variable that has the same name as a magic variable, such as "ansible_version". Don't do this:

- name: set_fact ansible_version
    ansible_version: "123"


Two of the most commonly used magic variables are inventory_hostname and hostvars.

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 51fc7 in the box below so that we can be sure you are a human.


Web design by yours truely - me, myself, and I   |   |