4

I was trying to use vars_prompt in Ansible with default values taken from facts (or otherwise a previously defined variable). The playbook is intended be used as an ad-hoc one for initial provisioning.

My playbook:

---
- hosts: server01
  gather_facts: True
  vars_prompt:
    - name: new_hostname
      prompt: please enter the name for the target
      default: "{{ ansible_hostname }}"
      private: no
  tasks:
    - debug: msg="{{ new_hostname }}"

Current result:

please enter the name for the target [{{ ansible_hostname }}]:
ERROR! 'ansible_hostname' is undefined

Expected results (assuming ansible_hostname=server01:

please enter the name for the target [server01]:

Is it possible to achieve in Ansible?

techraf
  • 64,883
  • 27
  • 193
  • 198
  • I bet you are out of luck here. There are no host variables at this stage – prompts are for whole play and questions you before any task (including setup) is done for any host. May be `{{ new_hostname | default(ansible_hostname) }}` and passing `new_hostname` with `-e` is a solution. – Konstantin Suvorov Jul 28 '16 at 21:19
  • "*There are no host variables at this stage*" -- the question is: are there any variables interpreted at this stage (it seems any is just treated as a string). Other than that, I started to wonder if I could create a dynamic playbook from j2 template locally and include it.. – techraf Jul 28 '16 at 21:34
  • Quick look to the code hints that this part of playbook is not templated. – Konstantin Suvorov Jul 29 '16 at 08:01
  • Yes, that's correct. I meant I will try to create a playbook which will locally create another (ephemeral) playbook from j2 template (filling the values) and run this subplaybook from the main playbook. – techraf Jul 29 '16 at 08:04
  • Yes even I experienced the same issue. On one error scenario, I wanted to get a user input whether to continue the flow or quit. But the prompting happens before executing any task. – Mohan Kumar P Aug 10 '16 at 05:01

1 Answers1

4

This can be implemented using the pause module:

---
- hosts: server01
  gather_facts: True
  tasks:
    - pause:
        prompt: please enter the name for the target [{{ ansible_hostname }}]
      register: prompt

    - debug:
        msg: "{{ prompt.user_input if prompt.user_input else ansible_hostname }}"
techraf
  • 64,883
  • 27
  • 193
  • 198