Ansible Playbook遇不可达主机时Jinja2逻辑执行失败求助
修复Ansible邮件Playbook中不可达主机的变量未定义错误
当清单内存在不可达主机时,check uptime Play会因ignore_unreachable: yes跳过该主机的uptime采集任务,导致对应主机的hostvars中没有up_time变量,邮件任务的Jinja2模板直接访问servervars.up_time.stdout就会触发变量未定义错误。以下是两种可行的修复方案:
方案一:在Jinja2模板中增加变量存在性检查
遍历主机时先判断up_time变量是否存在,再执行后续的数值判断,避免访问不存在的属性:
- name: send mail hosts: localhost gather_facts: no become: no tasks: - name: Communication on high uptime servers mail: host: relay.cust.services port: 25 from: abc@xyz.com to: abc@xyz.com subject: Communication on high uptime servers body: |- {% for server, servervars in hostvars.items() %} {% if servervars.up_time is defined %} {% if servervars.up_time.stdout |int >= 10 %} Consider rebooting the server **{{ server }}** for better performance as it has high uptime of days: {{ servervars.up_time.stdout }} {% endif %} {% endif %} {% endfor %}
方案二:仅遍历可达主机组
利用之前group_by模块生成的host_status_success组(仅包含可达主机),直接遍历该组主机,完全避开不可达主机的变量问题:
- name: send mail hosts: localhost gather_facts: no become: no tasks: - name: Communication on high uptime servers mail: host: relay.cust.services port: 25 from: abc@xyz.com to: abc@xyz.com subject: Communication on high uptime servers body: |- {% for server in groups['host_status_success'] %} {% set servervars = hostvars[server] %} {% if servervars.up_time.stdout |int >= 10 %} Consider rebooting the server **{{ server }}** for better performance as it has high uptime of days: {{ servervars.up_time.stdout }} {% endif %} {% endfor %}
额外优化建议
可以将check uptime Play的目标主机改为host_status_success,避免对不可达主机执行无用任务:
- name: check uptime hosts: host_status_success gather_facts: no ignore_unreachable: yes become: no tasks: - name: check uptime raw: uptime |awk '{print $3}' register: up_time
内容的提问来源于stack exchange,提问作者Sharma
相关产品推荐
相关产品推荐

