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

如何让Ansible不将host_vars中的普通文件识别为配置文件?

Ansible host_vars下非配置文件的识别问题

问题场景

我的Ansible inventory结构如下:

inventory/
  group_vars/
  host_vars/
    /my_host1/
    /my_host2/
      aws/
        config
        credentials
      some.conf

运行playbook时触发如下错误:

ERROR! We were unable to read either as JSON nor YAML, these are the errors we got from each:
JSON: Expecting value: line 1 column 2 (char 1)

Syntax Error while loading YAML.
  did not find expected <document start>

The error appears to be in '/home/user/src/my-ansible/inventory/host_vars/my_host2/aws/config': line 2, column 1, but may
be elsewhere in the file depending on the exact syntax problem.

The offending line appears to be:

[default]
region = eu-central-1
^ here

Ansible会将aws目录下的config文件当作YAML主机配置文件读取,我发现重命名为config.txt后,Ansible会忽略该文件。想知道除了添加后缀外,是否有其他办法让Ansible将这类文件识别为普通文件,而非配置文件?

解决方案

  • 配置Ansible忽略指定文件
    在ansible.cfg的[defaults]段添加ignore_files配置,用正则表达式指定需要忽略的文件名:

    [defaults]
    ignore_files = ^config$|^credentials$
    

    这样Ansible在加载host_vars/group_vars时会自动跳过匹配这些规则的文件,无需修改文件名。

  • 迁移非配置文件到外部目录
    将包含普通文件的aws目录移出host_vars,比如放到项目根目录的files文件夹下,之后在playbook中通过copy模块引用这些文件,从根源避免Ansible误解析。

  • 添加非解析后缀
    给文件加上.txt、.cfg这类Ansible默认不识别为变量配置的后缀。Ansible默认只会解析无后缀、.yml/.yaml/.json后缀的文件作为变量配置,添加其他后缀即可让文件被忽略。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 09:25:26