Convert epoch time to datetime within JSON query not working in Ansible

132 Views Asked by At

I have a list of dictionaries and for all items in this list, I want to convert one key-value pair epoch time to datetime but I'm getting an error

"JMESPathError in json_query filter plugin:\nUnknown function: strftime()"

Here is the code:


- name: Update list of dicts
  hosts: localhost
  gather_facts: false
  vars:
    var1: [ { "name": "abc", "id": "23213123", "epochTime": 1687505936 }, { "name": "def", "id": "9c5219430000005c", "epochTime": 1687505950 } ]

  tasks:

  - name: Convert epoch time to datetime for list of dictionaries 
    set_fact:
      list_dict_human_readable: "{{ var1 | json_query('[].{name: name, id: id, epochTime: epochTime | int | \"%Y-%m-%d %H:%M:%S\" | strftime(ansible_date_time.epoch) }') }}"

  - debug:
      msg: "{{ list_dict_human_readable }}"


Expected result:

list_dict_human_readable: [ { "name": "abc", "id": "23213123", "epochTime": "2023-06-23 07:38:56"}, { "name": "def", "id": "9c5219430000005c", "epochTime": "2023-06-23 07:39:10"} ]

Ansible version is 2.9

Any idea? Thanks.

1

There are 1 best solutions below

8
Vladimir Botka On

Create the update

  var1_update: |
    {% filter from_yaml %}
    {% for i in var1 %}
    - {epochTime: "{{ '%Y-%m-%d %H:%M:%S'|strftime(i.epochTime) }}"}
    {% endfor %}
    {% endfilter %}

gives

  var1_update:
  - epochTime: '2023-06-23 09:38:56'
  - epochTime: '2023-06-23 09:39:10'

Update var1

    - set_fact:
        var1: "{{ var1|zip(var1_update)|map('combine') }}"

gives what you want

  var1:
  - epochTime: '2023-06-23 09:38:56'
    id: '23213123'
    name: abc
  - epochTime: '2023-06-23 09:39:10'
    id: 9c5219430000005c
    name: def

Example of a complete playbook for testing

- hosts: localhost

  vars:

    var1:
      - epochTime: 1687505936
        id: '23213123'
        name: abc
      - epochTime: 1687505950
        id: 9c5219430000005c
        name: def

    var1_update: |
      {% filter from_yaml %}
      {% for i in var1 %}
      - {epochTime: "{{ '%Y-%m-%d %H:%M:%S'|strftime(i.epochTime) }}"}
      {% endfor %}
      {% endfilter %}
        
  tasks:

    - debug:
        var: var1_update

    - set_fact:
        var1: "{{ var1|zip(var1_update)|map('combine') }}"
    - debug:
        var: var1