Ansible:如何定义并调用全局计数器变量实现检测统计?
解决Ansible计数器不更新的问题
你的问题核心在于没有实际修改计数器变量——原来的debug任务只是把+1写在了输出字符串里,并没有真正更新count_pass和count_total的值。Ansible中变量默认不可直接在模板中修改,必须通过set_fact模块来更新变量值,同时可以用条件表达式实现你要的“不用when”的需求。
修正后的Playbook示例
- name: CIS Requirements check hosts: target1 vars: count_pass: 0 count_total: 0 serial: 1 tasks: - name: Check for CIS PermitRootLogin lineinfile: path: /etc/ssh/sshd_config regexp: '^(\s*)PermitRootLogin(\s+)no(\s*)$' state: absent check_mode: yes register: permitrootlogin_check - name: Update compliance counters set_fact: # 检测通过则count_pass加1,否则加0 count_pass: "{{ count_pass | int + (1 if permitrootlogin_check.changed else 0) }}" # 无论结果如何,count_total都加1 count_total: "{{ count_total | int + 1 }}" - name: Output check result debug: msg: "{% if permitrootlogin_check.changed %} [PASSED] SSH root login disabled {% else %} [FAILED] SSH root login not disabled {% endif %}" - name: Number of Compliant CIS Requirement debug: msg: "The number of compliant CIS requirement is {{ count_pass }} / {{ count_total}}"
关键说明
- 用
set_fact更新变量:这是Ansible中修改变量的标准方式,确保变量值能在后续任务中生效。 - 条件表达式替代when:通过
(1 if 条件 else 0)的三元表达式,直接计算计数器的增量,不需要单独写when分支。 - 修正原debug的语法错误:你原来的debug任务模板有语法错误(比如多余的大括号、未闭合的模板标签),已经在示例中修复。
如果后续有更多检测任务,只需要复制“检测任务 + set_fact更新计数器 + debug输出”这一组任务即可,所有任务会共享count_pass和count_total的累计值。
内容的提问来源于stack exchange,提问作者leri
相关产品推荐
相关产品推荐

