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: Format Dates, Time & Timestamps in Playbooks

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

How to use ansible_date_time fact in playbooks. Access date, time, epoch, ISO8601 timestamps. Format dates with strftime filter, create time-based filenames.

ansible_date_time: Format Dates, Time & Timestamps in Playbooks

How to Use Date, Time, and Timestamp in Ansible Playbook

Welcome to another episode of Ansible Pilot! I'm Luca Berton, and today we're diving into the fascinating world of handling date, time, and timestamps in Ansible Playbooks. We'll explore the ansible_date_time variable, conduct a live Playbook, and provide you with simple Ansible code to get started.

See also: ansible_date_time: Use Date, Time & Timestamps in Ansible Playbooks

The ansible_date_time Variable

Ansible simplifies working with date and time information through the ansible_date_time variable. This built-in variable comes packed with a wealth of information, neatly organized into key-value pairs. Let's take a closer look at some of the key values it provides:

"ansible_date_time": {
    "date": "2022-05-18",
    "day": "18",
    "epoch": "1652887408",
    "hour": "15",
    "iso8601": "2022-05-18T15:23:28Z",
    "minute": "23",
    "month": "05",
    "second": "28",
    "time": "15:23:28",
    "tz": "UTC",
    "weekday": "Wednesday",
    "weekday_number": "3",
    "year": "2022"
}

These values cover everything from the current date, time, and timezone to more detailed information like the day of the week, month, and year. This data can be immensely useful in various scenarios within your Ansible Playbook.

One important note: to leverage the ansible_date_time variable, ensure that Ansible Facts are enabled in your playbook by including gather_facts: true.

Playbook

Are you ready for a hands-on experience? Let's jump into a quick live Playbook where we'll showcase how to display the full ansible_date_time and the ISO8601 format.

Ansible Playbook Code

---
- name: date and time Playbook
  hosts: all
  gather_facts: true
  tasks:
    - name: date and time
      ansible.builtin.debug:
        var: ansible_date_time
    - name: ISO8601
      ansible.builtin.debug:
        var: ansible_date_time.iso8601

Execution

Run the following command to execute the playbook:

$ ansible-playbook -i inventory datetime_fact.yml

The output will provide detailed information about the current date and time, as well as the ISO8601 format.

See also: Ansible Scheduled Tasks: Cron Jobs & at Module for Timed Execution

Conclusion

Congratulations! You've just learned how to harness the power of date, time, and timestamp variables in your Ansible Playbooks. The ansible_date_time variable opens up a world of possibilities for managing time-related data effortlessly. Feel free to explore and integrate this knowledge into your automation workflows. Happy automating!

ansible_date_time Fact

Ansible provides date/time through the ansible_date_time fact (gathered automatically):

- name: Show all date/time values
  debug:
    var: ansible_date_time

Available fields:

| Field | Example | Description | |-------|---------|-------------| | date | 2025-01-15 | Date (YYYY-MM-DD) | | time | 14:30:25 | Time (HH:MM:SS) | | iso8601 | 2025-01-15T14:30:25Z | ISO 8601 format | | epoch | 1736953825 | Unix timestamp | | weekday | Wednesday | Day name | | weekday_number | 3 | Day number (0=Sunday) | | month | 01 | Month number | | year | 2025 | Year | | hour | 14 | Hour | | minute | 30 | Minute | | tz | UTC | Timezone |

See also: Securely Automate Sudo Passwords in Ansible Playbooks

Common Use Cases

Timestamped backup file

- name: Backup database with timestamp
  ansible.builtin.command: >
    pg_dump mydb -f /backup/mydb_{{ ansible_date_time.date }}_{{ ansible_date_time.time | replace(':', '') }}.sql
  become: true
  # Creates: /backup/mydb_2025-01-15_143025.sql

Timestamped deployment directory

- name: Create release directory
  vars:
    release_dir: "/opt/releases/{{ ansible_date_time.epoch }}"
  ansible.builtin.file:
    path: "{{ release_dir }}"
    state: directory
    mode: '0755'

Log deployment time

- name: Record deployment timestamp
  ansible.builtin.copy:
    content: |
      Deployed: {{ ansible_date_time.iso8601 }}
      Version: {{ app_version }}
      Host: {{ inventory_hostname }}
    dest: /opt/myapp/DEPLOY_INFO
    mode: '0644'

Custom Date Formatting with strftime

- name: Custom date formats
  debug:
    msg:
      - "US format: {{ '%m/%d/%Y' | strftime }}"
      - "EU format: {{ '%d.%m.%Y' | strftime }}"
      - "Compact: {{ '%Y%m%d_%H%M%S' | strftime }}"
      - "Human: {{ '%B %d, %Y at %I:%M %p' | strftime }}"

strftime from epoch

- name: Convert epoch to readable
  vars:
    file_epoch: 1736953825
  debug:
    msg: "File date: {{ '%Y-%m-%d %H:%M:%S' | strftime(file_epoch) }}"

Date Arithmetic

Calculate date offsets

- name: Get date 7 days ago
  vars:
    seven_days_ago: "{{ '%Y-%m-%d' | strftime(ansible_date_time.epoch | int - 604800) }}"
  debug:
    msg: "Cleanup files older than {{ seven_days_ago }}"

Find files older than X days

- name: Find files older than 30 days
  ansible.builtin.find:
    paths: /var/log/myapp
    age: 30d
    recurse: true
  register: old_files

FAQ

Why is the timestamp the same for all tasks?

ansible_date_time is gathered once at the start of the play. For a fresh timestamp per task, use:

- name: Get current time
  ansible.builtin.command: date +%s
  register: current_time
  changed_when: false

How do I use a different timezone?

- name: Show time in specific timezone
  ansible.builtin.command: "TZ='America/New_York' date '+%Y-%m-%d %H:%M:%S'"
  register: ny_time
  changed_when: false

How do I compare dates?

Convert to epoch for numeric comparison:

- name: Check if certificate expires within 30 days
  ansible.builtin.shell: "date -d '{{ cert_expiry }}' +%s"
  register: expiry_epoch

- name: Alert if expiring soon debug: msg: "Certificate expires in less than 30 days!" when: (expiry_epoch.stdout | int) - (ansible_date_time.epoch | int) < 2592000

Related Articles

building an Ansible inventory

Category: database-automation

Watch the video: ansible_date_time: Format Dates, Time & Timestamps in Playbooks — Video Tutorial

Browse all Ansible tutorials · AnsiblePilot Home