Ansible 仅当文件存在时才包含任务 [英] Ansible include task only if file exists

查看:48
本文介绍了Ansible 仅当文件存在时才包含任务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图仅包含存在的文件.如果我的角色的用户需要,这允许在现有任务/角色"之间自定义任务/角色".我发现了这个:

I'm trying to include a file only if it exists. This allows for custom "tasks/roles" between existing "tasks/roles" if needed by the user of my role. I found this:

- include: ...
  when: condition

但是 Ansible 文档指出:

But the Ansible docs state that:

所有任务都得到评估,但条件适用于每个任务" - http://docs.ansible.com/playbooks_conditionals.html#applying-when-to-roles-and-includes

"All the tasks get evaluated, but the conditional is applied to each and every task" - http://docs.ansible.com/playbooks_conditionals.html#applying-when-to-roles-and-includes

所以

- stat: path=/home/user/optional/file.yml
  register: optional_file
- include: /home/user/optional/file.yml
  when: optional_file.stat.exists

如果包含的文件不存在,将会失败.我想可能有另一种机制允许用户向现有配方添加任务.我不能让用户在我的之后添加角色,因为他们无法控制顺序:他们的角色将在我的之后执行.

Will fail if the file being included doesn't exist. I guess there might be another mechanism for allowing a user to add tasks to an existing recipe. I can't let the user to add a role after mine, because they wouldn't have control of the order: their role will be executed after mine.

推荐答案

感谢大家的帮助!我在今天的 Ansible 中尝试了所有回答和我自己的问题代码后,正在回答我自己的问题:ansible 2.0.1.0

Thanks all for your help! I'm aswering my own question after finally trying all responses and my own question's code back in today's Ansible: ansible 2.0.1.0

我的原始代码现在似乎可以工作了,除了我正在查找的可选文件在我的本地机器中,所以我不得不通过 local_action 运行 stat 并设置 become: no 对于那个特定的任务,所以 ansible 不会尝试在我的本地机器上执行 sudo 并出现错误:"sudo: a password is required\n"

My original code seems to work now, except the optional file I was looking was in my local machine, so I had to run stat through local_action and set become: no for that particular tasks, so ansible wouldn't attempt to do sudo in my local machine and error with: "sudo: a password is required\n"

- local_action: stat path=/home/user/optional/file.yml
  register: optional_file
  become: no
- include: /home/user/optional/file.yml
  when: optional_file.stat.exists

这篇关于Ansible 仅当文件存在时才包含任务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆