Ansible:使用include_vars模块无法加载指定YAML文件
问题:Ansible include_vars搭配files_matching未加载目标YAML文件
问题场景
使用Ansible的include_vars模块并通过files_matching选项加载指定YAML文件时,执行剧本无报错,但目标文件未被成功加载,定义的变量为空字典。
剧本代码
--- - hosts: localhost gather_facts: no vars: work_folder: /home/ubuntu/vars tasks: - name: Load yaml file include_vars: dir: "/home/ubuntu/vars" files_matching: "^(.*)-hive-proxy_values.yaml" name: hive_proxy_values - debug: var: "{{ hive_proxy_values}}"
执行输出
TASK [Load yaml file] ************************************************************************************************************************* task path: /home/ubuntu/hive.yaml:7 ok: [localhost] => { "ansible_facts": { "hive_proxy_values": {} }, "ansible_included_var_files": [], "changed": false } ok: [localhost] => { "<class 'dict'>": "VARIABLE IS NOT DEFINED!: " }
目标文件状态
目标文件存在于指定目录:
ls -l /home/ubuntu/vars -rw-rw-r-- 1 ubuntu ubuntu 145 Aug 15 05:20 mtn-wbel-AAA-OAM-12x-hive-proxy_values.yaml
问题原因及修复方案
1. files_matching默认不支持正则表达式
Ansible的include_vars模块中,files_matching参数默认使用shell风格通配符(fnmatch),而非正则表达式。若要使用正则匹配,需显式添加use_regex: yes参数。
修复后的加载任务:
- name: Load yaml file include_vars: dir: "/home/ubuntu/vars" files_matching: "^(.*)-hive-proxy_values.yaml" use_regex: yes name: hive_proxy_values
若不想使用正则,也可改用shell通配符简化匹配规则:
files_matching: "*-hive-proxy_values.yaml"
2. debug模块的var参数使用错误
debug模块的var参数直接接受变量名,不需要包裹双大括号{{ }},否则会导致变量解析异常。
修复后的debug任务:
- debug: var: hive_proxy_values
完整修复后的剧本
--- - hosts: localhost gather_facts: no vars: work_folder: /home/ubuntu/vars tasks: - name: Load yaml file include_vars: dir: "/home/ubuntu/vars" files_matching: "^(.*)-hive-proxy_values.yaml" use_regex: yes name: hive_proxy_values - debug: var: hive_proxy_values
内容的提问来源于stack exchange,提问作者Eva
相关产品推荐
相关产品推荐

