Skip to content

vars_prompt: add choices support for input validation - #85882

Closed
bhowmickkrishnendu wants to merge 5 commits into
ansible:develfrom
bhowmickkrishnendu:feature-vars-prompt-choices-only
Closed

vars_prompt: add choices support for input validation#85882
bhowmickkrishnendu wants to merge 5 commits into
ansible:develfrom
bhowmickkrishnendu:feature-vars-prompt-choices-only

Conversation

@bhowmickkrishnendu

Copy link
Copy Markdown

Summary

This PR adds support for a new choices key in vars_prompt, allowing list-based input validation directly in playbooks. Users can now restrict input to predefined options, improving playbook usability and preventing invalid data entry.

Feature

Example usage:

hosts: localhost
gather_facts: no
vars_prompt:
  - name: color
    prompt: "Choose a color"
    choices:
      - red
      - green
      - blue
    private: no

tasks:
  - debug:
      msg: "You selected: {{ color }}"

Behavior:

  • If the user enters an invalid choice during interactive prompts, they are shown the valid options and prompted again.
  • Values provided via --extra-vars are also validated against the choices list.
  • If an invalid value is passed via --extra-vars, a ValueError is raised with a clear error message.

Example with --extra-vars:

Valid usage:

ansible-playbook playbook.yml --extra-vars "color=red"

Invalid usage (raises error):

ansible-playbook playbook.yml --extra-vars "color=yellow"

Error:

Invalid value for 'color': 'yellow' not in allowed choices ['red', 'green', 'blue']

Changes Made

  • lib/ansible/playbook/play.py: Added 'choices' to the list of allowed keys in vars_prompt validation.

  • lib/ansible/executor/playbook_executor.py:

    • Added logic to validate interactive user input against choices list.
    • Added validation for values provided via --extra-vars.
    • Implemented re-prompting logic when invalid choices are entered interactively.
    • Added clear error messages showing available options.
  • changelogs/fragments/vars_prompt_choices_support.yml: Added changelog fragment documenting the new feature.

Notes

  • Backward compatible: No changes to existing behavior unless choices is explicitly used.
  • Enhanced UX: Clear error messages guide users to valid options.
  • Comprehensive validation: Both interactive input and --extra-vars are validated.
  • Useful for: Enforcing specific input options (e.g., environments, regions, deployment types).

ISSUE TYPE

  • Feature Pull Request

Testing

Test interactive prompts with valid/invalid choices:

ansible-playbook test_choices.yml

Test --extra-vars validation with valid choice:

ansible-playbook test_choices.yml --extra-vars "color=red"

Test --extra-vars validation with invalid choice (should raise error):

ansible-playbook test_choices.yml --extra-vars "color=yellow"

@ansibot ansibot added the needs_triage Needs a first human triage before being processed. label Sep 20, 2025
Add support for 'choices' key in vars_prompt to restrict user input
to predefined options. When choices are specified:
- Interactive prompts validate user input against allowed choices
- Values from --extra-vars are also validated
- Invalid values raise ValueError with clear error message

This enhancement improves playbook usability by preventing invalid
input and providing clear feedback to users.
@bhowmickkrishnendu
bhowmickkrishnendu force-pushed the feature-vars-prompt-choices-only branch from 2f44e52 to 8d772ea Compare September 20, 2025 07:37
@webknjaz

Copy link
Copy Markdown
Member

/azp run

@azure-pipelines

Copy link
Copy Markdown
Azure Pipelines successfully started running 1 pipeline(s).

@webknjaz

Copy link
Copy Markdown
Member

FYI this sort of change would normally require tests.

@bhowmickkrishnendu
bhowmickkrishnendu force-pushed the feature-vars-prompt-choices-only branch from e7ff121 to 899d414 Compare September 23, 2025 07:54
@ansibot ansibot added the needs_revision This PR fails CI tests or a maintainer has requested a review/revision of the PR. label Sep 23, 2025
@bhowmickkrishnendu

Copy link
Copy Markdown
Author

Thanks for the review! I’ve added integration tests under test/integration/targets/vars_prompt_choices/.

The tests cover:

  • Valid choices via --extra-vars
  • Invalid choices via --extra-vars (expected failure)

Please let me know if you’d like additional scenarios included.

@ansibot ansibot removed the needs_revision This PR fails CI tests or a maintainer has requested a review/revision of the PR. label Sep 23, 2025
@mkrizek mkrizek added needs_verified This issue needs to be verified/reproduced by maintainer and removed needs_triage Needs a first human triage before being processed. labels Sep 30, 2025
@ansibot ansibot added the stale_ci This PR has been tested by CI more than one week ago. Close and re-open this PR to get it retested. label Oct 3, 2025
@bhowmickkrishnendu

Copy link
Copy Markdown
Author

This is long standing PR. Please verify!

@s-hertel s-hertel left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Have you considered using a play argument spec instead? I'm not sure I see the benefit to adding 'choices' to 'vars_prompt' since the argument spec handles that and more.

For example:

# playbook.yml
- hosts: localhost
  gather_facts: no
  vars_prompt:
    - name: from_vars_prompt
      prompt: enter choice1 or choice2
  validate_argspec: vars_prompt_options
# playbook.meta.yml  - name must match playbook
argument_specs:
  vars_prompt_options:
    options:
      from_vars_prompt:
        type: str
        choices:
          - choice1
          - choice2
        required: True

Comment on lines +142 to +143
# 🔹 New: support for choices
choices = var.get("choices")

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What if choices is an unsupported format or contains invalid choices?

Comment on lines +145 to +150
if self._tqm:
self._tqm.send_callback(
'v2_playbook_on_vars_prompt',
vname, private, prompt, encrypt, confirm,
salt_size, salt, default, unsafe
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems like a change in behavior. Previously this occurred only iv the variable name is not in extra vars.

Comment on lines +152 to +162
# Skip prompt if provided via --extra-vars
if vname in self._variable_manager.extra_vars:
play.vars[vname] = self._variable_manager.extra_vars[vname]

# If choices are defined, validate extra-vars value too
if choices and play.vars[vname] not in choices:
raise ValueError(
f"Invalid value for '{vname}': "
f"'{play.vars[vname]}' not in allowed choices {choices}"
)
continue

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think extra vars should be validated using choices.


# 🔹 Check choices for interactive input
if choices:
while answer not in choices:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If there's no valid choice this will loop forever. I think some validation of the contents of choices should be added first.

@bcoca

bcoca commented Oct 22, 2025

Copy link
Copy Markdown
Member

@bhowmickkrishnendu stop spaming comments in other tickets, this is not a 'long standing PR' by any account, I could link hundreds that have been in the queue much longer.

@ansibot

ansibot commented Jun 17, 2026

Copy link
Copy Markdown
Contributor

Hi @bhowmickkrishnendu!

Thank you very much for your submission to Ansible. It means a lot to us that you've taken the time to contribute.

Unfortunately, we currently ask that first-time contributors only have one open pull request. This will help you to learn what an acceptable pull request is like and also help us keep up with the review queue.

Since you already have an active pull request open at #85368, we are automatically closing this one for now. Once your other PR is merged or closed, please feel free to reopen this one or submit it again.

Thank you for understanding!

click here for bot help

@ansibot ansibot closed this Jun 17, 2026
@ansibot ansibot removed the needs_verified This issue needs to be verified/reproduced by maintainer label Jun 17, 2026
@ansible ansible locked as resolved and limited conversation to collaborators Jul 2, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

bot_closed stale_ci This PR has been tested by CI more than one week ago. Close and re-open this PR to get it retested.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants