ansible - Ansible 中基于 vars_prompt 有条件地导入剧本
问题描述
我正在使用以下 ansible 脚本根据用户输入导入剧本,
---
- hosts: localhost
vars_prompt:
- name: "cleanup"
prompt: "Do you want to run cleanup? Enter [yes/no]"
private: no
- name: run the cleanup yaml file
import_playbook: cleanup.yml
when: cleanup == "yes"
执行日志:
bash-$ ansible-playbook -i hosts cleanup.yml
Do you want to run cleanup? Enter [yes/no]: no
PLAY [localhost] *********************************************************************************************************************
TASK [Gathering Facts] ***************************************************************************************************************
ok: [127.0.0.1]
PLAY [master] ********************************************************************************************************************
TASK [Gathering Facts] ***************************************************************************************************************
fatal: [192.168.56.128]: FAILED! => {"msg": "The conditional check 'cleanup == \"yes\"' failed. The error was: error while evaluating conditional (cleanup == \"yes\"): 'cleanup' is undefined"}
to retry, use: --limit @/home/admin/playbook/cleanup.retry
PLAY RECAP ***************************************************************************************************************************
127.0.0.1 : ok=1 changed=0 unreachable=0 failed=0
192.168.56.128 : ok=0 changed=0 unreachable=0 failed=1
它在导入的剧本中而不是在邮件剧本中引发错误。请帮助我根据用户输入导入剧本。
解决方案
vars_prompt
变量仅在调用它们的剧本中定义。为了在其他游戏中使用它们,一种解决方法是使用set_fact
将变量绑定到主机,然后使用hostvars
从第二次游戏访问该值。
例如:
---
- hosts: localhost
vars_prompt:
- name: "cleanup"
prompt: "Do you want to run cleanup? Enter [yes/no]"
private: no
tasks:
- set_fact:
cleanup: "{{cleanup}}"
- debug:
msg: 'cleanup is available in the play using: {{cleanup}}'
- debug:
msg: 'cleanup is also available globally using: {{hostvars["localhost"]["cleanup"]}}'
- name: run the cleanup yaml file
import_playbook: cleanup.yml
when: hostvars["localhost"]["cleanup"] == True
推荐阅读
- angular - 如何根据数据的多次订阅返回我自己的 observable
- java - 如何解决无输出问题-使用while-?
- macros - 扩展 SPF 宏
- apache-spark - Spark 2.1.1:如何在 Spark 2.1.1 中已经训练的 LDA 模型上预测看不见的文档中的主题?
- html - 如何将导航栏的长度调整为手机的大小
- python - 记录对审计日志的更改
- swift - 来自故事板的初始化“此编码器要求从 initWithCoder 返回替换的对象”Swift
- canvas - 获取未捕获的错误:无效参数:null。在飞镖
- integer - 如何在普通 lisp 中检查整数是否为立方体?
- loops - 在循环的前一次迭代中多次借用