如何编写Ansible Playbook根据CPU厂商配置IOMMU的GRUB参数
如何编写Ansible Playbook根据CPU厂商配置IOMMU的GRUB参数
遇到这个ansible_processor_vendor未定义的报错很正常,问题出在你没有让Ansible收集目标主机的系统事实(facts)——这个变量是Ansible通过收集主机硬件信息生成的,默认情况下如果你的Playbook没有开启事实收集,就会找不到这个变量。
下面是修正后的完整Playbook,我会一步步给你解释关键点:
- name: Configure GRUB for IOMMU based on CPU manufacturer hosts: your_target_hosts become: yes gather_facts: yes # 关键!开启事实收集,这样才能获取ansible_processor_vendor变量 tasks: - name: Set GRUB options for Intel systems ansible.builtin.lineinfile: path: /etc/default/grub regexp: '^GRUB_CMDLINE_LINUX_DEFAULT=' line: 'GRUB_CMDLINE_LINUX_DEFAULT="quiet splash intel_iommu=on iommu=pt"' backrefs: yes when: ansible_processor_vendor == 'GenuineIntel' notify: update-grub - name: Set GRUB options for AMD systems ansible.builtin.lineinfile: path: /etc/default/grub regexp: '^GRUB_CMDLINE_LINUX_DEFAULT=' line: 'GRUB_CMDLINE_LINUX_DEFAULT="quiet splash amd_iommu=on iommu=pt"' backrefs: yes when: ansible_processor_vendor == 'AuthenticAMD' notify: update-grub handlers: - name: update-grub ansible.builtin.command: update-grub # 注意:如果是RHEL/CentOS系的发行版,这里应该换成 grub2-mkconfig -o /boot/grub2/grub.cfg
关键点说明:
- 开启事实收集:添加
gather_facts: yes(其实默认就是yes,但明确写出来更稳妥,避免之前不小心关掉了这个配置),这样Ansible会先执行setup模块收集主机的硬件、系统信息,包括ansible_processor_vendor变量。 - 条件判断的正确性:
ansible_processor_vendor的值确实是GenuineIntel(英特尔)和AuthenticAMD(AMD),你的判断条件没问题。 - handler的适配性:不同Linux发行版更新GRUB的命令可能不一样——Debian/Ubuntu系用
update-grub,而RHEL/CentOS/Rocky Linux这类系统需要用grub2-mkconfig -o /boot/grub2/grub.cfg,如果你的服务器混合了不同发行版,可以给handler加条件判断,比如:
handlers: - name: update-grub for Debian/Ubuntu ansible.builtin.command: update-grub when: ansible_os_family == 'Debian' - name: update-grub for RHEL/CentOS ansible.builtin.command: grub2-mkconfig -o /boot/grub2/grub.cfg when: ansible_os_family == 'RedHat'
另外,如果你担心覆盖原有的GRUB_CMDLINE_LINUX_DEFAULT里的其他参数,可以改用ansible.builtin.replace模块,或者用lineinfile的insertafter/insertbefore配合正则,不过你的原写法用backrefs: yes是没问题的,它会匹配原行并替换成新的内容。
备注:内容来源于stack exchange,提问作者knpwrs




