Ansible将变量写入YAML文件

Ansible将变量写入YAML文件

本文介绍了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所说,这是有效的.
  2. 如果您使用的是to_yaml(而不是to_nice_yaml),那么您已经安装了较旧的ansible,现在该进行升级了.
  3. 使用to_nice_yaml
  4. 可以将您自己的kwarg传递给过滤器函数,通常将它们传递给底层的python模块调用.像你的情况.像这样:

  1. As jwodder said, it's valid.
  2. If you're using to_yaml (instead of to_nice_yaml) you have fairly old install of ansible, it's time to upgrade.
  3. Use to_nice_yaml
  4. 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

请注意,至少从Ansible 2.2.0起,indent现在可以被覆盖(我使用它缩进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).

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

07-30 19:27