【发布时间】:2019-06-13 14:39:37
【问题描述】:
根据@Zeitounator 的建议,我已将问题重新编写得更具体,而不是使用我想要实现的通用示例。
我使用 ansible 通过在 hosts.ini 文件中添加一个新条目并运行 ansible-playbook -i inventory/dev/hosts.ini --limit SomeGroup playbooks/site.yml 来启动 VMware 中的虚拟机
vmware 角色(称为vmware)将
* 检查虚拟机是否已经存在。
* 如果是,那么显然它不会创建 VM。
* 如果不存在,则从模板创建虚拟机。
为了销毁一个虚拟机,我运行这个:ansible-playbook -i inventory/dev/hosts.ini --limit SomeGroup playbooks/site.yml -e 'vmware_destroy=true'
按预期工作。现在解决我的问题。
当这个变量被设置时(vmware_destroy=true),它会成功销毁虚拟机,但是 ansible 会尝试在刚刚被销毁的主机上继续执行 playbook 的其余部分。显然它失败了。由于失败,剧本确实停止了。但并不优雅。
这里是一个逻辑流程的例子:
$ cat playbooks/site.yml
---
- hosts: all
gather_facts: no
roles:
- { role: vmware, tags: vmware }
- hosts: all
gather_facts: yes
roles:
- { role: bootstrap, tags: bootstrap }
- { role: common, tags: common }
- hosts: AppServers
gather_facts: no
roles:
- { role: application }
# and so on.
$ cat playbooks/roles/vmware/main.yml
---
# Checks to see if the VM exists already.
# A variable `found_vm` is registered in this task.
- import_tasks: find.yml
# Only import this task when all of the `when` conditions are met.
- import_tasks: destroy.yml
when:
- vmware_destroy is defined
- vmware_destroy # Meaning 'True'
- found_vm
# If the above is true, it will not import this task.
- import_tasks: create.yml
when:
- found_vm.failed
- vmware_destroy is not defined
所以,关键是,当我指定 -e 'vmware_destroy=true' 时,ansible 将尝试运行 playbook 的其余部分并失败。
我不希望 ansible 失败。我希望它在完成基于命令行上提供的-e 'vmware_destroy=true 标志的vmware 角色后优雅地停止。
我知道我可以为此使用不同的剧本,例如:
ansible-playbook -i inventory/dev/hosts.ini --limit SomeGroup playbooks/VMWARE_DESTROY.yml。但我宁愿使用变量而不是单独的剧本。如果有强烈的论据以这种方式拆分剧本,请提供参考。
如果需要更多说明,请告诉我。
提前谢谢你。
【问题讨论】:
-
我以为我很清楚我想做什么。在剧本到达终点之前停止剧本。我会进一步澄清这一点。
-
meta: end_play结束一出戏,顾名思义,而不是剧本。由于第一次播放后没有停止的条件,只需从文件中删除您不想运行的其他播放(KISS 原则)......或者尝试更好地解释您想要实现的目标的根源,因为您可能不会走上正轨。
标签: ansible