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

如何验证Ansible Playbook输出中的指定变更及组状态条件?

SonarQube Onboarding Ansible Playbook 验证方案

针对你提出的三个验证点,推荐三种不同场景下的最佳验证方式:

一、手动快速验证(适合临时检查)

直接查看Playbook输出即可完成验证:

  • 验证整体changed计数:找到末尾的PLAY RECAP,查看changed数值,只要大于0就满足要求(当前输出中changed=1,符合条件);
  • 验证指定任务的changed状态:定位到[TASK [Create tenants permission structure]]的输出块,查看返回的JSON中changed字段是否为true(当前输出中该字段为true,符合条件);
  • 验证test_team_b的item状态:找到[TASK [sonarqube-onboard : Create Sonarqube Groups]]任务下的所有item,筛选出name为test_team_b的条目,检查每个条目的status字段是否为present(当前输出中唯一的test_team_b条目status为present,符合条件)。

二、脚本自动化验证(适合批量/定期校验)

用Python脚本解析Playbook输出日志(假设输出保存为ansible_output.log),自动完成三个验证点的检查,示例代码如下:

import re
import json

def validate_ansible_log(log_path):
    with open(log_path, 'r') as f:
        log_content = f.read()

    # 验证1:整体changed计数>0
    recap_match = re.search(r'changed=(\d+)', log_content)
    if not recap_match:
        print("ERROR: 未找到PLAY RECAP")
        return False
    changed_count = int(recap_match.group(1))
    if changed_count <= 0:
        print("ERROR: 整体changed计数不大于0")
        return False
    print(f"验证1通过:整体changed计数={changed_count}")

    # 验证2:Create tenants permission structure任务changed为true
    task2_pattern = r'TASK \[Create tenants permission structure\].*?changed: \[localhost\] => ({.*?})'
    task2_match = re.search(task2_pattern, log_content, re.DOTALL)
    if not task2_match:
        print("ERROR: 未找到目标任务输出")
        return False
    task2_result = json.loads(task2_match.group(1))
    if not task2_result.get('changed'):
        print("ERROR: 目标任务changed字段不为true")
        return False
    print("验证2通过:目标任务changed为true")

    # 验证3:Create Sonarqube Groups中所有test_team_b的item status为present
    task3_pattern = r'TASK \[sonarqube-onboard : Create Sonarqube Groups\].*?ok: \[localhost\] => \(item=(.*?)\) =>'
    task3_items = re.findall(task3_pattern, log_content)
    valid = True
    for item_str in task3_items:
        try:
            item = eval(item_str)  # 仅用于可信日志,生产环境建议用更安全的解析方式
            if item.get('name') == 'test_team_b':
                if item.get('status') != 'present':
                    print(f"ERROR: test_team_b的item状态不为present: {item}")
                    valid = False
        except:
            print(f"WARN: 解析item失败: {item_str}")
    if valid:
        print("验证3通过:所有test_team_b的item status为present")
    else:
        return False

    return True

if __name__ == '__main__':
    if validate_ansible_log('ansible_output.log'):
        print("所有验证点均通过")
    else:
        print("验证失败")

三、Playbook内置断言(适合执行过程中实时校验)

修改原Ansible Playbook,添加assert任务,在Playbook执行过程中直接验证结果,确保符合预期:

- name: 验证整体changed计数大于0
  assert:
    that:
      - ansible_play_stats.changed > 0
    fail_msg: "整体changed计数未大于0"
    success_msg: "整体changed计数验证通过"
  run_once: true

- name: 验证Create tenants permission structure任务changed为true
  assert:
    that:
      - hostvars.localhost.create_tenants_perm_result.changed == true
    fail_msg: "Create tenants permission structure任务changed不为true"
    success_msg: "Create tenants permission structure任务验证通过"
  # 注意:需要给原任务添加register参数,示例:
  # - name: Create tenants permission structure
  #   copy: ...
  #   register: create_tenants_perm_result

- name: 验证所有test_team_b的tenant status为present
  assert:
    that:
      - item.status == 'present'
    loop: "{{ temp_var.tenant | selectattr('name', 'equalto', 'test_team_b') | list }}"
    fail_msg: "test_team_b的tenant状态不为present: {{ item }}"
    success_msg: "test_team_b的tenant状态验证通过"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 19:52:33