I am looking to convert date input variable into epoch. I did not see a Ansible function to help me with this.
For eg:
Date is a variable of format: %m/%d/%Y %H:%M:%S
, this needs to be converted to epoch secs.
Ansible has a to_datetime
filter, documented here. That page includes the following examples:
# Get total amount of seconds between two dates. Default date format is %Y-%m-%d %H:%M:%S but you can pass your own format {{ (("2016-08-14 20:00:12" | to_datetime) - ("2015-12-25" | to_datetime('%Y-%m-%d'))).total_seconds() }} # Get remaining seconds after delta has been calculated. NOTE: This does NOT convert years, days, hours, etc to seconds. For that, use total_seconds() {{ (("2016-08-14 20:00:12" | to_datetime) - ("2016-08-14 18:00:00" | to_datetime)).seconds }} # This expression evaluates to "12" and not "132". Delta is 2 hours, 12 seconds # get amount of days between two dates. This returns only number of days and discards remaining hours, minutes, and seconds {{ (("2016-08-14 20:00:12" | to_datetime) - ("2015-12-25" | to_datetime('%Y-%m-%d'))).days }}
Using this filter, you could convert a date to string to a unix epoch time like this:
- debug:
msg: "{{ ('2019-05-06 15:50:00'|to_datetime).strftime('%s') }}"
Which would output:
TASK [debug] **********************************************************************************
ok: [localhost] => {
"msg": "1557172200"
}
I had to convert a string for the user module. The other approaches her didn't work for me.
You can use strftime
:
vars:
expire_date: 2020-07-12
task:
- name: "create user"
user:
name: user
expires: "{{ expire_date.strftime('%s') }}"
become: true
Thanks, that worked. here is what i am doing
- name: update blackout file
win_lineinfile:
path: D:\temp\blackout\blackout.txt
backup: yes
insertafter: EOF
line: "\\r\\nPermissions: admin=write\\r\\nadhoc:{{ regex_suppression }};{{ start_date_epoch }};{{ end_date_epoch }};{{ changerequest }}"
vars:
regex_suppression: "^(?i).*__({{serverlist | regex_replace(',','|')}}).*"
start_date_epoch: "{{ ( start_time | to_datetime).strftime('%s') }}"
end_date_epoch: "{{ ( end_time | to_datetime).strftime('%s') }}"
I had to use the following to get a date stored from a previous call (e.g. 2020-03-10) converted.
msg: "{{ ((variable.stdout + ' 00:00:00') | to_datetime).strftime('%s') }}"