Using a variable as a default value in vars_prompt

2020-02-02 01:22发布

问题:

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?

回答1:

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 }}"