1

I want to provision a JSON file with Ansible. The content of this file is a variable in my Ansible's playbook.

And very important for my usecase: I need the indentation & line breaks to be exactly the same as in my variable.

The variable looks like this :

my_ansible_var: 
  {
    "foobar": {
      "foo": "bar"
    },
    "barfoo": {
      "bar": "foo"
    }
  }

And it's use like this in my playbook :

- name: drop the gitlab-secrets.json file
  copy: 
    content: "{{ my_ansible_var }}"
    dest: "/some/where/file.json"

Problem: when this tasks is played, my file is provisionned but as a "one-line" file:

{ "foobar": { "foo": "bar" }, "barfoo": { "bar": "foo" } }

I tried several other ways:

  • Retrieve the base64 value of my JSON content, and use content: "{{ my_ansible_var | b64decode }}" : same problem at the end
  • I tried playing with YAML block indicator : none of the block indicators helped me with that problem
  • I tried adding some filters like to_json, to_nice_json(indent=2) : no more luck here

Question:

How in Ansible can I provison a JSON file while keeping the exact indentation I want ?

Community
  • 1
  • 1
Pierre
  • 2,552
  • 5
  • 26
  • 47

1 Answers1

2
  1. In your example my_ansible_var is a dict. If you don't need to access its keys in your playbook (e.g. my_ansible_var.foobar.foo) and just want it as JSON string for your copy task, force it to be a string.

  2. There is type-detection feature in Ansible template engine, so if you feed it with dict-like or list-like string, it will be evaluated into object. See some details here.

This construction will work ok for your case:

---
- hosts: localhost
  gather_facts: no
  vars:
    my_ansible_var: |
      {
        "foobar": {
          "foo": "bar"
        },
        "barfoo": {
          "bar": "foo"
        }
      }
  tasks:
    - copy:
        content: "{{ my_ansible_var | string }}"
        dest: /tmp/out.json

Note vertical bar in my_ansible_var definition and | string filter in content expression.

Community
  • 1
  • 1
Konstantin Suvorov
  • 65,183
  • 9
  • 162
  • 193
  • 1
    Thanks, it works as expected. I was misunderstanding the way I was declaring/using my variable – Pierre Mar 20 '17 at 09:51