Ansible Playbook跨多OS获取更新时间,debug多变量报错如何解决?
解决多系统Ansible Playbook中debug环节变量未定义问题
问题原因
你的Playbook中,针对不同操作系统的任务会被when条件判断跳过:
- Ubuntu服务器会跳过RHEL相关任务,导致
lastupdate_r变量未被创建 - RHEL/CentOS服务器会跳过Ubuntu相关任务,导致
lastupdate_u变量未被创建
debug模块同时引用两个可能未定义的变量,就会触发VARIABLE IS NOT DEFINED!错误。
解决方案
以下是几种可行的修复方式:
方案1:使用default过滤器处理未定义变量
给未定义的变量设置默认提示文本,避免报错:
--- - hosts: mysystems tasks: - name: Get last update run - Ubuntu register: lastupdate_u shell: echo "Last apt activity is $(grep Start-Date /var/log/apt/history.log | tail -n 1 | awk '{print $2}')" when: ansible_distribution == 'Ubuntu' - name: Get last update run - RHEL/CentOS register: lastupdate_r shell: echo "Last dnf activity is $(grep 'logging initialized' /var/log/dnf.log | tail -n 1 | awk '{print $1}')" when: ansible_distribution in ['CentOS', 'RedHat'] - debug: msg: | {{ lastupdate_u.stdout_lines | default('无APT更新记录') }} {{ lastupdate_r.stdout_lines | default('无DNF更新记录') }}
方案2:统一注册到同一个变量
让不同系统的任务都注册到同一个变量名,确保每个服务器都会生成该变量:
--- - hosts: mysystems tasks: - name: Get last update run - Ubuntu register: last_update shell: echo "Last apt activity is $(grep Start-Date /var/log/apt/history.log | tail -n 1 | awk '{print $2}')" when: ansible_distribution == 'Ubuntu' - name: Get last update run - RHEL/CentOS register: last_update shell: echo "Last dnf activity is $(grep 'logging initialized' /var/log/dnf.log | tail -n 1 | awk '{print $1}')" when: ansible_distribution in ['CentOS', 'RedHat'] - debug: var: last_update.stdout_lines
这种方式最简洁,每个服务器只会触发其中一个任务,last_update变量始终有值。
方案3:用set_fact整合变量
通过set_fact自动取已定义的变量值:
--- - hosts: mysystems tasks: - name: Get last update run - Ubuntu register: lastupdate_u shell: echo "Last apt activity is $(grep Start-Date /var/log/apt/history.log | tail -n 1 | awk '{print $2}')" when: ansible_distribution == 'Ubuntu' - name: Get last update run - RHEL/CentOS register: lastupdate_r shell: echo "Last dnf activity is $(grep 'logging initialized' /var/log/dnf.log | tail -n 1 | awk '{print $1}')" when: ansible_distribution in ['CentOS', 'RedHat'] - set_fact: update_info: "{{ lastupdate_u.stdout_lines | default(lastupdate_r.stdout_lines) }}" - debug: var: update_info
内容的提问来源于stack exchange,提问作者MPWeber
相关产品推荐
相关产品推荐

