ansiblejinja2

Ansible Jinja2 Template dict in dict


I want to template php.ini configs for apache2 and cli. I filtered out the default options and added them to a dictionary like this:

php_config_options:
  cli:
    engine: "On"
    short_open_tag: "Off"
    precision: 14
    [...]
  apache2:
    engine: "On"
    short_open_tag: "Off"
    precision: 14
    [...]

I have put this under vars/Ubuntu-22.yaml so that I can configure it ongoing for the releases. My template looks like this:

{% if php_config_options[environment] is defined %}
{% for option, value in php_config_options[environment].items() %}
{{ option }} = {{ value }}
{% endfor %}
{% endif %}

and my task like this:

- name: setup | Template php.ini
  ansible.builtin.template:
    src: "{{ php_version }}/php.ini.j2"
    dest: /etc/php/{{ php_version }}/apache2/php.ini
    owner: root
    group: root
    mode: 0644
  vars:
    environment: "apache2"

When I try to run it I got the Error dict object has no element [] but I don't know why. Can anyone help me here?

My idea is to use these default variables, but when I want to change one I will set this in either group_vars or host_vars and he picks this + the other default ones.


Solution

  • Given the simplified dictionary

    php_config_options:
      cli:
        engine: "On"
        short_open_tag: "Off"
        precision: 14
    

    Use the filter community.general.to_ini. For example, the template

    {{ php_config_options | community.general.to_ini }}
    

    gives

    [cli]
    engine = On
    short_open_tag = Off
    precision = 14
    

    Example of a complete playbook for testing

    - hosts: localhost
    
      vars:
    
        php_config_options:
          cli:
            engine: "On"
            short_open_tag: "Off"
            precision: 14
    
      tasks:
    
        - copy:
            dest: /tmp/ansible/php.ini
            content: |
              {{ php_config_options | community.general.to_ini }}