Automating Dynamic Time Date Facts with Ansible

How to use the set_fact module and lookup plugin to set Ansible date.

Luca Berton



In the realm of automation and infrastructure management, Ansible stands out for its simplicity and power, enabling IT professionals to automate a wide array of tasks efficiently. One of the lesser-discussed yet powerful features of Ansible is its ability to set facts dynamically during playbook execution. This capability can be particularly useful when you need to generate values on the fly, such as capturing the current date and time.

A practical application of this is setting a fact to hold the current date and time, which can be used for various purposes such as timestamping files, creating backup directories with the date, or logging. Let’s delve into how you can leverage Ansible’s set_fact module along with the lookup plugin to achieve this.

Understanding set_fact and lookup

Before we dive into the example, it’s essential to understand the two key components we’ll be using: ansible.builtin.set_fact and lookup.

  • ansible.builtin.set_fact: This module is used to set new variables on a host-by-host basis during playbook execution. These variables will be available for the remainder of the playbook's execution and can be used to influence the outcome dynamically.
  • lookup: The lookup plugin is used to retrieve data from outside sources within your Ansible playbooks. There are many types of lookup plugins, but in our example, we will use the pipe lookup to execute a shell command on the control node and use its output.

The Practical Example: Setting a Date Fact

Let’s look at a practical example where we set a fact named unix_date that captures the current date and time in a specific format:

- name: "Set a fact for the date"
unix_date: "{{ lookup('pipe', 'date +%Y-%m-%d-%H%M') }}"

In this task:

  • Task Name: It’s always a good practice to give your tasks descriptive names. Here, it clearly indicates that this task is setting a fact for the date.



Luca Berton

I help creative Automation DevOps, Cloud Engineer, System Administrator, and IT Professional to succeed with Ansible Technology to automate more things everyday