优化Ansible任务:实现Windows计划任务可配置时间重启并支持空值
解决Windows定时重启任务支持单/双时间配置的简洁方案
最简洁的实现方式是利用Ansible的条件触发器,仅在时间变量非空时生成对应的触发器条目,这样就能自由启用/禁用早上或晚上的重启计划,且不会触发格式错误。
修改后的任务代码
- name: Schedule restart for windows machine community.windows.win_scheduled_task: name: "Scheduled restart machine" description: "This task restarts the machine at configured date && time" actions: - path: shutdown.exe arguments: "/r /f /t 0" triggers: # 仅当早上重启时间非空时添加该触发器 - type: "{{ trigger_type }}" start_boundary: "{{ restart_morning_time }}" when: restart_morning_time | length > 0 # 仅当晚上重启时间非空时添加该触发器 - type: "{{ trigger_type }}" start_boundary: "{{ restart_evening_time }}" when: restart_evening_time | length > 0 username: "SYSTEM" run_level: highest state: present
变量配置示例
想禁用某个时段的重启,直接将对应时间设为空字符串即可:
vars: trigger_type: "daily" # 可选值:'daily', 'weekly', 'monthly' restart_morning_time: "2024-08-10T07:00:00" # 启用早上重启 restart_evening_time: "" # 禁用晚上重启
原理说明
通过when条件判断,Ansible会自动跳过空值对应的触发器条目,确保提交给win_scheduled_task模块的start_boundary始终是符合要求的时间格式,不会出现多个时间拼接导致的格式错误。
内容的提问来源于stack exchange,提问作者Cyanic Wolf
相关产品推荐
相关产品推荐

