Ansible 将变量写入 YAML 文件 [英] Ansible write variables into YAML file

查看:46
本文介绍了Ansible 将变量写入 YAML 文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个特定的 ansible 变量结构,我想将它从 Vault 获取到我主机上的 yaml 文件中.

I have a specific ansible variable structure that I want to get from the vault into a yaml file on my hosts.

让我们假设一个这样的结构:

Lets assume a structure like this:

secrets:
   psp1:
     username: this
     password: that
   secret_key: 123
  ...

我需要一个类似通用"模板的东西来输出目前包含的任何秘密",因为内容几乎完全根据当前环境发生变化.

I need something like a "generic" template to output whatever "secrets" contains at the moment, since the content changes almost completely based on the current environment.

我能想到的最简单的解决方案是在这样的模板中输出整个结构:

The easiest solution I can think of is to output the whole structure in an template like this:

# config/secrets.yml
{{ secrets | to_yaml }}

但是jinja2 to_yaml过滤器只对第一层进行yamlify",在json中输出更深的嵌套.

But the jinja2 to_yaml filter does only "yamlify" the first level, deeper nestings are outputted in json.

我能以某种方式解决这个问题吗?有没有更简单的方法来实现我想要的?

Can I work around that problem somehow? Is there an easier way to achieve what I want?

感谢您的帮助!

推荐答案

  1. 正如 jwodder 所说,它是有效的.

  1. As jwodder said, it's valid.

如果您使用的是 to_yaml(而不是 to_nice_yaml),那么您安装的 ansible 已经很旧了,是时候升级了.

If you're using to_yaml (instead of to_nice_yaml) you have fairly old install of ansible, it's time to upgrade.

使用to_nice_yaml

可以将您自己的 kwargs 传递给过滤函数,这些函数通常将它们传递给底层的 Python 模块调用.喜欢这个你的情况.所以像:

It's possible to pass your own kwargs to filter functions, which usually pass them on to underlying python module call. Like this one for your case. So something like:

 {{ secrets | to_nice_yaml( width=50, explicit_start=True, explicit_end=True) }}

唯一的问题是你不能覆盖indent=4,allow_unicode=True,default_flow_style=False

only catch is you can't override indent=4, allow_unicode=True, default_flow_style=False

请注意,indent 现在可以被覆盖,至少从 Ansible 2.2.0 开始(我使用它来缩进 2 个空格以遵循一个项目的编码标准).

Note that indent can now be overridden, at least as of Ansible 2.2.0 (I use it to indent 2 spaces to follow coding standards for one project).

可以找到 to_nice_yaml 的更好文档这里.

Better documentation for to_nice_yaml can be found here.

这篇关于Ansible 将变量写入 YAML 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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