AnsiblePilot — Master Ansible Automation

AnsiblePilot is the leading resource for learning Ansible automation, DevOps, and infrastructure as code. Browse over 1,400 tutorials covering Ansible modules, playbooks, roles, collections, and real-world examples. Whether you are a beginner or an experienced engineer, our step-by-step guides help you automate Linux, Windows, cloud, containers, and network infrastructure.

Popular Topics

About Luca Berton

Luca Berton is an Ansible automation expert, author of 8 Ansible books published by Apress and Leanpub including "Ansible for VMware by Examples" and "Ansible for Kubernetes by Example", and creator of the Ansible Pilot YouTube channel. He shares practical automation knowledge through tutorials, books, and video courses to help IT professionals and DevOps engineers master infrastructure automation.

ansible_date_time: Access Date, Time & Timestamp Facts in Ansible

By Luca Berton · Published 2024-01-01 · Category: windows-automation

Complete guide to ansible_date_time fact. Access date, time, epoch, ISO8601, and timezone variables in playbooks with strftime formatting examples.

ansible_date_time: Access Date, Time & Timestamp Facts in Ansible

Introduction

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 ansible.builtin.set_fact module along with the lookup plugin to achieve this.

Understanding ansible.builtin.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.

See also: Mastering Time in Ansible: An Introduction to the now() Function

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"
  ansible.builtin.set_fact:
    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. • ansible.builtin.set_fact Module: This module is used to define a new variable. • unix_date: This is the name of the variable (or fact) we are setting. The name can be anything you choose, but it should be descriptive of the data it holds. • lookup('pipe', 'date +%Y-%m-%d-%H%M'): This part of the task is where the magic happens. The lookup plugin with the pipe argument is used to execute the date command on the control node. The +%Y-%m-%d-%H%M format specifies that we want the output to be in the format of Year-Month-Day-HourMinute.

Use Cases

Once unix_date fact is set, you can use it anywhere within your playbook. Here are a few examples of how you might use this fact: • Creating timestamped backup directories. • Naming log files with the execution date and time. • Tagging resources with the creation date in cloud environments.

See also: Mastering Ansible-Creator: Simplify Your Ansible Collection Development

Conclusion

Leveraging Ansible's ansible.builtin.set_fact module with the lookup plugin to set dynamic date facts is a powerful technique that can enhance your automation strategies. It's a testament to Ansible's flexibility and capability to adapt to various operational needs. This method is not only efficient but also simplifies processes that require dynamic values, making your automation tasks more robust and reliable. Whether you're a seasoned Ansible user or new to the platform, incorporating dynamic date facts into your playbooks can significantly streamline your automation workflows.

Access Date/Time Facts

- debug:
    msg:
      - "Date: {{ ansible_date_time.date }}"           # 2026-04-05
      - "Time: {{ ansible_date_time.time }}"           # 14:30:45
      - "ISO: {{ ansible_date_time.iso8601 }}"         # 2026-04-05T14:30:45Z
      - "Epoch: {{ ansible_date_time.epoch }}"         # 1743868245
      - "Year: {{ ansible_date_time.year }}"           # 2026
      - "Month: {{ ansible_date_time.month }}"         # 04
      - "Day: {{ ansible_date_time.day }}"             # 05
      - "Hour: {{ ansible_date_time.hour }}"           # 14
      - "Weekday: {{ ansible_date_time.weekday }}"     # Sunday
      - "TZ: {{ ansible_date_time.tz }}"               # UTC

See also: Creating Ansible Collection Using ansible-creator and VS Code Ansible Extension

Timestamp in Filenames

- name: Backup with timestamp
  ansible.builtin.copy:
    src: /etc/nginx/nginx.conf
    dest: "/backup/nginx.conf.{{ ansible_date_time.iso8601_basic_short }}"
    remote_src: true
  become: true
# Result: nginx.conf.20260405T143045

Format Dates with strftime

- set_fact:
    formatted_date: "{{ '%Y-%m-%d %H:%M:%S' | strftime }}"
    custom_format: "{{ '%d/%m/%Y' | strftime }}"

# From epoch - set_fact: from_epoch: "{{ '%Y-%m-%d' | strftime(1743868245) }}"

now() Function

- debug:
    msg:
      - "Now: {{ now() }}"
      - "UTC: {{ now(utc=true) }}"
      - "Formatted: {{ now().strftime('%Y-%m-%d') }}"
      - "Epoch: {{ now().strftime('%s') }}"

Date Arithmetic

# Days ago
- set_fact:
    seven_days_ago: "{{ '%Y-%m-%d' | strftime(ansible_date_time.epoch | int - 604800) }}"

# Hours from now - set_fact: two_hours_later: "{{ '%H:%M' | strftime(ansible_date_time.epoch | int + 7200) }}"

Conditional by Time

# Only run during business hours
- name: Deploy (business hours only)
  command: /opt/deploy.sh
  when:
    - ansible_date_time.hour | int >= 9
    - ansible_date_time.hour | int < 17
    - ansible_date_time.weekday != "Saturday"
    - ansible_date_time.weekday != "Sunday"

# Skip during maintenance window - name: Health check uri: url=http://localhost/health when: ansible_date_time.hour | int != 2 # Skip at 2 AM

Timestamp in Templates

# config.j2
# Generated by Ansible on {{ ansible_date_time.iso8601 }}
# Host: {{ inventory_hostname }}

[app] deploy_time={{ ansible_date_time.epoch }}

ansible_date_time Fields

| Field | Example | |-------|---------| | date | 2026-04-05 | | time | 14:30:45 | | iso8601 | 2026-04-05T14:30:45Z | | iso8601_basic | 20260405T143045000000 | | iso8601_basic_short | 20260405T143045 | | epoch | 1743868245 | | year | 2026 | | month | 04 | | day | 05 | | hour | 14 | | minute | 30 | | second | 45 | | weekday | Sunday | | weekday_number | 0 | | tz | UTC |

FAQ

Date is from controller or remote host?

ansible_date_time comes from the remote host (gathered with setup module). For controller time, use now() or lookup('pipe', 'date').

How do I compare dates?

Convert to epoch for comparison:

when: (now().strftime('%s') | int - file_mtime | int) > 86400  # Older than 1 day

Can I use a specific timezone?

- set_fact:
    est_time: "{{ '%Y-%m-%d %H:%M' | strftime(ansible_date_time.epoch | int - 18000) }}"

Related Articles

argv form of Ansible commandmanaging Windows hosts with Ansible

Category: windows-automation

Browse all Ansible tutorials · AnsiblePilot Home