用户向vars_prompt
提供某些输入时如何有条件地运行任务。问题是,我的变量被视为bool,并且yes
和no
从未匹配。
- hosts: localhost
gather_facts: no
vars_prompt:
- name: "myvar"
prompt: "Do you want to proceed(yes/no)?"
private: no
tasks:
- name: "Set variable"
set_fact:
myvar: "{{ myvar }}"
- name: "Conditional task"
shell: echo "conditional action"
when: "'yes' in myvar"
当我运行上述代码时,我收到以下错误消息:
fatal: [localhost]: FAILED! => {}
味精:
The conditional check ''yes' in myvar' failed. The error was: Unexpected templating type error occurred on ({% if 'yes' in myvar %} True {% else %} False {% endif %}): argument of type 'bool' is not iterable
The error appears to have been in '/home/monk/samples/user.yml': line 14, column 7, but may
be elsewhere in the file depending on the exact syntax problem.
The offending line appears to be:
- name: "Conditional task"
^ here
最佳答案
问:请防止在ansible中将变量转换为bool。
答:请参见How Exactly Does Ansible Parse Boolean Variables?。可以简单地计算条件中的变量myvar
- name: "Set variable"
set_fact:
myvar: "{{ myvar }}"
- name: "Conditional task"
shell: echo "conditional action"
when: myvar
条件
when: "'yes' in myvar"
不起作用,因为myvar
不是列表。这是导致错误的原因:'bool'类型的参数不可迭代
笔记
从Prompts引用:
对于已通过命令行--extra-vars选项定义的任何变量,将跳过对各个vars_prompt变量的提示...
从Passing Variables On The Command Line引用:
使用key = value语法传递的值将解释为字符串。如果您需要传递不应该是字符串的任何内容(布尔值,整数,浮点数,列表等),请使用JSON格式。
因此,为了安全起见,请使用显式
bool
强制转换when: myvar|bool
关于ansible - 防止在Ansible中将变量转换为bool,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57961473/