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 模块打印出当前日期。

详细步骤:

  1. 关闭 gather_facts 为了避免获取远程主机的日期,需要在 Playbook 的 hosts 部分设置 gather_facts: False
  2. 使用 set_fact 模块: set_fact 模块用于在 playbook 中创建或修改变量。在此示例中,我们将 ansible_date_time.date 的值存储到 current_date 变量中。
  3. 使用 ansible_date_time 模块: ansible_date_time 模块提供有关当前日期和时间的详细信息。ansible_date_time.date 返回当前日期的字符串格式。
  4. 使用 debug 模块: debug 模块用于打印变量的值。在此示例中,我们将打印 current_date 变量的值。

总结:

通过上述步骤,您可以在 Ansible Playbook 中轻松获取当前日期并将其存储到变量中,方便在其他任务中使用。

Ansible 获取当前日期到变量 - 详细教程及示例

原文地址: https://www.cveoy.top/t/topic/pS8j 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录