Search code examples
ansiblejinja2ansible-vault

Ansible Jinja2 template - Remove trailing whitespace


I am trying to load an ansible vault file into an k8 configmap YAML file using Ansible Jinja template but facing an issue with a trailing whitespace getting added at the end of the contents of the YAML file. This is causing errors as below:

Vault format unhexlify error: Odd-length string

Sample of ansible template am using is :

Playbook main.yml -

- name: display multiple files   
  shell: cat /tmp/test.yml   
  register: test

Ansible Jinja Template

apiVersion: v1
data:
 test.yml: |-
     {{ test.stdout.splitlines()|indent(4, false)|trim|replace(' ','') }}
kind: ConfigMap
metadata: 
  name: test
  namespace: test-namespace

test.yml example:

  $ANSIBLE_VAULT;1.1;AES256
  62313365396662343061393464336163383764373764613633653634306231386433626436623361
  6134333665353966363534333632666535333761666131620a663537646436643839616531643561
  63396265333966386166373632626539326166353965363262633030333630313338646335303630
  3438626666666137650a353638643435666633633964366338633066623234616432373231333331
  6564

Output YAML created from Jinja Template is below

apiVersion: v1
data:
 test.yml:
     $ANSIBLE_VAULT;1.1;AES256
  62313365396662343061393464336163383764373764613633653634306231386433626436623361
  6134333665353966363534333632666535333761666131620a663537646436643839616531643561
  63396265333966386166373632626539326166353965363262633030333630313338646335303630
  3438626666666137650a353638643435666633633964366338633066623234616432373231333331
  6564   
kind: ConfigMap
metadata: 
  name: test
  namespace: test-namespace

Can you please let me know what i may be missing in my ansible template file to fix the above trailing whitespace issues.


Solution

  • I am trying to load a Ansible Vault encrypted file into a configmap using jinja2 templating

    Then you are solving the wrong problem; let the to_yaml filter do all that escaping for you, rather than trying to jinja your way through it.

    - command: cat /tmp/test.yml
      register: tmp_test
    - set_fact:
        cm_skeleton:
          apiVersion: v1
          data:
          kind: ConfigMap
          metadata: 
            name: test
            namespace: test-namespace
    - copy:
        content: >-
          {{ cm_skeleton | combine({"data":{"test.yml": tmp_test.stdout}}) | to_yaml }}
        dest: /tmp/test.configmap.yml
    

    If you have other things you are trying to template into that ConfigMap, fine, you can still do so, but deserialize in into a dict so you can insert the literal contents of test.yml into the dict and then re-serialize using the to_yaml filter:

    - set_fact:
       cm_skeleton: '{{ lookup("template", "cm.j2") | from_yaml }}'
    - copy:
       contents: '{{ cm_sketeton | combine({"data"...}) | to_yaml }}'