thelinuxvault blog

Introduction to Ansible Prompts and Runtime Variables

Ansible, the open-source automation tool, has revolutionized how system administrators, DevOps engineers, and developers manage infrastructure, deploy applications, and automate repetitive tasks. A key strength of Ansible is its flexibility, and much of that flexibility stems from its ability to handle dynamic data. Two critical features enabling this are Ansible prompts (user-input variables during execution) and runtime variables (variables passed externally at execution time).

Hardcoding values in playbooks (e.g., usernames, passwords, or environment-specific configurations) is inefficient, insecure, and limits reusability. Prompts and runtime variables solve this by allowing you to inject dynamic values into playbooks when they run, making your automation adaptable to different scenarios, environments, and user inputs.

In this blog, we’ll explore what prompts and runtime variables are, how to use them, advanced use cases, and best practices to master these powerful features.

2026-02

Table of Contents#

  1. What Are Ansible Prompts and Runtime Variables?
  2. Why Use Prompts and Runtime Variables?
  3. Working with Ansible Prompts (vars_prompt)
  4. Working with Runtime Variables (--extra-vars)
  5. Advanced Use Cases
  6. Best Practices
  7. Conclusion
  8. References

What Are Ansible Prompts and Runtime Variables?#

Ansible Prompts#

Ansible prompts (defined via vars_prompt in playbooks) are interactive user inputs collected during playbook execution. They pause the playbook and ask the user to enter a value (e.g., a username, password, or environment name), which is then stored in a variable for use in tasks.

Runtime Variables#

Runtime variables (passed via the --extra-vars or -e flag) are external variables injected into the playbook at execution time, without requiring user interaction. They are ideal for automation pipelines, CI/CD workflows, or scenarios where variables are determined dynamically (e.g., from a build server or inventory).

Why Use Prompts and Runtime Variables?#

  • Flexibility: Adapt playbooks to different environments (dev, staging, prod) by passing environment-specific variables at runtime.
  • Security: Avoid hardcoding sensitive data (passwords, API keys) in playbooks. Use prompts to input secrets interactively or runtime variables with Ansible Vault for encryption.
  • Reusability: Write a single playbook that works for multiple use cases by dynamically injecting variables (e.g., creating users with different names).
  • Automation-Friendly: Runtime variables integrate seamlessly with CI/CD tools (Jenkins, GitHub Actions) and Ansible Tower/AWX, enabling fully automated workflows.

Working with Ansible Prompts (vars_prompt)#

The vars_prompt section in a playbook defines variables to be collected from the user. It supports parameters like prompt (message to display), private (hide input for secrets), default (pre-filled value), and confirm (validate sensitive inputs).

Basic Syntax and Parameters#

Here’s the general structure of vars_prompt:

- name: My Playbook  
  hosts: all  
  vars_prompt:  
    - name: "variable_name"       # Name of the variable to store input  
      prompt: "Enter a value"     # Message displayed to the user  
      private: yes/no             # Whether to hide input (default: no)  
      default: "optional_value"   # Pre-filled value (user can press Enter to accept)  
      confirm: yes/no             # Re-prompt to confirm input (e.g., passwords)  
  tasks:  
    - name: Use the prompted variable  
      debug:  
        msg: "You entered: {{ variable_name }}"  

Practical Examples of vars_prompt#

Example 1: Simple Prompt for a Username#

This playbook prompts the user for a username and prints it:

# prompt_username.yml  
- name: Prompt for username  
  hosts: localhost  
  vars_prompt:  
    - name: "username"  
      prompt: "Enter the username to create"  
      private: no  # Input is visible  
  tasks:  
    - name: Display the username  
      debug:  
        msg: "Creating user: {{ username }}"  

Execution Output:

$ ansible-playbook prompt_username.yml  
Enter the username to create: alice  # User input  
PLAY [Prompt for username] **************************************************  
TASK [Gathering Facts] ******************************************************  
ok: [localhost]  
TASK [Display the username] *************************************************  
ok: [localhost] => {  
    "msg": "Creating user: alice"  
}  
PLAY RECAP ******************************************************************  
localhost                  : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

Example 2: Secure Password Prompt with Confirmation#

For sensitive inputs like passwords, use private: yes and confirm: yes to hide input and validate:

# create_user_with_password.yml  
- name: Create a user with a prompted password  
  hosts: webservers  
  vars_prompt:  
    - name: "user_password"  
      prompt: "Enter the user's password"  
      private: yes  # Input is hidden (no echo)  
      confirm: yes  # Re-prompt to confirm  
  tasks:  
    - name: Create user "jane" with the prompted password  
      user:  
        name: jane  
        password: "{{ user_password | password_hash('sha512') }}"  # Hash the password  
        state: present  

Execution Output:

$ ansible-playbook create_user_with_password.yml  
Enter the user's password:  # User types "SecurePass123" (not visible)  
confirm Enter the user's password:  # User retypes "SecurePass123"  
PLAY [Create a user with a prompted password] *******************************  
TASK [Gathering Facts] ******************************************************  
ok: [webserver1]  
TASK [Create user "jane" with the prompted password] ************************  
changed: [webserver1]  
PLAY RECAP ******************************************************************  
webserver1                 : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0  

Working with Runtime Variables (--extra-vars)#

Runtime variables are passed to playbooks using the --extra-vars (or -e) flag. They override most other variable sources (inventory, vars files) and are ideal for non-interactive scenarios.

Passing Runtime Variables: Methods and Examples#

Ansible supports multiple ways to pass --extra-vars:

1. Key-Value Pairs (Simplest)#

Pass variables directly as key=value pairs:

ansible-playbook -e "service_name=httpd state=restarted" manage_service.yml  

Playbook Example (manage_service.yml):

- name: Manage a service with runtime variables  
  hosts: webservers  
  tasks:  
    - name: Start/stop/restart the service  
      service:  
        name: "{{ service_name }}"  
        state: "{{ state }}"  

2. JSON String#

For complex variables (e.g., lists, dictionaries), use a JSON string:

ansible-playbook -e '{"users": ["alice", "bob"], "groups": ["dev", "ops"]}' create_users.yml  

Playbook Example (create_users.yml):

- name: Create multiple users from a runtime list  
  hosts: all  
  tasks:  
    - name: Create users  
      user:  
        name: "{{ item }}"  
        state: present  
      loop: "{{ users }}"  # Iterate over the "users" list from --extra-vars  

3. From a File (@file)#

Store variables in a JSON/YAML file and pass it with @:

File: extra_vars.yml

env: production  
app_port: 8080  
features:  
  - logging  
  - monitoring  

Command:

ansible-playbook -e "@extra_vars.yml" deploy_app.yml  

4. From Inventory or Vault#

You can also pass variables stored in inventory files or encrypted with Ansible Vault. For example, to use a vault-encrypted variable file:

ansible-playbook -e "@secrets.vault.yml" --vault-password-file ~/.vault_pass deploy.yml  

Variable Precedence#

Ansible variables have a strict precedence order. --extra-vars override all other variable sources (e.g., inventory, vars in playbooks, group_vars). This ensures runtime variables always take priority, making them reliable for dynamic overrides.

Advanced Use Cases#

Combining Prompts and Runtime Variables#

Use prompts for interactive, human-driven tasks (e.g., manual approval) and runtime variables for automated pipelines. For example:

# deploy_with_approval.yml  
- name: Deploy app with manual approval  
  hosts: appservers  
  vars_prompt:  
    - name: "approve_deployment"  
      prompt: "Type 'YES' to approve deployment"  
      private: no  
      default: "NO"  
  tasks:  
    - name: Deploy only if approved  
      when: approve_deployment == "YES"  
      git:  
        repo: "{{ repo_url }}"  # Passed via --extra-vars  
        dest: /opt/app  

Execution (with runtime repo_url):

ansible-playbook -e "repo_url=https://github.com/myapp.git" deploy_with_approval.yml  

Conditional Prompts#

Use the when clause in vars_prompt to conditionally prompt for variables. For example, prompt for a database password only if create_db is true:

vars_prompt:  
  - name: "db_password"  
    prompt: "Enter database password"  
    private: yes  
    when: create_db | bool  # Only prompt if create_db is true  

Pass create_db via --extra-vars:

ansible-playbook -e "create_db=true" setup_db.yml  

Runtime Variables in Ansible Tower/AWX#

Ansible Tower (or AWX, the open-source version) uses survey variables to collect user input, which are passed to playbooks as --extra-vars. This replaces vars_prompt in Tower workflows, enabling UI-driven input for job templates.

Best Practices#

  1. Avoid Overusing Prompts: Prompts require human interaction, which breaks fully automated workflows (e.g., CI/CD pipelines). Use --extra-vars for non-interactive scenarios.
  2. Secure Sensitive Data: Even with prompts, avoid logging sensitive variables. Use no_log: yes in tasks handling secrets, or encrypt variables with Ansible Vault.
  3. Document Variables: Clearly document expected variables (name, type, purpose) in playbooks or a README to guide users/automation tools.
  4. Test with --check: Validate variable behavior with ansible-playbook --check to avoid runtime errors.
  5. Prefer Files for Complex Variables: For lists/dictionaries, use @file instead of CLI key-value pairs for readability.

Conclusion#

Ansible prompts and runtime variables are indispensable for building flexible, secure, and reusable automation. Prompts (vars_prompt) excel at interactive tasks requiring human input, while runtime variables (--extra-vars) power automated, pipeline-friendly workflows. By mastering these features, you’ll unlock Ansible’s full potential to adapt to diverse environments and use cases.

References#