Introduction
In IT infrastructure management, automation is a key component that empowers administrators to streamline repetitive tasks and ensure consistent operations. Ansible, a popular open-source automation tool, offers extensive capabilities for orchestrating tasks across a wide range of systems. One intriguing aspect of Ansible is its ability to execute tasks at specific times, enabling administrators to schedule actions with precision. This article will explore a practical example of how Ansible can execute tasks at a predetermined time, specifically at 10:55.
The Power of Scheduled Execution
Imagine a scenario where a system administrator needs to perform a task on a fleet of servers every day at exactly 10:55. This task might involve updating configurations, performing backups, or any other action necessary to maintain system health and security. Manually executing such tasks can be time-consuming, error-prone, and disruptive, especially in a large-scale environment.
Ansible addresses this challenge by allowing administrators to define and schedule tasks for execution at specific times. This reduces the required manual effort and ensures consistency and accuracy in task execution.
Links
- https://docs.ansible.com/ansible/latest/collections/ansible/builtin/wait_for_module.html
- https://docs.ansible.com/ansible/latest/playbook_guide/playbooks_vars_facts.html
Understanding the Playbook
To Playbooknstrate scheduled execution with Ansible, we will walk through an Ansible playbook that accomplishes the following:
1. Calculates the time remaining until 10:55.
2. Displays the current datetime, target datetime (10:55), and time remaining in seconds.
3. Pauses the playbook execution until the specified time (10:55) is reached.
4. Displays a message indicating the completion of the wait period.
Here’s the Ansible playbook for achieving this:
``yaml
---
- name: Execute at 10:55
hosts: all
vars:
var_wait_time: "10:55:00"
var_wait_datetime: "{{ ansible_date_time.year }}-{{ ansible_date_time.month }}-{{ ansible_date_time.day }} {{ var_wait_time }}"
var_current_datetime: "{{ ansible_date_time.date }} {{ ansible_date_time.time }}"
tasks:
- name: Calculate the seconds to pause
ansible.builtin.set_fact:
var_wait_seconds: "{{ ((var_wait_datetime | to_datetime) - (var_current_datetime | to_datetime)).total_seconds() }}"
delegate_to: localhost
- name: Show the datetimes and seconds to pause
ansible.builtin.debug:
msg: "{{ var_wait_datetime }} :: {{ var_current_datetime }} :: {{ var_wait_seconds }}"
delegate_to: localhost
- name: Pause for {{ var_wait_seconds }} seconds
ansible.builtin.wait_for:
timeout: "{{ var_wait_seconds | int }}"
when: var_wait_seconds | int > 0
- name: Display message
ansible.builtin.debug:
msg: "Waited {{ var_wait_seconds }} seconds"
``
This playbook showcases using Ansible’s datetime manipulation functions,