Ansible 101 - Retrieving Date and Time in Ansible
Customers often need to retrieve basic information while automating tasks with Ansible. One frequently requested piece of information is the current date and time.
In many programming languages, developers typically call a function or module to obtain the current datetime, save it to a variable, and reuse it throughout their application. However, Ansible is not a traditional programming language — it is a declarative automation tool that focuses on achieving a desired state across target nodes. Therefore, retrieving date and time information in Ansible requires running a task on a target node.
There are several ways to gather the current datetime during an Ansible playbook run:
1. Using the setup
Module
The setup
module collects facts about a target node, including basic system information like the current time.
You can retrieve a minimal set of facts (which includes the date/time). This command gathers minimal facts from the localhost and saves them into a file called facts.json for later use.
ansible -m setup -a "gather_subset=min" localhost > facts.json
2. Using the pipe Lookup Plugin
Alternatively, you can generate a timestamp dynamically during a playbook run by using the pipe lookup to call the system date command:
---
- hosts: localhost
gather_facts: false
tasks:
- name: "Get the current timestamp"
set_fact:
timestamp: "{{ lookup('pipe', 'date +%Y%m%d%H%M%SZ') }}"
- name: "Display the timestamp"
debug:
msg: "Current timestamp is {{ timestamp }}"
3. Using the built-in ansible-date-time fact
Ansible’s built-in ansible_date_time fact already provides detailed timestamp information without needing to call external commands. You can use it like this:
---
- hosts: all
gather_facts: true
tasks:
- name: "Display ansible_date_time fact"
debug:
var: ansible_date_time
The ansible_date_time fact includes various fields like:
- ansible_date_time.date — current date (YYYY-MM-DD)
- ansible_date_time.time — current time (HH:MM:SS)
- ansible_date_time.iso8601 — ISO 8601 formatted timestamp
- and more.
This method is often the most efficient because it uses information already available during a playbook run when gather_facts is enabled.
Conclusion
By understanding these methods, you can flexibly retrieve and use date and time information within your Ansible automations, depending on your project’s needs.
Happy automating! 🚀