Jinja Formatting of Inline Certificate

Viewed 43

I'm attempting to use Jinja to automate the creation of a config file with inline certificates. For the most part, the config as a whole looks as expected with the exception of the certificates. While I can get them into the end file, the formatting is messed up and thus not working.

The expected goal is obviously

pki:
  # The CAs that are accepted by this node. Must contain one or more certificates created by 'nebula-cert ca'
  ca: |
    -----BEGIN CERTIFICATE-----
    <snip>
    -----END CERTIFICATE-----
  cert: |
    -----BEGIN CERTIFICATE-----
    <snip>
    -----END CERTIFICATE-----
  key:  |
    -----BEGIN X25519 PRIVATE KEY-----
    <snip>
    -----END X25519 PRIVATE KEY-----

But I'm ending up with

pki:
  # The CAs that are accepted by this node. Must contain one or more certificates created by 'nebula-cert ca'
  ca: |
    -----BEGIN CERTIFICATE-----
  <snip>
  -----END CERTIFICATE-----
  cert: |
    -----BEGIN CERTIFICATE-----
  <snip>
  -----END CERTIFICATE-----
  key:  |
    -----BEGIN X25519 PRIVATE KEY-----
  <snip>
  -----END X25519 PRIVATE KEY-----

The snippet from my Jinja template looks like this:

pki:
  ca: |
    {{ca}}
  cert: |
    {{hostCert}}
  key:  |
    {{hostKey}}

The template is obviously lined up, but I'm obviously missing some form of formatting. I've attempted to use the |center(x) formatting but it's not working... or doing anything that I can see. Does anyone have advice on getting the certificates to align properly so that they're read correctly?

1 Answers

Jinja is doing exactly what you've told it to do: it places the value of the ca variable in your text where you've placed the {{ ca }} token. The content of the ca variable isn't indented, so it's not indented when you place it in your document.

If you want to indent a block of text, Jinja provides the indent filter. You would use it like this:

pki:
  ca: |
    {{ca|indent(4)}}

Having said that...this seems like a situation in which using Jinja is a sub-optimal solution: why not just render the YAML from a Python data structure using yaml.safe_dump?

Related