如何使用 Ansible 的 win_regedit 模块在 Windows 系统中自动化创建注册表键和值

以下是一个完整的指南,介绍如何使用 Ansible 的 win_regedit 模块在 Windows 类系统中创建指定路径下的注册表键和值。手动更改注册表值可能会耗时且容易出错,而 Ansible 提供了内置功能以无副作用的方式管理单个键值对。

使用 Ansible 模块 win_regedit 添加 Windows 注册表项

关于 win_regedit 模块

win_regedit 是 Ansible 的一个模块,全名为 ansible.windows.win_regedit,属于 Ansible 的 Windows 模块集合。该模块非常稳定,已经存在多年,适用于 Windows 和 Windows Server 操作系统。它用于添加、修改或删除注册表键和值。

主要参数

  • path(字符串,必需):指定要操作的完整注册表键路径,包括 Hive(如 HKLM 或 HKCU)。
  • name(字符串,必需):指定注册表项的名称。
  • type(字符串,必需):指定值的数据类型,选项包括:
  • string:字符串类型
  • dword:32 位整数
  • qword:64 位整数
  • binary:二进制数据
  • multistring:多字符串
  • expandstring:可扩展字符串
  • data(字符串,必需):指定注册表项的值。
  • state(字符串):指定操作的状态。可选值包括:
  • present:添加或修改注册表项。
  • absent:删除注册表项。

示例代码

以下是一个 Ansible Playbook,用于在 Windows 系统中创建一个注册表键,路径为 HKEY_LOCAL_MACHINE\Software\Test,键名为 hello,值为 world。

文件名:registry_add.yml

---
- name: 添加 Windows 注册表项
  hosts: all
  vars:
    mypath: 'HKLM:\Software\Test'  # 注册表路径
    mykey: 'hello'                  # 注册表键名
    mytype: string                  # 数据类型
    myvalue: 'world'                # 注册表值
  tasks:
    - name: 添加注册表键值
      ansible.windows.win_regedit:
        path: "{{ mypath }}"
        name: "{{ mykey }}"
        type: "{{ mytype }}"
        data: "{{ myvalue }}"

执行命令

$ ansible-playbook -i virtualmachines/win/inventory windows/registry_add.yml

执行结果

PLAY [添加 Windows 注册表项] *******************************************************

TASK [Gathering Facts] ******************************************************
ok: [WindowsServer]

TASK [添加注册表键值] *************************************************************
changed: [WindowsServer]

PLAY RECAP *******************************************************************
WindowsServer              : ok=2    changed=1    unreachable=0    failed=0    skipped=0    rescued=0    ignored=0

验证注册表项是否创建成功

在 Windows 主机上检查注册表项是否已创建:

$ ssh vagrant@WindowsServer
C:\>reg query "HKLM\Software\Test"

如果注册表项存在,您将看到类似以下的输出:

HKEY_LOCAL_MACHINE\Software\Test
    hello    REG_SZ    world

通过以上步骤,您可以使用 Ansible 的 win_regedit 模块轻松在 Windows 系统中添加注册表键和值。