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

如何阻止Ansible将变量中的双引号替换为单引号?

Ansible变量双引号被自动替换为单引号的解决办法

问题重现

直接在任务中编写字面量字符串时,双引号可以正常保留:

- name: Add test monitor
  lucasheld.uptime_kuma.monitor:
    api_url: "https://test.example.com"
    api_token: "{{ token }}"
    type: keyword
    name: testing
    url: http://10.11.10.10:9005/v1/dns/status
    keyword: |-
      {"test":"this works"}
    state: present

对应输出:

{"test":"this works"}

但将字符串替换为变量引用后,双引号会被自动替换为单引号,还会插入不必要的空格:

- name: Add test monitor
  lucasheld.uptime_kuma.monitor:
    api_url: "https://test.example.com"
    api_token: "{{ token }}"
    type: keyword
    name: testing
    url: http://IPADDRESS/v1/dns/status
    keyword: |-
      {{ keyword }}
    state: present
  vars:
    keyword: |-
      {"test":"does not work"}

对应输出:

{'test': 'does not work'}

可行解决办法

方法1:用raw过滤器保留原始字符串

在引用变量时添加raw过滤器,阻止Ansible对字符串进行转义或格式转换,完全保留变量的原始内容:

- name: Add test monitor
  lucasheld.uptime_kuma.monitor:
    api_url: "https://test.example.com"
    api_token: "{{ token }}"
    type: keyword
    name: testing
    url: http://IPADDRESS/v1/dns/status
    keyword: |-
      {{ keyword | raw }}
    state: present
  vars:
    keyword: |-
      {"test":"does not work"}

方法2:用!unsafe标签标记变量

在定义变量时使用!unsafe标签,明确告知Ansible这是不需要处理的原始字符串,避免自动替换引号:

- name: Add test monitor
  lucasheld.uptime_kuma.monitor:
    api_url: "https://test.example.com"
    api_token: "{{ token }}"
    type: keyword
    name: testing
    url: http://IPADDRESS/v1/dns/status
    keyword: |-
      {{ keyword }}
    state: present
  vars:
    keyword: !unsafe '{"test":"does not work"}'

方法3:使用quote过滤器(按需选择)

如果需要确保字符串的引号格式严格保留,可使用quote过滤器,注意此方法会给整个字符串额外包裹一层双引号,适合下游应用能兼容外层引号的场景:

- name: Add test monitor
  lucasheld.uptime_kuma.monitor:
    api_url: "https://test.example.com"
    api_token: "{{ token }}"
    type: keyword
    name: testing
    url: http://IPADDRESS/v1/dns/status
    keyword: "{{ keyword | quote }}"
    state: present
  vars:
    keyword: '{"test":"does not work"}'

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 04:11:09