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
  debug:
    msg: "{{ ansible_default_ipv4 }}"

 

Which should return something like this.

TASK [output the 'ansible_default_ipv4' magic variable]
ok: [server1.example.com] => {
    "msg": {
        "address": "192.168.0.6",
        "alias": "eno16777984",
        "broadcast": "192.168.0.255",
        "gateway": "192.168.0.1",
        "interface": "eno16777984",
        "macaddress": "00:0c:29:fc:f5:79",
        "mtu": 1500,
        "netmask": "255.255.255.0",
        "network": "192.168.0.0",
        "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: [server1.example.com]: 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
  set_fact:
    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.




Comments

Web design by yours truely - me, myself, and I   |   jeremy.canfield@freekb.net   |