On Wed, 15 Jun 2022 02:10:08 -0700 (PDT)
Nipun Jain <[email protected]> wrote:

>     - name: Gather AMI Info
>       amazon.aws.ec2_ami_info:
>         owners: self
>         region: us-east-1
>         filters:
>           state: available
>       register: result

Let's assume the data below for testing

    result:
      images:
        - name: app1
          creation_date: '2022-06-13T19:22:13.000Z'
        - name: app2
          creation_date: '2022-06-14T19:22:13.000Z'
        - name: app3
          creation_date: '2022-06-15T19:22:13.000Z'

>     - name: Set fact date from last {{ec2_input_day}} days
>       run_once: yes
>       set_fact:
>         ec2_f_date: "{{ lookup('pipe','date \"+%Y-%m-%d\"
>                         -d "{{ec2_input_day}} day ago\"') }}"

To get the current date use filter *strftime*, e.g.

    ec2_f_date: "{{ '%Y-%m-%d %H:%M:%S'|strftime }}"

gives

    ec2_f_date: '2022-06-16 10:29:58'

> 
>     - name: Set fact date from {{ec2_input_day}} days using amis filters
>       run_once: yes
>       set_fact:
>         ec2_f_amis: "{{ result | json_query(\"item[?creation_date<= \" + 
> ec2_f_date + \"]\") }}"
>     - debug:
>         var: ec2_f_amis

Use filter *to_datetime*. See "Handling dates and times"
https://docs.ansible.com/ansible/latest/user_guide/playbooks_filters.html#handling-dates-and-times

Given 

    ec2_input_day: '2'

In the loop, calculate the difference in days and evaluate the
condition, e.g.

    - debug:
        msg: "Age of {{ item.name }}
              is greater than or equal {{ ec2_input_day }} day(s)"
      loop: "{{ result.images }}"
      when: days|int >= ec2_input_day|int
      vars:
        days: "{{ (ec2_f_date|to_datetime -
                  item.creation_date|
                  to_datetime('%Y-%m-%dT%H:%M:%S.000Z')).days }}"

will display the first image. The other two will be skipped

    msg: Age of app1 is greater than or equal 2 day(s)

-- 
Vladimir Botka

-- 
You received this message because you are subscribed to the Google Groups 
"Ansible Project" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/ansible-project/20220616104704.017f3fa7%40gmail.com.

Attachment: pgp_yapBPL88I.pgp
Description: OpenPGP digital signature

Reply via email to