Nathan
Nathan

Reputation: 7709

How to render all ansible variables to yml file with ansible 2.3

I am storing all ansible variables to a yaml file (filtering out those that starting with 'ansible_') with this playbook:

- hosts: localhost
  tasks:
  - set_fact:
      all_vars: "{{all_vars | default({}) |combine({item.key: item.value})}}"
    when: "{{not item.key.startswith('ansible_')}}"
    with_dict: "{{vars}}"
  - copy:
      content: "{{ all_vars }}"
      dest: "/tmp/tmp.yml"

This is group_vars/all/defaults.yml

SOME_FACT1: "some-fact"
SOME_FACT2: "{{ SOME_FACT1 }}"
SOME_FACT3: "{{ SOME_FACT2 }}"

This works perfectly with ansible 2.2. But with ansible 2.3 (2.3.1.0) the variables are not rendered. I get results like this:

... "SOME_FACT1": "some-fact", "SOME_FACT3": "{{ SOME_FACT2 }}", "SOME_FACT2": "{{ SOME_FACT1 }}" ...

How can i force ansible 2.3 to render the variables?

Upvotes: 1

Views: 855

Answers (1)

Nathan
Nathan

Reputation: 7709

The problem seems, that ansible will not render vars and (I do not know why) all_vars. But any variable inside vars/all_vars is rendered properly when used directly.

So this works:

- hosts: localhost
  tasks:
  - set_fact:
          all_vars: "{{all_vars | default([]) |union([item.key + ':{{' + item.key + '|to_json}}'])}}"
    when: "{{not item.key.startswith('ansible_')}}"
    with_dict: "{{vars}}"
  - copy:
      content: "{{ all_vars | join('\n') }}"
      dest: "/tmp/tmp1.yml"
  - template:
      src: "/tmp/tmp1.yml"
      dest: "/tmp/tmp.yml"

The idea is:

  1. Create a file that lists all variables in the format

    SOME_VAR: {{ SOME_VAR | to_json }} ...

  2. Render that file using template.

Not very nice, but it works.

Upvotes: 1

Related Questions