Ansible:在 GRUB cmdline 中插入单词

Kal*_*san 3 regex ansible

我想使用 Ansible 的 lineinfile 或替换模块,以便将单词添加splash到 GRUB 中的 cmdline。

它应该适用于以下所有示例:

示例 1:

  • 前: GRUB_CMDLINE_DEFAULT=""
  • 后: GRUB_CMDLINE_DEFAULT="splash"

示例 2:

  • 前: GRUB_CMDLINE_DEFAULT="quiet"
  • 后: GRUB_CMDLINE_DEFAULT="quiet splash"

示例 3:

  • 前: GRUB_CMDLINE_DEFAULT="quiet nomodeset"
  • 后: GRUB_CMDLINE_DEFAULT="quiet nomodeset splash"

帖子Ansible:在文件中的现有行上插入一个单词很好地解释了如何在没有引号的情况下完成此操作。但是,我无法在引号中插入单词。

为了将单词添加splash到 cmdline(如图所示),Ansible 角色或剧本中需要什么条目?

bgo*_*ndy 7

受到 Adam 答案的启发,我使用这个来启用 IOMMU:

- name: Enable IOMMU
  ansible.builtin.lineinfile:
    path: /etc/default/grub
    regexp: '^GRUB_CMDLINE_LINUX_DEFAULT="((?:(?!intel_iommu=on).)*?)"$'
    line: 'GRUB_CMDLINE_LINUX_DEFAULT="\1 intel_iommu=on"'
    backup: true
    backrefs: true
  notify: update-grub
Run Code Online (Sandbox Code Playgroud)

请注意,我必须设置backrefstrue才能\1引用工作,否则捕获的组不会被替换。

幂等性也很好用。

编辑:请注意此代码片段仅适用于 Intel CPU,并且可能需要更新以适合您的平台。


mar*_*ele 5

您可以在没有shell输出的情况下使用 2 个lineinfiles模块执行此操作。

在您的示例中,您正在搜索splash

- name: check if splash is configured in the boot command
  lineinfile:
    backup: true
    path: /etc/default/grub
    regexp: '^GRUB_CMDLINE_LINUX=".*splash'
    state: absent
  check_mode: true
  register: grub_cmdline_check
  changed_when: false

- name: insert splash if missing
  lineinfile:
    backrefs: true
    path: /etc/default/grub
    regexp: "^(GRUB_CMDLINE_LINUX=\".*)\"$"
    line: '\1 splash"'
  when: grub_cmdline_check.found == 0
  notify: update grub
Run Code Online (Sandbox Code Playgroud)

诀窍是如果我们能找到splash某处,尝试删除该行,但只检查check_mode: true. 如果找到了该术语 ( found> 0),则我们不需要更新该行。如果没有找到,就意味着我们需要插入它。我们在最后加上 backrefs。


Kal*_*san 3

一种可能的解决方案是定义两个条目,如下所示:

- name: "Checking GRUB cmdline"
  shell: "grep 'GRUB_CMDLINE_LINUX_DEFAULT=.*splash.*' /etc/default/grub"
  register: grub_cfg_grep
  changed_when: false
  failed_when: false

- name: "Configuring GRUB cmdline"
  replace:
    path: '/etc/default/grub'
    regexp: '^GRUB_CMDLINE_LINUX_DEFAULT="((\w.?)*)"$'
    replace: 'GRUB_CMDLINE_LINUX_DEFAULT="\1 splash"'
  when: '"splash" not in grub_cfg_grep'
Run Code Online (Sandbox Code Playgroud)

说明:我们首先使用 grep 检查splash 关键字是否出现在所需的行中。由于 grep 在未找到字符串时给出负返回码,因此我们使用 抑制错误failed_when: false。grep 的输出保存到grub_cfg_grep变量中。

接下来,我们将replace模块绑定到关键字splash位于grep的标准输出中的条件。正则表达式采用引号中的旧内容并在其后面添加splash关键字。

注意:如果执行前为空字符串,则读取结果" splash"(前面有空格),但它仍然是有效的命令行。