User inputs with Ansible Prompt with examples

Working with Ansible Prompts.

Sometimes you need input from the user to decide how the playbook should run. Maybe you need to name a directory. Maybe there are plays written for installing multiple versions. And you can install one version based on the user input. Or there may be some data which is sensitive you do not want to store in any variable.

The user can provide the values in many ways. You have an Ansible prompt module which will prompt the user for the value when the play is run. You can give values as extra arguments to the command line arguments. etc.

In this session, we will focus on Ansible prompts.

A basic example of Ansible Prompts.

To ask for a user input, we will use the vars_prompt section. Something like below,

 vars_prompt:
    - name: "Version"
      prompt: "Which version Do you want to install?"

What this does is, during the playbook run, the question ‘Which version Do you want to install?’ will be [rompted. The answer to this will be saved to Version variable. This variable can be used throughout the play (not the entire playbook) to alter the flow of execution. 

Note: If there is already a variable named ‘Version,’ it can be overwritten based on how that variable was given. For more details on the precedence of Ansible, variables check this.

Note: The prompt will be shown when the play where the vars_prompt is given starts. you can’t set it as to prompt during a task.

In the following example, I am giving the value “1.0” in the prompt. Since the input provided is hidden by default, you cannot see the value I am typing. You can see the output printed in the debug statement.

- hosts: all
  gather_facts: False
  vars_prompt:
    - name: "Version"
      prompt: "Which version Do you want to install?"

  tasks:
    - name: Ansible prompt example.
      debug:
        msg: "{{ Version }}"

Basic Example of an Ansible prompt

 

You can also give a default value to the variable. So if no value is provided during the prompt, then the default value will be assigned to the variable. The following will assign the value “3.0” in case no value is given.

vars_prompt:
    - name: "Version"
      prompt: "Which version Do you want to install?"
      default: "3.0"

Private option in Ansible prompt for displaying the user input

Sometimes you may need the user to see what he is giving as the input. In that case, you set the private option to ‘no’.

Ansible Prompt example with private set to false.