返回

WSL2 中 Molecule 和 Vagrant 启动 VM 失败?轻松解决无头模式问题

windows

WSL2 中使用 Molecule 和 Vagrant 通过无头模式启动 VM 失败

问题

在 Windows Subsystem for Linux 2 (WSL2) 中使用 Molecule 和 Vagrant 通过无头模式启动虚拟机 (VM) 时遇到问题。

解决方法

解决此问题的方法是在 Molecule.yml 文件中指定 GUI 模式:

  1. 添加 Vagrant 提供程序配置:
driver:
  name: vagrant
  provider:
    name: virtualbox
    gui: true
  1. 移除无头 CLI 命令:
start_command: "startvm \"{{ instance_name }}\""
  1. 完整的 Molecule.yml 配置:
---
dependency:
  name: galaxy
  enabled: false
prerun: false
driver:
  name: vagrant
  provider:
    name: virtualbox
    gui: true  
lint: |
  yamllint .
  ansible-lint .
platforms:
  - name: peertube-host
    box: debian/buster64
    memory: 2048
    cpu: 2
    interfaces:
      - auto_config: true
        network_name: private_network
        type: static
        ip: "192.168.56.4"
provisioner:
  name: ansible
  log: True
  env:
    ALLOW_WORLD_READABLE_TMPFILES: True
    ANSIBLE_FORCE_COLOR: true
    ANSIBLE_ROLES_PATH: ../../roles:../../roles-dependencies/
    ANSIBLE_COLLECTIONS_PATH: $PWD/collections-dependencies/
    ANSIBLE_VERBOSITY: 3
  playbooks:
    converge: ../../site.yml
  inventory:
    links:
      group_vars: ../../inventories/molecule/group_vars/
verifier:
  name: testinfra
  options:
    junit-xml: default-report.xml
    o: "junit_family=legacy"

解释

  • provider 配置下添加 gui: true 将 Vagrant 提供程序配置为在 GUI 模式下启动 VM。
  • 移除 start_command,因为 Vagrant CLI 会自动尝试在 GUI 模式下启动 VM,如果 Vagrantfile 中未指定其他设置。

注意

  • 使用 GUI 模式可能会增加启动 VM 所需的时间。
  • 如果在使用 GUI 模式时遇到问题,请确保 VirtualBox 已正确安装并已启用 VT-x 或 AMD-V 硬件虚拟化。

常见问题解答

  1. 为什么需要在 WSL2 中使用 GUI 模式来启动 VM?

    由于 WSL2 无法直接访问 GPU,因此在 headless 模式下启动 VM 会导致图形问题。

  2. 为什么在 Molecule.yml 文件中指定 GUI 模式很重要?

    Molecule 使用 Vagrant CLI 来启动和管理 VM,因此在 Molecule.yml 文件中指定 GUI 模式将确保 Vagrant CLI 以 GUI 模式启动 VM。

  3. 使用 GUI 模式有什么优点?

    GUI 模式允许用户可视化 VM 的启动过程,并更轻松地诊断问题。

  4. 使用 GUI 模式有什么缺点?

    GUI 模式可能会增加启动 VM 所需的时间。

  5. 除了使用 GUI 模式之外,还有哪些其他方法可以解决此问题?

    另一种方法是安装带有 WSL2 GPU 支持的 Windows 10 或 11 版本,这将允许在 headless 模式下启动 VM。