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

Ansible 2.9.6中uri模块status_code是否支持范围值(如200-500)

Ansible 2.9.6 uri模块status_code范围写法的支持情况

在Ansible 2.9.6版本中,uri模块的status_code参数并不支持[200:500]这种简洁的范围简写语法。这个参数在该版本里仅接受具体的状态码数值(单个或列表形式),就像你之前使用的[200,201,400,401,403,409,500]这种写法。

不过要实现"允许200到500之间所有状态码"的需求,有两种实用的替代方案:

方案1:用Jinja2的range函数生成状态码列表

你可以借助Jinja2的range函数自动生成200到500的完整状态码列表(注意range是左闭右开区间,所以要写range(200, 501)才能包含500)。修改后的playbook代码如下:

---
- hosts: localhost
  tasks:
    - name: Create a new bitbucket repository
      uri:
        user: "{{username}}"
        password: "{{password}}"
        method: POST
        body_format: json
        body: "{{ lookup('file','create-repo.json')}}"
        return_content: yes
        # 生成200-500的所有状态码列表
        status_code: "{{ range(200, 501) | list }}"
        force_basic_auth: yes
        validate_certs: no
        url: "{{url}}"
      register: bitbucketResponse
    - name: show bitbucket response
      debug:
        msg: "{{bitbucketResponse}}"
...

如果你的需求是允许多个离散范围(比如仅2xx、4xx、5xx),还可以组合多个range结果:

status_code: "{{ range(200,300) | list + range(400,600) | list }}"

这样就能覆盖所有200-299、400-599的状态码。

方案2:结合failed_when自定义失败条件

如果你不想罗列所有状态码,也可以保留默认的status_code(默认是200),然后通过failed_when来判断返回状态是否在目标范围内,只有不在范围内时才标记任务失败:

---
- hosts: localhost
  tasks:
    - name: Create a new bitbucket repository
      uri:
        user: "{{username}}"
        password: "{{password}}"
        method: POST
        body_format: json
        body: "{{ lookup('file','create-repo.json')}}"
        return_content: yes
        force_basic_auth: yes
        validate_certs: no
        url: "{{url}}"
      register: bitbucketResponse
      # 仅当状态码不在200-500之间时才标记失败
      failed_when: bitbucketResponse.status not in range(200, 501)
    - name: show bitbucket response
      debug:
        msg: "{{bitbucketResponse}}"
...

这种方式更灵活,尤其适合需要对状态码做复杂判断的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.07 00:37:44