如何在Ansible vars_prompt中基于tool变量动态展示对应命令选项?
实现Ansible vars_prompt动态展示工具命令选项
完全可以实现你的需求,你的现有Playbook已经通过Jinja2模板尝试根据tool的值动态切换命令提示内容,下面可以优化得更严谨易用:
1. 为工具输入添加验证逻辑
给tool的vars_prompt增加验证规则,确保用户只能输入指定的工具名称,避免后续动态提示逻辑出错:
- name: tool prompt: | Input Tool name [ nodetool or systemctl ] or press ENTER for defaults >--> default: nodetool private: false unsafe: true validate: | {% if not (value in ['nodetool', 'systemctl']) %} {{ fail("Invalid tool! Only nodetool or systemctl are allowed.") }} {% endif %}
2. 优化命令的动态提示与默认值
把不同工具的可用命令整理成统一变量,方便维护,同时实现动态匹配默认值:
--- - name: Generate Cassandra Reports hosts: "{{ target }}" vars: # 统一管理各工具的命令选项与默认值,便于后续扩展 tool_commands: nodetool: options: ["status", "gossipinfo", "compactionstats"] default: "status" systemctl: options: ["status cassandraDB.service", "list-machines"] default: "status cassandraDB.service" vars_prompt: - name: target prompt: | List of available hosts / groups to choose : ------------------------------------------ {{ groups | dict2items | json_query('[?key!=`all` && key!=`ungrouped`]') | items2dict | to_nice_yaml }} Input host / group name or press ENTER for defaults >--> default: group1 private: no serial: 1 - name: tool prompt: | Input Tool name [ nodetool or systemctl ] or press ENTER for defaults >--> default: nodetool private: false unsafe: true validate: | {% if not (value in tool_commands.keys()) %} {{ fail("Invalid tool! Only " ~ tool_commands.keys() | join(', ') ~ " are allowed.") }} {% endif %} - name: command prompt: | Choose the command for {{ tool }}: Available options: {{ tool_commands[tool].options | join(', ') }} Input command or press ENTER for defaults >--> default: "{{ tool_commands[tool].default }}" private: false unsafe: true
优化点说明
- 新增
tool_commands变量统一管理工具命令,后续新增工具或命令只需修改该变量,无需改动prompt模板 - 为
tool添加动态验证逻辑,后续扩展工具时验证规则可自动适配 - 命令提示明确显示当前选中的工具及对应可用命令,用户体验更清晰
- 命令默认值随选中工具自动切换,比如选systemctl时默认值变为
status cassandraDB.service
内容的提问来源于stack exchange,提问作者RaviNookala
相关产品推荐
相关产品推荐

