Search code examples
ansible

How do I specify host as a variable in ansible?


There are examples on the internet but none of them seem to work for me:

test.yaml

---

- hosts: "{{ non_default_host }}"
  tasks:
    - debug:
        msg: 'This is the host specified"

then I run this with

ansible-playbook -i hosts test.yaml -e "non_default_host=<somehost>"

All I see is bunch of warnings:

[WARNING]: No inventory was parsed, only implicit localhost is available
[WARNING]: provided host list is empty, only localhost is available
[WARNING]: Could not match supplied host pattern, ignoring somehost

PLAY [somehost]
skipping: no hosts matched

But if I change the hosts to all

test.yaml

---

- hosts: all
  tasks:
    - debug:
        msg: 'This is the host specified"

and then below command this works fine

   ansible-playbook -i 'somehost,'  test.yaml

Solution

  • For an inventory file example with content of

    [example:children]
    default
    non_default
    
    [default]
    node[01:03].example.com
    
    [non_default]
    node[01:03].example.net
    

    checked with

    ansible-inventory --inventory example --graph
    @all:
      |--@ungrouped:
      |--@example:
      |  |--@default:
      |  |  |--node01.example.com
      |  |  |--node02.example.com
      |  |  |--node03.example.com
      |  |--@non_default:
      |  |  |--node01.example.net
      |  |  |--node02.example.net
      |  |  |--node03.example.net
    

    a minimal example playbook

    ---
    - hosts: "{{ host }}"
      become: false
      gather_facts: false
      connection: local
    
      tasks:
    
      - debug:
          msg: "This is the 'hosts: {{ host }}' specified"
    

    called via

     ansible-playbook --inventory example test.yml --extra-vars="host=node03.example.com"
    

    will result into an output of

    PLAY [node03.example.com] **********************************
    
    TASK [debug] ***********************************************
    ok: [node03.example.com] =>
      msg: 'This is the ''hosts: node03.example.com'' specified'
    

    Documentation