如何使用 Ansible Playbook 和 win_regedit 模块在类似 Windows 的系统中自动化删除特定 Hive 下的“Test”路径以及其中的“hello”键? 手动更改注册表值可能会耗时且容易出错。 Ansible 提供了内置功能,可以以幂等的方式管理单个键值对。

在类似 Windows 的系统中使用 Ansible 删除 Windows 注册表 ansible.windows.win_regedit 获取 Windows 注册表键的信息 让我们来谈谈 Ansible 的 win_regedit 模块。 它的全名是 ansible.windows.win_regedit,这意味着它是专门用于与 Windows 目标主机交互的模块集合的一部分。 这是一个非常稳定的模块,已经存在多年,并且适用于 Windows 和 Windows Server 操作系统。 它可以添加、更改或删除注册表键和值。

参数

  • path(字符串):要搜索的完整注册表键路径,包括 Hive。
  • name(字符串):路径参数中注册表项的名称。
  • state(字符串):present/absent 唯一强制性的参数是“path”,即要搜索的完整注册表键路径,包括 Hive。 你可能需要指定一个“name”,即注册表项的名称。 如果你想要删除所有路径,基本上是整个 Windows 注册表树,但如果你只想删除单个条目,还需要指定它的“name”。请注意! 对于我们用例来说,关键的参数是“state”,用于指定我们是想添加或修改(“present”选项)还是删除(“absent”选项)。

示例

如何在类似 Windows 的系统中使用 Ansible Playbook 访问 Windows 注册表来删除 Windows 注册表键。 具体来说,我将删除位于“HKEY_LOCAL_MACHINESoftwareTest”的 Windows 注册表键。

代码

---
- name: windows registry remove
  hosts: all
  vars:
    mypath: 'HKLM:\Software\Test'
  tasks:
    - name: registry remove path
      ansible.windows.win_regedit:
        path: "{{ mypath }}"
        state: absent

执行

ansible-pilot $ ansible-playbook -i virtualmachines/win/inventory windows/registry_remove.yml
PLAY [windows registry remove] ******************************************************
TASK [Gathering Facts] **************************************************************
ok: [WindowsServer]
TASK [registry remove path] *********************************************************
changed: [WindowsServer]
PLAY RECAP ***************************************************************************
WindowsServer              : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
ansible-pilot $

幂等性

ansible-pilot $ ansible-playbook -i virtualmachines/win/inventory windows/registry_remove.yml
PLAY [windows registry remove] ******************************************************
TASK [Gathering Facts] **************************************************************
ok: [WindowsServer]
TASK [registry remove path] *********************************************************
ok: [WindowsServer]
PLAY RECAP ***************************************************************************
WindowsServer              : ok=2    changed=0    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0
ansible-pilot $

执行前

win_regedit 执行前

执行后

win_regedit 执行后