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

Ansible:如何从Action插件中执行Lookup插件

在Ansible Action插件中调用Lookup插件的实现方法

完全可以在Action插件内部调用Lookup插件,不需要依赖self._execute_module(),具体实现步骤如下:

1. 获取Lookup插件实例

通过ActionBase类提供的_lookup_loader属性加载目标Lookup插件,直接复用Action插件自身的loader和templar属性作为参数:

lookup_plugin = self._lookup_loader.get(
    "目标lookup插件名称",
    loader=self._loader,
    templar=self._templar
)

2. 调用Lookup插件的run方法

拿到插件实例后,调用其run方法执行逻辑,核心参数说明:

  • 位置参数:传入Lookup插件需要的输入参数(比如file lookup的文件路径)
  • variables:传入当前任务的变量集合,直接使用task_vars或self._task_vars
  • 可选参数:比如wantlist=True,强制返回列表结果,避免单个值被自动解包

示例代码(调用内置file lookup读取文件内容)

from ansible.plugins.action import ActionBase

class ActionModule(ActionBase):
    def run(self, tmp=None, task_vars=None):
        super().run(tmp, task_vars)
        
        # 加载file lookup插件
        file_lookup = self._lookup_loader.get(
            "file",
            loader=self._loader,
            templar=self._templar
        )
        
        # 执行lookup逻辑,读取指定文件
        file_result = file_lookup.run(
            ["/etc/hosts"],
            variables=task_vars,
            wantlist=True
        )
        
        # 返回结果给Ansible任务
        return {
            "changed": False,
            "hosts_content": file_result[0]
        }

注意事项

  • 确保目标Lookup插件已存在:内置插件直接使用名称,自定义插件需放在Ansible能识别的路径下
  • 不同Lookup插件的run方法参数可能略有差异,可参考对应插件的源码确认参数要求
  • 若需要处理多值结果,务必设置wantlist=True,否则当结果只有一个值时会被自动转为字符串而非列表

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 02:15:34