如何让Ansible检测Windows待安装补丁并在邮件中展示结果?
解决Ansible邮件正文循环输出Windows待安装补丁的问题
修改思路
要遍历所有远程Windows主机的补丁检测结果,需利用Ansible的变量遍历能力,通过groups['all']获取所有目标主机,逐个提取每个主机的补丁列表,拼接成符合要求的格式。
修改后的Playbook
- hosts: all name: check patching gather_facts: 'no' tasks: - name: Get list of pending patches win_shell: >- (New-Object -ComObject Microsoft.Update.Session).CreateupdateSearcher().Search("IsHidden=0 and IsInstalled=0").Updates | Select-Object Title register: pending_patches - hosts: localhost tasks: - name: Generate email body content set_fact: email_body: | {% for host in groups['all'] %} "{{ host }}" Requires "{{ hostvars[host]['pending_patches'].stdout_lines | join('", "') }}" {% endfor %} - name: Send patch notification email mail: host: 1.1.1.1 port: 25 from: SomeEmail@Somewhere.com to: SomeEmail@SomewhereElse.com subject: Pending Windows Patches Report body: "{{ email_body }}"
关键说明
- 语义化变量命名:将原
List重命名为pending_patches,避免变量名模糊导致的混淆。 - Jinja2模板循环生成正文:通过
groups['all']遍历所有目标主机,提取对应主机的补丁列表;若单主机存在多个待安装补丁,用join('", "')将多个补丁标题拼接为逗号分隔的字符串。 - 修复邮件模块语法:原playbook缺失
mail模块声明,需补上mail:才能正常执行邮件发送任务。
特殊场景适配
如果groups['all']包含localhost,需在循环中排除它,修改模板部分:
{% for host in groups['all'] if host != 'localhost' %}
内容的提问来源于stack exchange,提问作者user3266154
相关产品推荐
相关产品推荐

