Am trying to read a file line by line and delete the line if certain conditions are met
sample input file:
abcd Sat Oct 25 04:30:35 EDT 2036
defg Tue Dec 01 18:59:59 EST 2037
ghij Fri Jun 17 06:15:06 EDT 2022
Expected output file:
abcd Sat Oct 25 04:30:35 EDT 2036
defg Tue Dec 01 18:59:59 EST 2037
The logic needed is read the file line by line and read the year at the last field. If it's less than 2023 then delete that line in the file. if greater than 2023 keep the line. in this example, the last line should be deleted , since the year 2022 is lesser than 2023.
sample code:
- name: read file
set_fact:
root_certificate_content: "{{ lookup('file', /home/user/cert_cleanup/{{ output_file }}) }}"
- name: display debug:
year: "{{ root_certificate_content.split('\n') [-1]}}"
- name: remove line
<< delete that line >>
when:
- year.value < 2023
I tried multiple options, nothing see to work. Error in 1st step itself
Given the file
Get the content of the file
Split lines, create a list of the years, and create a dictionary from the years and lines
gives
Reject the lines older than 2023 and join the lines
gives
Write the file
Example of a complete playbook for testing
gives running with options --check --diff
Notes:
run_once: truedelegate_to: localhost