Return Host Variables with Ansible

From Knowledge Center
Jump to: navigation, search

Inventory

This playbook demonstrates how you can return shell output and also return host variables

inventory.ini

[admin]
localhost

[admin:vars]
location_country="South Africa"
location_city="Cape Town"

Playbook

debug.yml

---
- hosts: admin
  tasks:
  - debug:
      msg: "System {{ inventory_hostname }} has uuid {{ ansible_product_uuid }}"

  - debug:
      msg: "System {{ inventory_hostname }} has gateway {{ ansible_default_ipv4.gateway }} and IP {{ ansible_default_ipv4.address }}"
    when: ansible_default_ipv4.gateway is defined

  - name: register uptime
    shell: /usr/bin/uptime
    register: result

  - debug: msg="{{result.stdout}}"
  - debug: var=result['stdout']
  - debug: msg="{{result['stdout']}}"

  - debug:
      var: hostvars[inventory_hostname]['ansible_nodename']

Running the Playbook

$ ansible-playbook -i inventory.ini debug.yml

PLAY [admin] ***************************

TASK [Gathering Facts] *******************************
ok: [localhost]

TASK [debug] ***************************
ok: [localhost] => {
    "msg": "Host: localhost has uuid F252C4F4-3EA9-4349-A130-C3F4278AC695"
}

TASK [debug] ***************************
ok: [localhost] => {
    "msg": "Host: localhost has gateway 197.85.7.1 and IP 197.85.7.248"
}

TASK [register uptime] ***************************
changed: [localhost]

TASK [debug] ***************************
ok: [localhost] => {
    "msg": " 22:07:23 up 72 days, 23:56,  2 users,  load average: 0.00, 0.00, 0.00"
}

TASK [debug] ***************************
ok: [localhost] => {
    "result['stdout']": " 22:07:23 up 72 days, 23:56,  2 users,  load average: 0.00, 0.00, 0.00"
}

TASK [debug] ***************************
ok: [localhost] => {
    "msg": " 22:07:23 up 72 days, 23:56,  2 users,  load average: 0.00, 0.00, 0.00"
}

TASK [debug] ***************************
ok: [localhost] => {
    "hostvars[inventory_hostname]['ansible_nodename']": "fw.ruanbekker.com"
}

TASK [print info] ***************************
ok: [localhost] => {
    "msg": [
        "Country: South Africa",
        "City: Cape Town",
        ""
    ]
}

PLAY RECAP ***************************
localhost                  : ok=9    changed=1    unreachable=0    failed=0