当ansible查找失败时,如何退回到默认值?

编程入门 行业动态 更新时间:2024-10-08 10:39:49
本文介绍了当ansible查找失败时,如何退回到默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

本文发布于:2023-11-28 04:12:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1640907.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:默认值   ansible

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!