Prevent to_nice_yaml filter from quoting integers when populated from variable

Hi,

I’m trying to deploy the contents of a dictionary to a yaml file:

- name: Deploy template
  vars:
    - cloud_init_config:
        fqdn: "{{ inventory_hostname }}"
        prefer_fqdn_over_hostname: true
        manage_etc_hosts: true
        ssh_pwauth: true
        users:
          - name: "{{ cloud_init_user }}"
            uid: "{{ cloud_init_user_uid | int }}"
  ansible.builtin.template:
    src: cloud_init.j2
    dest: /tmp/cloud_init
  delegate_to: localhost
  become: false

The template I’m using looks like this:

{{ cloud_init_config | to_nice_yaml(indent=2) }}

Which results in:

$ cat /tmp/cloud_init 
fqdn: test.example.com
manage_etc_hosts: true
prefer_fqdn_over_hostname: true
ssh_pwauth: true
users:
- name: spike
  uid: '1000'

Is there a way to prevent the uid from being quoted? Using a string for the uid parameter was deprecated with cloud-init 22.3 and I’m trying to fix it before it becomes an issue.

When I don’t set the value for the uid key from a variable everything works as expected, i.e.:

- name: Deploy template
  vars:
    - cloud_init_config:
        fqdn: "{{ inventory_hostname }}"
        prefer_fqdn_over_hostname: true
        manage_etc_hosts: true
        ssh_pwauth: true
        users:
          - name: "{{ cloud_init_user }}"
            uid: 1000
  ansible.builtin.template:
    src: cloud_init.j2
    dest: /tmp/cloud_init
  delegate_to: localhost
  become: false

leads to

$ cat /tmp/cloud_init 
fqdn: test.example.com
manage_etc_hosts: true
prefer_fqdn_over_hostname: true
ssh_pwauth: true
users:
- name: spike
  uid: 1000

Any pointers are greatly appreciated!

Use jinja2_native so that templating can return non-strings, or template more of the structure so that Ansible can parse the returned string back into a data structure.

        users:
          - "{{ { 'name': cloud_init_user, 'uid': cloud_init_user_uid | int } }}"
2 Likes

Enabling jinja2_native didn’t make a difference I’m afraid.

This worked though:

users:
  - "{{ { 'name': cloud_init_user, 'uid': cloud_init_user_uid | int } }}"

Thanks a bunch!

1 Like

Ah, I always forget that the template module is not affected by jinja2_native.

1 Like