You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将ansible_uptime_seconds转为天、HH:MM:SS并输出到os.csv

解决Ansible中Unix秒数转“天, HH:MM:SS”格式的问题

你可以通过Jinja2算术运算和字符串格式化,直接在Playbook中将ansible_uptime_seconds转换为目标格式。核心逻辑是拆分总秒数为天、时、分、秒,再拼接成指定字符串。

修改后的完整Playbook

---
- name: playbook query system and output to file
  hosts: OEL7_systems 
  vars:
    output_file: os.csv
  tasks:
     - block:
         # For permisison setup.
         - name: get current user
           command: whoami
           register: whoami
           run_once: yes
 
         - name: clean_file
           copy:
             dest: "{{ output_file }}"
             content: 'hostname,distribution,version,release,uptime'
             owner: "{{ whoami.stdout }}"
           run_once: yes
 
         - name: fill os information
           lineinfile:
             path: "{{ output_file }}"
             line: >-
               {{ ansible_hostname }},
               {{ ansible_distribution }},
               {{ ansible_distribution_version }},
               {{ ansible_distribution_release }},
               {{ ansible_uptime_seconds // 86400 }}天, {{ '%02d:%02d:%02d' % ((ansible_uptime_seconds % 86400) // 3600, (ansible_uptime_seconds % 3600) // 60, ansible_uptime_seconds % 60) }}
           # Tries to prevent concurrent writes.
           throttle: 1
       delegate_to: localhost

关键转换逻辑说明

  • 计算天数:ansible_uptime_seconds // 86400,通过整数除法得到总天数(1天=86400秒)
  • 格式化时分秒:
    • 先取整天之外的剩余秒数:ansible_uptime_seconds % 86400
    • 小时:(剩余秒数) // 3600,用%02d确保显示为两位数字(如1小时显示为01)
    • 分钟:(剩余秒数 % 3600) // 60,同样格式化为两位数字
    • 秒:剩余秒数 % 60,格式化为两位数字
  • 最终拼接成X天, HH:MM:SS的格式

补充说明

  • 使用>-符号让line字段内容更易读,避免换行导致的CSV格式问题
  • %02d是Python风格的格式化语法,保证时分秒始终以两位数字呈现,符合统一格式要求

内容的提问来源于stack exchange,提问作者JDFreez

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 16:15:40