在Ansible中导入具有布尔条件的任务或剧本



实际上我需要这样的东西:

- hosts: localhost

tasks:
- name: Perforce template
import_tasks: ./../vsphere-client/perforce/template_to_vm.yml
when: new_server_type == "perforce"

- name: Gitlab Pgbouncer template
import_tasks: ./../vsphere-client/gitlab-pgbouncer/template_to_vm.yml
when: new_server_type == "gitlab-pgbouncer"

- name: Gitlab Postgres template
import_tasks: ./../vsphere-client/gitlab-postgres/template_to_vm.yml
when: new_server_type == "gitlab-postgres"

- name: Build API template
import_tasks: ./../vsphere-client/build-api/template_to_vm.yml
when: new_server_type == "build-api"

但它给出了一个错误,比如:

ERROR! unexpected parameter type in action: <type 'bool'>

我知道这是不支持的,但有什么办法可以做到这一点吗?

您是否尝试过使用include_tasks,例如以下

- include_tasks: setup-RedHat.yml
when: ansible_os_family == 'RedHat'

所以对你来说,如下

- hosts: localhost
tasks:
- name: Perforce template
include_tasks: ./../vsphere-client/perforce/template_to_vm.yml
when: new_server_type == "perforce"

一定有其他内容没有显示,因为您的代码看起来不错,应该可以工作。我怀疑问题出在您正在导入的文件中。

同时,如果切换到include_tasks不是问题,那么只需一个任务就可以大大缩短上述时间:

---
- hosts: localhost
tasks:
- name: "{{ new_server_type }} template"
include_tasks: "./../vsphere-client/{{ new_server_type }}/template_to_vm.yml"

如果您确实需要检查以确保new_server_type具有正确的值,那么这仍然是可能的。

---
- hosts: localhost
vars:
allowed_types:
- perforce
- gitlab-pgbouncer
- gitlab-postgres
- build-api
tasks:
- name: "{{ new_server_type }} template"
include_tasks: "./../vsphere-client/{{ new_server_type }}/template_to_vm.yml"
when: new_server_type in allowed_types

正如前面的两个答案所暗示的那样,捕获是import_tasks而不是include_tasks。import_tasks的文档显示:

大多数关键字,包括循环和条件,只应用于导入的任务,而不应用于此语句本身。如果您需要应用其中任何一个,请改用ansible.buildin.include_tasks。

最新更新