Ansible 的 lookup 插件是一种强大的工具,可以用来从外部源加载变量或模板。file 查找插件(ansible.builtin.file)是 Ansible 核心功能的一部分,用于读取本地文件的内容,并将其内容赋值给变量,以便在 Playbook 中使用。

file 查找插件的主要参数

  • _terms:字符串,指定要读取的文件路径。这是必需参数。
  • 返回值:_raw,文件内容的列表形式。

示例:将文件内容读取到变量中

以下是一个示例 Playbook,展示如何使用 file 查找插件读取文件内容,并将其赋值给变量。

---
- name: read file on host
  hosts: all
  vars:
    contents: "{{ lookup('file', 'example.txt') }}"
  tasks:
    - name: print file
      ansible.builtin.debug:
        msg: "the content of file is {{ contents }}"

执行步骤

  1. 准备文件 确保 example.txt 文件存在于 Ansible 控制节点的当前工作目录中,或者指定正确的文件路径。

  2. 运行 Playbook 使用以下命令运行 Playbook:

    bash ansible-playbook -i inventory variables/read-file.yml

执行结果

如果任务成功执行,输出将类似于以下内容:

PLAY [read file on host] ***************************************************

TASK [Gathering Facts] *****************************************************
ok: [demo.example.com]

TASK [print file] *********************************************************
ok: [demo.example.com] => {
    "msg": "the content of file is example contents"
}

PLAY RECAP *****************************************************************
demo.example.com           : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

幂等性测试

由于 lookup 插件读取文件内容并赋值给变量,这是一个幂等操作。多次运行 Playbook 不会改变结果:

PLAY [read file on host] ***************************************************

TASK [Gathering Facts] *****************************************************
ok: [demo.example.com]

TASK [print file] *********************************************************
ok: [demo.example.com] => {
    "msg": "the content of file is example contents"
}

PLAY RECAP *****************************************************************
demo.example.com           : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

注意事项

  1. 文件路径:lookup 插件在 Ansible 控制节点上读取文件,而不是在目标主机上。确保文件路径正确。
  2. 文件内容:文件如果内容较大,可能会导致变量内容过长。建议在必要时进行内容处理。
  3. 安全性和权限:确保文件内容不会暴露敏感信息,尤其是在共享或记录输出时。
  4. 错误处理:如果文件不存在或路径错误,lookup 插件会报错。可以通过条件语句或错误处理机制来避免这些问题。

总结

file 查找插件是一个非常实用的工具,用于在 Ansible Playbook 中读取本地文件的内容,并将其赋值给变量。通过灵活使用 lookup 插件,你可以轻松地将文件内容集成到你的自动化任务中。