Ansible全局错误计数变量查询及场景应用需求
Ansible 全局错误统计与类型区分方案
核心做法
用Ansible的set_fact配合block/rescue结构,在任务执行时捕获不同类型错误,更新全局变量GLOB,里面包含总错误数和两种错误类型的统计。
具体操作步骤
1. 初始化全局错误变量
在主playbook开头添加这段代码,完成GLOB变量的初始化:
- name: 初始化全局错误统计变量 set_fact: GLOB: total_errors: 0 error_types: http_50x: 0 code_errors: 0 run_once: true
run_once: true保证多节点执行时,该变量在所有机器上保持一致。
2. 给DoThings.yml添加错误捕获逻辑
用block包裹DoThings的任务,出错时在rescue块里判断错误类型并更新GLOB:
- name: 执行DoThings任务 block: - include_tasks: DoThings.yml rescue: - name: 判断错误类型并更新统计 set_fact: GLOB: >- {% if '50' in (ansible_failed_result.msg | default('')) or '50' in (ansible_failed_result.stderr | default('')) %} {{ GLOB | combine({ 'total_errors': GLOB.total_errors + 1, 'error_types': GLOB.error_types | combine({'http_50x': GLOB.error_types.http_50x + 1}) }) }} {% else %} {{ GLOB | combine({ 'total_errors': GLOB.total_errors + 1, 'error_types': GLOB.error_types | combine({'code_errors': GLOB.error_types.code_errors + 1}) }) }} {% endif %} run_once: true
3. 给Clear.yml添加同样的错误捕获
无论DoThings是否出错,Clear都要执行,同样给它加上错误统计逻辑:
- name: 执行Clear任务(不受前面错误影响) block: - include_tasks: Clear.yml rescue: - name: 判断错误类型并更新统计 set_fact: GLOB: >- {% if '50' in (ansible_failed_result.msg | default('')) or '50' in (ansible_failed_result.stderr | default('')) %} {{ GLOB | combine({ 'total_errors': GLOB.total_errors + 1, 'error_types': GLOB.error_types | combine({'http_50x': GLOB.error_types.http_50x + 1}) }) }} {% else %} {{ GLOB | combine({ 'total_errors': GLOB.total_errors + 1, 'error_types': GLOB.error_types | combine({'code_errors': GLOB.error_types.code_errors + 1}) }) }} {% endif %} run_once: true
4. 在Report.yml中使用统计结果
在Report.yml里直接调用GLOB变量做判断或输出:
- name: 输出错误统计报告 debug: msg: | 总错误数: {{ GLOB.total_errors }} 50x HTTP错误数: {{ GLOB.error_types.http_50x }} 代码类错误数: {{ GLOB.error_types.code_errors }} - name: 提示50x错误需重试 debug: msg: "发现{{ GLOB.error_types.http_50x }}个50x HTTP错误,建议重试相关API调用" when: GLOB.error_types.http_50x > 0 - name: 提示代码类错误需修复 debug: msg: "发现{{ GLOB.error_types.code_errors }}个代码类错误,请检查任务逻辑或参数配置" when: GLOB.error_types.code_errors > 0
额外优化提示
如果API调用用的是uri模块,可以直接提取返回状态码判断,比匹配字符串更准确,示例:
# 在DoThings.yml或Clear.yml中的API调用任务 - name: 调用OpenStack API uri: url: "{{ openstack_api_endpoint }}" method: POST body: "{{ api_request_body }}" register: api_response ignore_errors: true - name: 根据API返回码更新错误统计 set_fact: GLOB: >- {% if api_response.status is defined and api_response.status >= 500 %} {{ GLOB | combine({ 'total_errors': GLOB.total_errors + 1, 'error_types': GLOB.error_types | combine({'http_50x': GLOB.error_types.http_50x + 1}) }) }} {% elif api_response.failed %} {{ GLOB | combine({ 'total_errors': GLOB.total_errors + 1, 'error_types': GLOB.error_types | combine({'code_errors': GLOB.error_types.code_errors + 1}) }) }} {% endif %} run_once: true
内容的提问来源于stack exchange,提问作者FrankieGG
相关产品推荐
相关产品推荐

