Passing hostname to ansible playbook through extravars

Viewed 53

I have to pass the host on which the Ansible command will be executed through extra vars.

I don't know in advance to which hosts the tasks will be applied to, and, therefore, my inventory file is currently missing the hosts: variable.

If I understood from the article "How to pass extra variables to an Ansible playbook" correctly, overwriting hosts is only possible by having already composed groups of hosts.

From the post Ansible issuing warning about localhost I gathered that referencing hosts to be managed in an Ansible inventory is a must, however, I still have doubts about it since the usage of extra vars was not mentioned in the given question.

So my question is: What can i do in order to make this playbook work?

- hosts: "{{ host }}"

  tasks:

    - name: KLIST COMMAND
      command: klist
      register: klist_result

    - name: TEST COMMAND
      ansible.builtin.shell: echo hi > /tmp/test_result.txt
1 Answers

... referencing hosts to be managed in an Ansible inventory is a must

Yes, that's the case. Regarding your question

What can I do in order to make this playbook work? (annot. without a "valid" inventory file)

you could try with the following workaround.

---
- hosts: localhost
  become: false
  gather_facts: false

  tasks:

  - add_host:
      hostname: "{{ target_hosts }}"
      group: dynamic

- hosts: dynamic
  become: true
  gather_facts: true

  tasks:

  - name: Show hostname
    shell:
      cmd: "hostname && who am i"
    register: result

  - name: Show result
    debug:
      var: result

A call with

ansible-playbook hosts.yml --extra-vars="target_hosts=test.example.com"

resulting into execution on

TASK [add_host] ***********
changed: [localhost]

PLAY [dynamic] ************

TASK [Show hostname] ******
changed: [test.example.com]

In any case it is recommended to check how to build your inventory.

Further Documentation

Related