gpt4 book ai didi

ansible - 防止 Ansible 中变量转换为 bool

转载 作者:行者123 更新时间:2023-12-02 02:03:26 27 4
gpt4 key购买 nike

当用户向 vars_prompt 提供一些输入时,如何有条件地运行任务。问题是,我的变量被视为 bool,并且 yesno 永远不会匹配。

- 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

最佳答案

当您使用 set_fact 重新影响变量时,实际上就完成了 bool 值的转换,这是不需要的(除非您想在后续游戏中使用它)。以下内容实际上如您所期望的那样工作:

---
- hosts: localhost
gather_facts: false
vars_prompt:
- name: myvar
prompt: "yes or no?"
private: no
tasks:
- debug:
msg: yes was entered
when: "'yes' in myvar"

同时,这可能不是解决您的问题的最佳方法。我宁愿将答案转换为 bool 来直接对其进行测试(如果您需要在下一个游戏中进行提示,您最终可以再次使用 set_fact )。

---
- hosts: localhost
gather_facts: false
vars_prompt:
- name: myvar
prompt: "yes or no?"
private: no
tasks:
- debug:
msg: yes was entered
when: myvar | bool

关于ansible - 防止 Ansible 中变量转换为 bool,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57961473/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com