问题描述
我有点惊讶地发现他的代码段失败并出现 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.
所以你要么向 Ansible 团队修补 ini 查找插件/文件问题,要么使用这个丑陋的解决方法:
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查找失败时如何回退到默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!