Ansible playbook, pass the inventory as a variable

ansible

I would like to override the target_host variable from tower into the playbook. It's easy to override any other playbook variable, but I can't seem to get hosts value to work; always complains that no host was specified.

---
- hosts: "{{ target_host }}"
  gather_facts: no
  vars:
    target_host: "10.80.100.163,"
  remote_user: root

  tasks:
  - name: Add users | create users, shell, home dirs
    user:
      name: bubba
      shell: /bin/bash
      createhome: yes
      password: $6$pGO4DKLQ$Eu97vmle/Zvb53gVCXGecfZzvYVd4twj8/EOMwmbYgCUkRAxsWQVXtFrxdZGal6hSLnY..5b/4x1MweH5ierz.
      comment: "Created with Ansible"

Hoping not to have to (learn how to) create a dynamic inventory for one IP, is there a way to do this?

thanks!

Best Answer

You can use ansible module: add_host https://docs.ansible.com/ansible/latest/modules/add_host_module.html

---
- hosts: "localhost"
  gather_facts: no
  tasks:
  - name: Add host
    add_host:
      hostname: "{{ your_new_hostname }}"
      groups: "group_for_new_hostname"
      ansible_user: "{{ ssh_user }}"
      ansible_ssh_pass: "{{ ssh_pass }}"

- hosts: "group_for_new_hostname"
  tasks:
  - name: Add users | create users, shell, home dirs
    user:
      name: bubba
      shell: /bin/bash
      createhome: yes
      password: $6$pGO4DKLQ$Eu97vmle/Zvb53gVCXGecfZzvYVd4twj8/EOMwmbYgCUkRAxsWQVXtFrxdZGal6hSLnY..5b/4x1MweH5ierz.
      comment: "Created with Ansible"