Ansible 获取当前日期到变量 - 详细教程及示例
Ansible 获取当前日期到变量
在 Ansible 中获取当前日期并将其存储到变量中,可以使用 set_fact 模块结合 ansible_date_time 模块。以下是一个示例 Playbook:
- name: Get current date
hosts: localhost
gather_facts: False
tasks:
- name: Get current date
set_fact:
current_date: '{{ ansible_date_time.date }}'
- name: Print current date
debug:
var: current_date
在这个示例中,首先关闭了 gather_facts 来避免获取远程主机的日期。然后使用 set_fact 模块将 ansible_date_time.date 的值存储到名为 current_date 的变量中。最后使用 debug 模块打印出当前日期。
详细步骤:
- 关闭
gather_facts: 为了避免获取远程主机的日期,需要在 Playbook 的hosts部分设置gather_facts: False。 - 使用
set_fact模块:set_fact模块用于在 playbook 中创建或修改变量。在此示例中,我们将ansible_date_time.date的值存储到current_date变量中。 - 使用
ansible_date_time模块:ansible_date_time模块提供有关当前日期和时间的详细信息。ansible_date_time.date返回当前日期的字符串格式。 - 使用
debug模块:debug模块用于打印变量的值。在此示例中,我们将打印current_date变量的值。
总结:
通过上述步骤,您可以在 Ansible Playbook 中轻松获取当前日期并将其存储到变量中,方便在其他任务中使用。
原文地址: https://www.cveoy.top/t/topic/pS8j 著作权归作者所有。请勿转载和采集!