Format date/time variable in Jinja2 template

I have a playbook that sets a fact for user info:

  • name: Get User Account Info
    set_fact:
    user_info: “{{ user_show.results | json_query(‘[*].json.result.result.{uid: uid[0], locked: krbloginfailedcount[0], disabled: nsaccountlock, pwdexp: krbpasswordexpiration[0].datetime}’) | list }}”

Later in the playbook, I use the template module to format up an HTML file that I email out. In that file, I’m trying to format the pwdexp variable above as a date/time string:

{% for user in user_info %}

{{ user.uid }} {{ user.locked }} {{ user.disabled }} {{ user.pwdexp|to_datetime('%m/%d/%Y %H:%M:%S').strftime('%s') }} {% endfor %}

The error I’m getting is: AnsibleError: template error while templating string: expected token ‘end of print statement’, got ‘.’

Any ideas on what I’m doing wrong?

Thanks,
Harry

I’d try adding some debugging before the template task, for example:

- name: Debug user variable
  ansible.builtin.debug:
    var: user
  loop: user_info
  loop_control:
    loop_var: user

- name: Debug user.pwdexp variable
  ansible.builtin.debug:
    var: user.pwdexp
  loop: user_info
  loop_control:
    loop_var: user

- name: Debug user.pwdexp | to_datetime variable
  ansible.builtin.debug:
    var: user.pwdexp | to_datetime('%m/%d/%Y %H:%M:%S')
  loop: user_info
  loop_control:
    loop_var: user

- name: Debug user.pwdexp | to_datetime.strftime variable
  ansible.builtin.debug:
    var: (user.pwdexp | to_datetime('%m/%d/%Y %H:%M:%S')).strftime('%s')
  loop: user_info
  loop_control:
    loop_var: user

However I think this might fix the template:

{% for user in user_info %}
{{ user.uid }} {{ user.locked }} {{ user.disabled }} {{ (user.pwdexp|to_datetime('%m/%d/%Y %H:%M:%S')).strftime('%s') }}
{% endfor %} 

Note the extra set of brackets.

So I added the extra parentheses in my template file, but now the playbook is giving the following error:

ValueError: time data ‘20241230121558Z’ does not match format ‘%m/%d/%Y %H:%M:%S’

Does the to_datetime and format have to match? I want to have 20241230121558 displayed as “12/30/2024 12:15:58Z”.

Thanks,
Harry

1 Like

Yes I, think so, see the documentation here and here.

What is an example value of user.pwdexp?

I figured it out. I changed the template to the following:

{{ (user.pwdexp|to_datetime(‘%Y%m%d%H%M%SZ’)).strftime(‘%m/%d/%Y %H:%M:%S’) }}

So the to_datetime matches the data format, and strftime prints that how I need it. All good now.

Thanks,
Harry

2 Likes