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

如何在MacOS系统下通过Ansible获取文件/目录的真实创建时间

MacOS环境Ansible获取目录真实创建时间的实现方案

问题原因

MacOS下的ctime对应文件元数据最后变更时间,而非文件/目录创建时间,Ansible内置stat、find模块默认未返回MacOS专属的创建时间字段,因此直接使用item.ctime会得到错误结果。

实现方案

我们可以调用MacOS原生的mdls命令(比ls -ldU输出更规范,更易解析)来获取目录的创建时间,具体playbook修改如下:

- name: Get dirs and real create dates on MacOS
  hosts: localhost
  gather_facts: true

  tasks:
    - name: Get target directory list
      find:
        paths:
          - "/Users/me/Work/Customers"
        file_type: directory
        recurse: false
      register: projectdirs

    - name: Get create time for each directory
      command: "mdls -name kMDItemFSCreationDate -raw {{ item.path | quote }}"
      register: dir_create_times
      loop: "{{ projectdirs.files }}"
      loop_control:
        label: "{{ item.path }}"
      changed_when: false # 标记为无变更,避免playbook执行结果显示changed

    - name: Output directory name and create date
      debug:
        msg: "{{ shortname }} {{ create_date }}"
      loop: "{{ dir_create_times.results }}"
      loop_control:
        label: "{{ item.item.path }}"
      vars:
        shortname: "{{ item.item.path | basename }}"
        # 把mdls返回的UTC时间转成指定格式,可根据需求调整时区和输出格式
        create_date: "{{ item.stdout | to_datetime('%Y-%m-%d %H:%M:%S %z') | strftime('%Y-%m-%d') }}"

如果你偏好使用提到的ls -ldU命令,可将获取创建时间的任务替换为以下版本:

- name: Get create time for each directory via ls command
  command: "ls -ldU %T@ {{ item.path | quote }}"
  register: dir_create_times
  loop: "{{ projectdirs.files }}"
  loop_control:
    label: "{{ item.path }}"
  changed_when: false

对应时间解析的变量修改为:

create_date: "{{ '%Y-%m-%d' | strftime(item.stdout.split(' ')[0] | float) }}"

注意事项

  • 执行playbook的用户需要持有目标目录的读取权限,否则无法正常获取元数据
  • 该方案仅适配MacOS平台,如需跨平台使用可在对应任务中添加when: ansible_os_family == 'Darwin'进行系统判断

内容的提问来源于stack exchange,提问作者Krist van Besien

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 21:36:02