本地运行Groovy脚本解析Ansible Inventory报错求助
解决本地Groovy执行readFile报错并提取Ansible Inventory主机名
报错原因
readFile(file: filePath)是Jenkins Pipeline的内置方法,标准Groovy运行环境不支持这种带命名参数的调用方式,所以本地执行时会抛出groovy.lang.MissingMethodException。
修复方案
用Groovy原生的文件读取方式替换Jenkins专属的readFile,同时优化主机名提取逻辑(原逻辑会把整行内容加入列表,实际需要提取空格前的主机名称):
修改后的完整脚本
def getHostList(def appName, def filePath) { def hosts = [] // 替换Jenkins readFile为Groovy原生文件读取 def content = new File(filePath).text def startCollect = false for(def line : content.split('\n')) { def trimmedLine = line.trim() // 精确匹配目标分组 if(trimmedLine == "[$appName]"){ startCollect = true continue } if(startCollect) { // 遇到新分组或空行时停止收集 if(trimmedLine.isEmpty() || trimmedLine.startsWith('[')){ break } // 提取空格前的主机名(处理"Client1 ansible_host=xxx"格式) def hostname = trimmedLine.split(/\s+/)[0] hosts.add(hostname) } } return hosts } // 调用示例:对应Inventory中的[Clients]分组 def hosts = getHostList("Clients", "/absolute/path/hosts2") // 打印结果验证 println "提取的主机列表:${hosts}"
关键改动说明
- 替换文件读取方式:用
new File(filePath).text直接读取文件内容,这是标准Groovy支持的跨环境写法。 - 优化分组匹配逻辑:精确匹配
[$appName]格式的分组行,避免部分匹配导致的错误触发。 - 精准提取主机名:通过
split(/\s+/)[0]提取每行第一个空格前的内容,确保只获取主机名称,而非整行配置。 - 增强终止条件:遇到空行或新分组时立即停止收集,避免读取到分组变量段(如
[Clients:vars]下的内容)。
测试验证
针对你提供的Inventory文件,调用getHostList("Clients", "/absolute/path/hosts2")会返回:
[Client1, Client2, Client3]
内容的提问来源于stack exchange,提问作者twet
相关产品推荐
相关产品推荐

