A key part of Ansible’s flexibility is its use of variables. Ansible allows us to define the variables in different places such as playbooks, roles, inventory, etc. This ensures that we have lots of flexibility and ease of maintenance for dynamic environments.
However, we might sometimes want to prompt the user for specific input when executing an Ansible playbook.
In this tutorial, we will explore the vars_prompt feature of Ansible and learn how to use it to prompt the user for input and store it into a variable. This will help us to interactively gather the user input during playbook execution, making the automation scripts more dynamic and adaptable.
Ansible Vars_Prompt
In Ansible, the vars_prompt is a section that we define in an Ansible playbook to prompt the user for required input. We can then store this input into a variable that we can reference later.
The following shows the basic syntax of the vars_prompt section in Ansible:
- hosts: localhost
vars_prompt:
- name: target_hostname
prompt: "What is the target hostname?"
tasks:
- name: Print hostname
debug:
msg: "Target hostname is: {{ target_hostname }}"
If we run the provided playbook, it prompts the username with the defined message. Once provided, it then prints out the Target hostname which is [provided hostname].
Output:
"msg": "Target hostname is: linuxhint.com"
}
Setting the Default Value
We can also define a default value that will be used if the user does not provide the value on the prompt.
An example playbook is as follows:
- hosts: localhost
vars_prompt:
- name: target_hostname
prompt: "What is the target hostname?"
default: "localhost"
tasks:
- name: Print hostname
debug:
msg: "Target hostname is: {{ target_hostname }}"
---
Prompting Sensitive Data
We can set the private option to yes for sensitive information to hide the input that is similar to UNIX’s passwd command.
- hosts: localhost
vars_prompt:
- name: user_password
prompt: "Enter password"
private: yes
tasks:
- name: Print password
debug:
msg: "Your password is {{ user_password }}"
Output:
Enter password: *****<em>***</em>
Upon running, the resulting value is as follows:
TASK [Print password] **************************
ok: [localhost] => {
"msg": "Your password is password"
}
Prompt for Confirmation
We can also prompt the user to confirm a given input using the confirm parameter as follows:
- hosts: localhost
vars_prompt:
- name: user_email
prompt: "Email: "
confirm: yes
tasks:
- name: Print email
debug:
msg: "Your email is {{ user_email }}"
Output:
Email: : <>
confirm Email: <>
Conclusion
We learned how to use the vars_prompt block in Ansible to introduce the interactivity in Ansible playbooks by providing a way for the playbook to fetch an input from the user.