20

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 }}

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?

Thanks for any help!

1 Answers1

31
  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) }}

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

* 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).

Better documentation for to_nice_yaml can be found here.

Kashyap
  • 15,354
  • 13
  • 64
  • 103
  • this worked out great for my playbook for elasticsearch, dumped the entire config from an array – Jacob Evans Feb 24 '16 at 16:06
  • 1
    It's not a formatting bug, it's a markdown feature. Code inside a list item has to be double-indented. – Nick Volynkin Apr 29 '16 at 08:39
  • 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). See: https://github.com/ansible/ansible/pull/17085 – geerlingguy Jun 19 '17 at 16:35
  • @Kashyap Where did you get to_nice_yaml options documentation? – EnzoR Dec 15 '20 at 10:38
  • 1
    @EnzoR from code, not documentation. But sure if they updated it in last 4 years. – Kashyap Dec 15 '20 at 14:25
  • What about default_style and friends? Do I really need to get to the source code? Which files were you reading? – EnzoR Dec 15 '20 at 14:57
  • @EnzoR, it's here: https://github.com/ansible/ansible/blob/stable-2.12/lib/ansible/plugins/filter/core.py#L57, and this seems to be the fix for indent: https://github.com/ansible/ansible/commit/27d065924f5a5318db4ecb52ec695cf1e4de7293 – Kashyap Feb 24 '22 at 23:03