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

Ansible整数类型变量失效但直接写入数字正常问题排查

问题解决方案

核心错误原因

  • body_format: json与手动指定的Content-Type: multipart/form-data头冲突:当uri模块指定body_format: json时,Ansible会自动将body字段序列化为JSON格式,且自动添加Content-Type: application/json请求头,手动指定不匹配的Content-Type会导致API无法正常解析请求体。
  • 变量类型转换错误:Jinja2模板插值默认会将值转换为字符串类型,你将GroupID的值用双引号包裹后,原本为数字类型的GroupID被转为字符串,与Portainer API要求的int类型不匹配,所以触发类型转换报错。
  • 修改body_format: form-multipart后报错的原因:该Portainer接口仅支持JSON格式的请求体,接收form表单格式时会用JSON解析器解析表单内容,碰到表单边界的-字符直接解析失败。
修正后的配置
ansible.builtin.uri:
  body_format: json
  headers:
    accept: application/json
    Authorization: "Bearer {{ portainer_auth['json']['jwt'] }}"
  body:
    Name: "{{ item['Name'] }}"
    # 若EndpointCreationType为数字类型,也不要套双引号,加int过滤器强制转数字
    EndpointCreationType: {{ item['EndpointCreationType'] | int }}
    URL: "{{ item['URL'] | default(omit, true) | string }}"
    PublicURL: "{{ item['PublicURL'] | default(omit, true) }}"
    # 不要加双引号,用int过滤器强制转换为数字类型
    GroupID: {{ item['GroupID'] | int }}

如果担心变量未定义的问题,可以给int过滤器加默认值,比如{{ item['GroupID'] | default(1, true) | int }},可根据自身业务需求调整默认值。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 09:24:01