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

Ansible如何在host_vars文件中保留变量格式而非实际值?

解决Ansible blockinfile写入变量文本而非实际值的问题

要让blockinfile模块原样写入{{ usernamevariable }}这类变量文本而不解析为实际值,需要禁用Jinja2的变量解析功能,具体有两种可行方法:

方法一:使用Jinja2 raw标签包裹变量部分

在需要保留的变量表达式前后添加{% raw %}和{% endraw %},告诉Ansible不要解析这部分内容:

- name: Write host_vars file with raw variables
  blockinfile:
    path: "/mypath/host_vars/{{ inventory_hostname | upper }}"
    block: |
      ansible_user: "{% raw %}{{ usernamevariable }}{% endraw %}"
      ansible_ssh_pass: "{% raw %}{{ userpasswordvariable }}{% endraw %}"
      ansible_connection: winrm
      ansible_winrm_server_cert_validation: ignore
      ansible_winrm_transport: ntlm
      ansible_port: 5985
    create: yes  # 若文件不存在则自动创建

方法二:转义变量表达式中的大括号

通过在大括号前添加反斜杠转义,让Jinja2将其视为普通文本:

- name: Write host_vars file with escaped variables
  blockinfile:
    path: "/mypath/host_vars/{{ inventory_hostname | upper }}"
    block: |
      ansible_user: "\{\{ usernamevariable \}\}"
      ansible_ssh_pass: "\{\{ userpasswordvariable \}\}"
      ansible_connection: winrm
      ansible_winrm_server_cert_validation: ignore
      ansible_winrm_transport: ntlm
      ansible_port: 5985
    create: yes

为什么单引号/反引号无效?

单引号仅在YAML中定义字符串字面量,但Jinja2仍会解析字符串内部的{{ ... }}表达式;反引号在Ansible中用于执行系统命令,不具备阻止变量解析的作用,因此这两种方法无法解决问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 16:00:17