ansible 2.1.2.0
我有一个情况,我试图与你们一起检查是否有可能使用Ansible vars_prompt
功能和 when
条件的解决方案 .
Ansible有这个名为:vars_prompt的功能,我想用when条件( when: ...
,我们通常在任务或剧本级动作的任务中使用)来支持这个功能
PS: 我的问题是 different than this post :Ansible to Conditionally Prompt for a Variable?,即我的 vars:
变量不依赖于任何机器的OS ENV变量,在我的例子中,我只有一个简单的硬编码值为 vars:
变量 . 我'm also running the when condition at the main playbook level (and not at the task'的水平) .
我正在尝试做的是提示用户输入变量值,只有在命令行,用户已使用 --extra-vars "install_tool=true"
调用 ansible-playbook install_tool.yml ... ...
在 workspace/ansible /install_tool.yml我有:
- hosts: all
become: true
gather_facts: false
vars:
instance: test
#install_tool: false
company_api_url: DUMMY_INVALID_URL
vars_prompt:
- name: "company_api_url"
prompt: "Enter Company API URL: "
default: "https://{{ instance }}.company.com"
private: no
when: install_tool == "true" and company_api_url == "DUMMY_INVALID_URL"
# or
#when: ( "{{ install_tool }}" == "true" and "{{ company_api_url }}" == "DUMMY_INVALID_URL" )
pre_tasks:
- debug: msg="install_tool = {{ install_tool }} and instance = {{ instance }}"
when: install_tool == "true"
My question:
如何使上述条件提示工作(对于提示变量使用有效的替换 default
值) and 也跳过提示用户完全取决于 install_tool
变量的值?
My understanding: 在顶级playbook文件(install_tool.yml)中,我正在定义一个变量 instance
,其值为 test
. 为什么vars_prompt部分的 default
值没有选择 test
并在playbook级别定义时替换它的值( - 或者如果用户在 ex: --extra-vars "instance=qa"
的命令行传递 instance
变量怎么办?在这种情况下,我希望默认值为 [https://qa.company.com]
,我该怎么办?)我在运行任何语法时都没有看到任何错误 .
我得到以下输出(但我期待一个替代的URL值,如: [https://test.company.com]
) and 即使在命令行设置或传递 install_tool
为 false
时,它仍然会提示:
运行:
$ ansible-playbook -i "localhost," --connection=local install_tool.yml --extra-vars "install_tool=false instance=qa"
要么
$ ansible-playbook -i inventory -l localhost install_tool.yml --extra-vars "install_tool=false"
...
.....some lines here
...
PLAYBOOK: install_tool.yml *******************************************
1 plays in install_tool.yml
Enter Company API URL: [https://{{ instance }}.company.com]:
在 vars_prompt
部分中使用 when: ( "{{ install_tool }}" == "true" and ...)
条件,在 - name: company_api_url
变量下,它没有't error out for any syntax issues or etc (that means, Ansible doesn'认为它是错误的,然后 WHY ,Ansible仍然提示我输入上面的 vars_prompts
变量,即使我正在传递 --extra-vars "install_tool=false"
--OR-- 如果我 uncomment 行: install_tool: false
在 vars:
部分?
PS: when: ...
条件成功地为 pre_tasks
部分工作,即当install_tool为true时,它显示这两个变量的值,当install_tool设置为false时,它不会运行 - debug
步骤并跳过它(这是预期的) .
谢谢 .
1 回答
您可以检查提示的变量here的所有支持的属性 .
提示的vars不支持
when
语句 . 从来没有 .提示变量的模板化默认值也是not supported .
防止变量提示的唯一方法是通过extra_vars传递有问题的变量 . 在您的示例中,如果您传递
-e company_api_url=my_custom_url
,Ansible将跳过提示 .