我很惊讶地发现他的代码因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查找失败时,如何退回到默认值?
发布评论