当ansible查找失败时,如何退回到默认值? [英] How to fallback to a default value when ansible lookup fails?
问题描述
我很惊讶地发现他的代码因IOError异常而失败,而不是默认忽略该值.
I was a little bit surprised to discover that his piece of code fails with an IOError exception instead of defaulting to omitting the value.
#!/usr/bin/env ansible-playbook -i localhost,
---
- hosts: localhost
tasks:
- debug: msg="{{ lookup('ini', 'foo section=DEFAULT file=missing-file.conf') | default(omit) }}"
如何在不引发异常的情况下加载值?
How can I load a value without raising an exception?
请注意,查找模块支持默认值参数,但是这个对我来说是没有用的,因为它仅在可以打开文件时才起作用.
Please note that the lookup module supports a default value parameter but this one is useless to me because it works only when it can open the file.
我需要一个即使无法打开文件也可以使用的默认值.
I need a default value that works even when the it fails to open the file.
推荐答案
据我所知,Jinja2不支持任何try/catch机制.
As far as I know Jinja2 unfortunately doesn't support any try/catch mechanism.
因此,您可以将ini查找插件/文件问题修补到Ansible团队,或者使用此丑陋的解决方法:
So you either patch ini lookup plugin / file issue to Ansible team, or use this ugly workaround:
---
- hosts: localhost
gather_facts: no
tasks:
- debug: msg="{{ lookup('first_found', dict(files=['test-ini.conf'], skip=true)) | ternary(lookup('ini', 'foo section=DEFAULT file=test-ini.conf'), omit) }}"
在此示例中,first_found
查找返回文件名(如果文件存在),否则返回空列表.如果文件存在,则ternary
过滤器将调用ini
查找,否则将返回omit
占位符.
In this example first_found
lookup return file name if file exists or empty list otherwise. If file exists, ternary
filter calls ini
lookup, otherwise omit
placeholder is returned.
这篇关于当ansible查找失败时,如何退回到默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!