Ansible: prevent interpreting variable’s content as JSON/YAML

ansible

I’m trying to use Ansible to tweak an ini-style configuration file, where one value is formatted as JSON data.

I tried the following task:

- name: Update configuration
  ini_file:
    dest: "{{ service_root }}/etc/production.ini"
    create: no
    section: app:main
    option: "{{ item.option }}"
    value: "{{ item.value }}"
    mode: '0640'
  notify: Reload Apache configuration
  with_list:
    - option: repoze.who.auth_tkt.secret
      value: "{{ secrets.auth_tkt }}"
    - option: oidc.client_config
      value: "{{ oidc_client_config | to_json }}"
  loop_control:
    label: "{{ item.option }}"

Unfortunately, when I try it, the oidc.client_config is not formatted as expected: the strings are between single-quote symbols instead of double-quote, and the false value shows up as False instead of false

As I understand it, when I use the item.value variable, Ansible sees it looks like JSON and decodes it, and then converts it to string, using Python’s str() function.

I tried a single-option task:

- name: Update configuration
  ini_file:
    dest: "{{ service_root }}/etc/production.ini"
    create: no
    section: app:main
    option: oidc.client_config
    value: "{{ oidc_client_config | to_json }}"
    mode: '0640'
  notify: Reload Apache configuration

This one works fine, I get the value formatted as expected in my configuration file. Hence, I can split split my initial task and then it works fine, but I’m unhappy with this solution.

Is there a way to prevent interpretation of the item.value variable as JSON/YAML?

For what it’s worth, I’m currently using (the quite ancient) Ansible 2.2.

Best Answer

In the advanced syntax section of the manual (https://docs.ansible.com/ansible/latest/user_guide/playbooks_advanced_syntax.html) there is a section on unsafe or raw strings. My understanding is you can just mark your value as unsafe and it will not be interpreted:

value: !unsafe "{{ oidc_client_config | to_json }}"