Hi,
I am trying to fetch the json data from ami info in the existing yml using ansible.Now i am getting errors regarding json query format in number expression.
I need help with proper json query under set fact so that the indentation is maintained.Please suggest how this can be achieved.
I am using below code for this :-
Hi Team,
Looking forward to any input.
To start with You cannot use operators like > < etc on a string like ‘2022-06-10’.
Can you be more clear about what you want to achieve?
- 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)
Hi Dick,
I understand your point …I want to achieve the list of amis which is based on creation date.For example i want to print out list of amis for last 3 days and the output showing only 3 days before amis info…Thats the aim of above script.
I hope you understand my problem situation.Imagine you have 100 amis so u want to get info of particular date of amis like filters.
Thank you so much Vladimir Botka.And it works now.