How to prompt user for a target host in Ansible?

techraf picture techraf · Oct 14, 2015 · Viewed 20k times · Source

I want to write a bootstrapper playbook for new machines in Ansible which will reconfigure the network settings. At the time of the first execution target machines will have DHCP-assigned address.

The user who is supposed to execute the playbook knows the assigned IP address of a new machine. I would like to prompt the user for is value.

vars_prompt module allows getting input from the user, however it is defined under hosts section effectively preventing host address as the required value.

Is it possible without using a wrapper script modifying inventory file?

Answer

nitzmahone picture nitzmahone · Apr 13, 2016

The right way to do this is to create a dynamic host with add_host and place it in a new group, then start a new play that targets that group. That way, if you have other connection vars that need to be set ahead of time (credentials/keys/etc) you could set them on an empty group in inventory, then add the host to it dynamically. For example:

- hosts: localhost
  gather_facts: no
  vars_prompt:
  - name: target_host
    prompt: please enter the target host IP
    private: no
  tasks:
    - add_host:
        name: "{{ target_host }}"
        groups: dynamically_created_hosts

- hosts: dynamically_created_hosts
  tasks:
  - debug: msg="do things on target host here"