Ansible如何本地获取目录最新文件用于include_vars?
问题描述
需要为变量设置默认值,该变量对应../roles/somerole/files/目录下最后添加的文件,但直接使用find模块会在远程主机而非本地查找路径,导致报错。
原代码示例:
- hosts: all become: yes pre_tasks: - name: Get last added file find: paths: "../roles/somerole/files/" register: found_files - name: Include vars from latest file in above folder include_vars: "{{ found_files.files | sort(attribute='mtime',reverse=true) | first }}"
执行输出:
[WARNING]: Skipped '../roles/somerole/files/' path due to this access issue: '../roles/somerole/files/' is not a directory ok: [1.1.1.1] => { "ansible_facts": { "discovered_interpreter_python": "/usr/bin/python3" }, "changed": false, "examined": 0, "files": [], "invocation": { "module_args": { "age": null, "age_stamp": "mtime", "contains": null, "depth": null, "excludes": null, "file_type": "file", "follow": false, "get_checksum": false, "hidden": false, "paths": [ "../roles/somerole/files/" ], "patterns": [ "*" ], "read_whole_file": false, "recurse": false, "size": null, "use_regex": false } }, "matched": 0, "msg": "Not all paths examined, check warnings for details", }
解决方案
要在本地执行文件查找操作,有两种常用实现方式:
方式一:使用delegate_to: localhost
给find模块添加delegate_to: localhost参数,强制任务在本地执行,同时搭配run_once: true避免重复执行:
- hosts: all become: yes pre_tasks: - name: Get last added file locally find: paths: "../roles/somerole/files/" register: found_files delegate_to: localhost run_once: true - name: Include vars from latest local file include_vars: file: "{{ found_files.files | sort(attribute='mtime', reverse=true) | first.path }}" delegate_to: localhost run_once: true
方式二:使用local_action
通过local_action直接指定任务在本地执行,语法更直观:
- hosts: all become: yes pre_tasks: - name: Get last added file locally local_action: module: find paths: "../roles/somerole/files/" register: found_files run_once: true - name: Include vars from latest local file local_action: module: include_vars file: "{{ found_files.files | sort(attribute='mtime', reverse=true) | first.path }}" run_once: true
关键注意点
- 确认
../roles/somerole/files/路径在本地存在,且Ansible执行用户有访问权限 run_once: true可避免在所有远程主机重复执行本地任务,提升执行效率- 通过
.path获取文件完整路径,确保include_vars能正确读取本地文件
内容的提问来源于stack exchange,提问作者Iryna Nazaruk
相关产品推荐
相关产品推荐

