Ansible - Access inventory alias

2019-02-04 02:08发布

问题:

Having an inventory file like:

[my_hosts]
my_host ansible_ssh_host=123.123.123.123
my_host2 ansible_ssh_host=234.234.234.234

I want to gather some debug information in my templates.

  • How do I acces the alias variable in a playbook/template? I.e.:

    debug: msg=Myhost is {{ ansible_host_alias }} 
    # Myhost is my_host
    # Myhost is myhost2
    

I tried to gather facts using ansible -m setup my_host . The variables ansible_hostname , HOSTNAME and HOST contain the machine's hostname, i.e. echo $HOSTNAME which differs from my ansible alias.

回答1:

The variable I was searching for is a built in feature: inventory_hostname

Ansible documentation about inventory_hostname and inventory_hostname_short is found from chapter Magic Variables, and How To Access Information About Other Hosts.

Original question: https://groups.google.com/forum/#!topic/ansible-project/Oa5YXjHecIw



回答2:

You can just simply use {{ ansible_ssh_host }} For example:

Inventory:

[my_hosts]
my_host ansible_ssh_host=127.0.0.1 my_host_alias=my_host

Playbook:

---
- name: My Good playbook
  user: ubuntu
  hosts: all

  tasks:
    - name: My message
      debug: msg="Myhost is {{ ansible_ssh_host }}"

    - name: My message bogus
      debug: msg="My host alias is {{ my_host_alias }}"

Execution:

$ ansible-playbook -i inventory play.yml

PLAY [My Good playbook] *******************************************************

GATHERING FACTS ***************************************************************
ok: [my_host]

TASK: [My message] ************************************************************
ok: [my_host] => {
    "msg": "Myhost is 127.0.0.1"
}

TASK: [My message bogus] ******************************************************
ok: [my_host] => {
    "msg": "My host alias is my_host"
}

PLAY RECAP ********************************************************************
my_host                    : ok=3    changed=0    unreachable=0    failed=0


标签: ansible