Ansible报错:'dict object' has no attribute 'json' 求助排查
Ansible Playbook 报错排查:'dict object' has no attribute 'json'
问题场景
执行以下Ansible Playbook代码时触发错误:
- name: Fetching Blueprint ID from VRA ansible.builtin.uri: url: https://myvrahost/catalog-service/api/consumer/entitledCatalogItemViews?%24filter=name+eq+%27myblueprinttest%27 method: GET validate_certs: no return_content: yes headers: Content-Type: application/json Authorization: Bearer {{ token.json['id'] }} register: bpid - name: Print BP_ID debug: msg: "{{ bpid.json }}"
错误信息
{"msg": "任务包含未定义变量的选项。错误为:'dict object' has no attribute 'json'\n\n错误似乎出现在'/home/user/vra_testing/vm_deploy_test1.yaml'文件的第48行第5列,但也可能因语法问题出现在文件其他位置。\n\n有问题的行似乎是:\n\n\n - name: Print BP_ID\n ^ 此处\n"}
报错明确指向msg: "{{ bpid.json }}"行,以下是具体排查思路和解决方法:
错误原因
- uri请求未成功:当
uri模块发起的请求失败(如HTTP状态码非200、认证失败、服务不可达等),模块不会生成json属性,此时bpid仅包含错误相关字段(如status、msg、elapsed)。 - token变量无效:如果
token.json['id']本身不存在或无效,会直接导致第一个uri请求失败,进而bpid无json属性。
解决方法
1. 先确认uri请求的完整执行结果
在Print BP_ID任务前添加debug任务,打印bpid的全部内容,判断请求是否成功:
- name: Debug full bpid output debug: var: bpid
若输出显示failed: true或status不在200系列,需针对性排查:
- 检查
url的过滤参数编码是否符合VRA API要求(%24filter对应$filter,%27对应单引号) - 验证
token的有效性,提前打印token内容确认:- name: Debug token content debug: var: token - 确认VRA服务是否可达、端口是否开放
2. 给bpid.json添加默认值避免报错
如果需要在请求失败时不中断Playbook执行,可使用default过滤器:
- name: Print BP_ID debug: msg: "{{ bpid.json | default('请求失败,请查看bpid详情') }}"
3. 添加条件判断控制任务执行
通过failed_when和when条件,确保仅在请求成功时才访问bpid.json:
- name: Fetching Blueprint ID from VRA ansible.builtin.uri: url: https://myvrahost/catalog-service/api/consumer/entitledCatalogItemViews?%24filter=name+eq+%27myblueprinttest%27 method: GET validate_certs: no return_content: yes headers: Content-Type: application/json Authorization: Bearer {{ token.json['id'] }} register: bpid failed_when: bpid.status not in [200, 201] - name: Print BP_ID debug: msg: "{{ bpid.json }}" when: bpid.status in [200, 201]
内容的提问来源于stack exchange,提问作者grub.d
相关产品推荐
相关产品推荐

