"当"动态包含文件时条件不起作用

时间:2014-04-03 08:19:40

标签: ansible ansible-playbook

我试图根据include中传递的参数动态ansible-playbook文件。要验证参数我在when条件下检查它,但它假设不适合我。 首先检查包含文件。

playbook.yml: -

---
- hosts: local
  user: roop
  gather_facts: no

  vars: {action: "",validAction: ["action1","action2","action3","action4"]}

  tasks:

    - name: validate action
      fail: msg="please make sure you pass valid action"
      when: action == "" or action not in validAction

    - include: "action/{{ action }}.yml"
      when: action !="" and action in validAction

这是两种情况:

1)当参数

中没有传递动作时
ansible-playbook playbook.yml 

错误:

ERROR: file not found: /path/to/action/.yml

预期输出:

Should be execute task 1 "Validate action" first.

2)当行动不对时

ansible-playbook playbook.yml -e "action=action5"

错误:

ERROR: file not found: /path/to/action/action5.yml

预期输出:

当用户传递无效操作的操作时,它应该检入task1 entity not in validEntity。在第一个任务中如果条件无效则应该中止执行。

处理此案件的任何建议?

1 个答案:

答案 0 :(得分:1)

似乎ansible在运行函数parse_yaml_from_file之前对包含进行了预先检查,如果FS上没有文件则会失败

作为一种解决方法,您可以使用以下代码,但您可能希望在Ansible github上将其报告为功能请求。

请在以下代码的目录操作下创建 dummy.yml 以使其工作touch action/dummy.yml

---
- hosts: all
  gather_facts: no

  vars: 

     action      : ""
     dummy       : "{{ action if action in validAction else 'dummy' }}"
     validAction : ["action1","action2","action3","action4"]

  tasks:
   - include: "action/{{dummy}}.yml"