Homebrew安装的Ansible自带community.general模块,但Ansible Lint无法识别该模块
嘿,我太懂这个坑了!很多用Homebrew在macOS上装Ansible的朋友都踩过——就像你遇到的这样:
你在macOS Sonoma 14.4.1上用Homebrew装了Ansible,playbook里用了community.general.locale_gen模块,实际运行完全没问题,但用ansible-lint检查时却弹出致命错误:
WARNING Listing 1 violation(s) that are fatal
syntax-check[unknown-module]: couldn't resolve module/action 'community.general.locale_gen'. This often indicates a misspelling, missing collection, or incorrect module path..yml:16:3
而且你已经通过ansible-galaxy collection list | grep community.general确认了community.general 8.6.0版本确实存在,playbook跑起来毫无障碍,就是ansible-lint“睁眼瞎”找不到它。
这问题本质上是Homebrew打包Ansible和Ansible Lint时,两者的环境路径没对齐——Ansible能找到collection的安装位置,但ansible-lint没读到同一路径配置。给你几个亲测有效的解决办法:
- 办法一:给ansible-lint指定Ansible的配置文件
先通过ansible --version查看Ansible默认使用的配置文件路径,然后在运行ansible-lint时加上--ansible-config参数指定这个文件,比如:
ansible-lint --ansible-config /path/to/your/ansible.cfg <redacted>.yml
这样ansible-lint就能和Ansible共用一套配置,自然能定位到collection了。
- 办法二:手动设置环境变量指定collection路径
先通过ansible-galaxy collection list community.general找到该模块的实际安装目录(就是输出开头# /opt/...那行的路径),然后把这个目录的父级collections目录设为环境变量,再运行ansible-lint:
export ANSIBLE_COLLECTIONS_PATH=/opt/homebrew/Cellar/ansible/[你的Ansible版本号]/libexec/lib/python3.11/site-packages/ansible_collections ansible-lint <redacted>.yml
要是嫌每次都输麻烦,把这个环境变量加到你的shell配置文件(比如/.zshrc或/.bashrc)里就行。
- 办法三:用Ansible自带的pip重装ansible-lint
有时候Homebrew装的ansible-lint和自带的Ansible版本存在环境兼容性问题,你可以先卸载Homebrew版的ansible-lint,再用Ansible自带的pip重新安装:
brew uninstall ansible-lint /opt/homebrew/bin/ansible-pip install ansible-lint
这样装出来的ansible-lint和Homebrew的Ansible在同一个Python环境下,就能自动识别到自带的community.general模块了。
备注:内容来源于stack exchange,提问作者Dave Dribin

