💡

OpenShift VirtualizationにWindows VMをサクッとプロビジョニングする

に公開

はじめに

OpenShift Virtualization Advent Calender 2025 14日目の記事です。

この記事では、OpenShift VirtualizationにサクッとWindows ServerなVMをプロビジョニングしよう!、をモチベーションにその方法をご紹介したいと思います。RHEL、Fedora等のLinux OSはほぼ準備なしにインストールしたVMを立ち上げることができるのですが、Windowsについては少々手間がかかります。なるべくなら、パブクラのようにVMを作ったら使える状態で立ち上がってほしいですよね。最初の仕込みはありますが、一度仕組みを作ってしまえばVirtual Machineの定義だけでOSインストールまで完了させることができます。

やってみよう

まず、適当に Project を作成しておきます。

$ oc new-project win-test

今回登場するnamescoped なリソース群は基本的に上記で管理することにします。

Windows Serverのイメージを準備する

VMが利用するインストールメディアを用意します。再利用できるように以下の通りDataVolumeのマニフェストファイルを作ります。今回はMicrosoft社が提供するWindows Server2025 のISOイメージにリンクされたURLをソースとして利用してみましょう。当記事でダウンロードリンクを直接貼るのはお行儀がよくなさそうなので、こちらを辿ってリンクを取得ください。また、defaultのStorageClassを設定していない場合は.spec.storage.storageClassNameで利用するStorageClassを明示するようにしましょう。

apiVersion: cdi.kubevirt.io/v1beta1
kind: DataVolume
metadata:
  name: win2k25-iso
spec:
  source:
    http:
      url: <ダウンロードURL>
  storage:
    resources:
      requests:
        storage: 7Gi

DataVolumeはCDI(Containerized Data Impoter)と呼ばれる仕組みが提供するリソースの1つです。当記事においては、外部ソースから仮想マシンディスクあるいは仮想メディアとして扱えるように取り込み、同時にPVCの作成を引き受けてくれる、というくらいの理解でよいかと思います。DataVolumeを作成すると専用のPodを起動し、それらをよろしくやってくれます。

DataVolumeでURLを指定して取得する、というのはVirtualMachineの.spec.dataVolumeTemplates配下に表現することも可能なのですが、VMを作成するたびにISOイメージのダウンロードが走り時間がかかってしまうので、別に定義しておくのが吉です。

作成したらoc applyします。

$ oc apply -f dv-win2k25-iso.yaml
datavolume.cdi.kubevirt.io/win2k25-iso created

イメージをダウンロードするためDataVolumeの作成に少し時間がかかります。oc waitして待ちましょう。

$ oc wait dv win2k25-iso --for=condition=Ready --timeout=60m
datavolume.cdi.kubevirt.io/win2k25-iso condition met

もしCDIの動作が気になる方はoc get podやoc logsで確認してみてください。

$ oc get pods
NAME                                                  READY   STATUS    RESTARTS   AGE
importer-prime-714a3087-4bf7-4935-863a-d91b9948199e   1/1     Running   0          7s

これでイメージの準備は完了です。

autounattend.xmlを作成する

インストールメディアのイメージが用意できたので早速VMを作成したいところですが、そのまま起動するとインストーラーのGUIとこんにちはしてポチポチすることになります。今回は、手動操作なしにインストールが完了した状態にもっていくことが目標なので、このプロセスをSysprepの自動応答ファイルautounattend.xmlを作って自動化してみます。

まずVirtual Machineでどのように表現できるかを確認してみましょう。

$ oc explain vm.spec.template.spec.volumes.sysprep
GROUP:      kubevirt.io
KIND:       VirtualMachine
VERSION:    v1

FIELD: sysprep <Object>


DESCRIPTION:
    Represents a Sysprep volume source.

FIELDS:
  configMap     <Object>
    ConfigMap references a ConfigMap that contains Sysprep answer file named
    autounattend.xml that should be attached as disk of CDROM type.

  secret        <Object>
    Secret references a k8s Secret that contains Sysprep answer file named
    autounattend.xml that should be attached as disk of CDROM type.

configMapやSecretにautounattend.xmlというファイル名でXMLを定義しておけばよさそうです。autounattend.xmlを0から直接編集するのは中々辛いですが、それでも自分の手で作成したい場合は、こちらで説明されているように、Windows ADKのツールキットに含まれるWindows SIMと呼ばれるツールを利用しましょう。今回は同ツールを使って私があーでもないこーでもないと奮闘して作成し、ConfigMapとして仕立てた内容を以下に記載します。

apiVersion: v1
kind: ConfigMap
metadata:
  name: win2k25-autounattend
data:
  autounattend.xml: |
    <?xml version="1.0" encoding="utf-8"?>
    <unattend xmlns="urn:schemas-microsoft-com:unattend">
        <settings pass="windowsPE">
            <component name="Microsoft-Windows-International-Core-WinPE" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <SetupUILanguage>
                    <UILanguage>en-US</UILanguage>
                </SetupUILanguage>
                <InputLocale>en-US</InputLocale>
                <UILanguage>en-US</UILanguage>
                <UserLocale>en-US</UserLocale>
                <SystemLocale>en-US</SystemLocale>
            </component>
            <component name="Microsoft-Windows-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <DiskConfiguration>
                    <Disk wcm:action="add">
                        <CreatePartitions>
                            <CreatePartition wcm:action="add">
                                <Order>1</Order>
                                <Size>500</Size>
                                <Type>Primary</Type>
                            </CreatePartition>
                            <CreatePartition wcm:action="add">
                                <Order>2</Order>
                                <Extend>true</Extend>
                                <Type>Primary</Type>
                            </CreatePartition>
                        </CreatePartitions>
                        <ModifyPartitions>
                            <ModifyPartition wcm:action="add">
                                <Order>1</Order>
                                <Format>NTFS</Format>
                                <Label>System</Label>
                                <PartitionID>1</PartitionID>
                                <Active>true</Active>
                            </ModifyPartition>
                            <ModifyPartition wcm:action="add">
                                <Order>2</Order>
                                <Format>NTFS</Format>
                                <Letter>C</Letter>
                                <PartitionID>2</PartitionID>
                            </ModifyPartition>
                        </ModifyPartitions>
                        <DiskID>0</DiskID>
                        <WillWipeDisk>true</WillWipeDisk>
                    </Disk>
                </DiskConfiguration>
                <ImageInstall>
                    <OSImage>
                        <InstallFrom>
                            <MetaData wcm:action="add">
                                <Key>/IMAGE/INDEX</Key>
                                <Value>2</Value>
                            </MetaData>
                        </InstallFrom>
                        <InstallTo>
                            <DiskID>0</DiskID>
                            <PartitionID>2</PartitionID>
                        </InstallTo>
                    </OSImage>
                </ImageInstall>
                <UserData>
                    <AcceptEula>true</AcceptEula>
                    <FullName>user</FullName>
                </UserData>
            </component>
        </settings>
        <settings pass="oobeSystem">
            <component name="Microsoft-Windows-Shell-Setup" processorArchitecture="amd64" publicKeyToken="31bf3856ad364e35" language="neutral" versionScope="nonSxS" xmlns:wcm="http://schemas.microsoft.com/WMIConfig/2002/State" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
                <AutoLogon>
                    <Password>
                        <Value>P@ssw0rd123</Value>
                        <PlainText>true</PlainText>
                    </Password>
                    <Enabled>true</Enabled>
                    <Username>Administrator</Username>
                </AutoLogon>
                <FirstLogonCommands>
                    <SynchronousCommand wcm:action="add">
                        <Order>1</Order>
                        <Description>Copy Post Install Script Into C Drive</Description>
                        <CommandLine>cmd /c copy E:\post-install.ps1 C:\Windows\Temp\post-install.ps1</CommandLine>
                        <RequiresUserInput>false</RequiresUserInput>
                    </SynchronousCommand>
                    <SynchronousCommand wcm:action="add">
                        <Order>2</Order>
                        <Description>Post Installation Script</Description>
                        <CommandLine>powershell -ExecutionPolicy Bypass -NoProfile -File C:\Windows\Temp\post-install.ps1</CommandLine>
                        <RequiresUserInput>false</RequiresUserInput>
                    </SynchronousCommand>
                </FirstLogonCommands>
                <UserAccounts>
                    <AdministratorPassword>
                        <Value>P@ssw0rd123</Value>
                        <PlainText>true</PlainText>
                    </AdministratorPassword>
                </UserAccounts>
            </component>
        </settings>
        <cpi:offlineImage cpi:source="wim:c:/users/administrator/desktop/sources/install.wim#Windows Server 2025 SERVERSTANDARD" xmlns:cpi="urn:schemas-microsoft-com:cpi" />
    </unattend>
  post-install.ps1: |
    # Disable AutoLogon
    reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Winlogon" /v AutoAdminLogon /t REG_SZ /d 0 /f

    # Enable RDP
    Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Control\Terminal Server' -Name 'fDenyTSConnections' -Value 0
    Enable-NetFirewallRule -DisplayGroup 'Remote Desktop'

    # install virtio drivers
    Start-Process msiexec -Wait -ArgumentList '/i F:\virtio-win-gt-x64.msi /qn /passive /norestart'

    # install Guest Agent
    Start-Process msiexec -Wait -ArgumentList '/i F:\guest-agent\qemu-ga-x86_64.msi /qn /passive /norestart'

    # Rename cached unattend.xml to avoid it is picked up by sysprep
    mv C:\Windows\Panther\unattend.xml C:\Windows\Panther\unattend.install.xml

    # Eject CD containing autounattend.xml, to avoid that the autounattend.xml on the CD is picked up by sysprep
    (new-object -COM Shell.Application).NameSpace(17).ParseName('E:').InvokeVerb('Eject')

    # Logout
    logoff

目が痛くなりますね。長いので、要点だけまとめます。

  • ConfigMapはautounattend.xmlとpost-install.ps1の2つのファイルで構成される
  • autounattend.xmlでは主に以下の設定を行う
    • 言語/ロケールなどの設定
    • ディスク構成とパーティション [1]
    • EULAのAccept
    • Administratorパスワードの設定
    • post-install.ps1の実行
  • post-install.ps1では主に以下の設定を行う
    • RDPの有効化
    • QEMU Guest Agentのインストール

結構色々とやってますが、ここでのポイントはPowerShellスクリプトを別途定義し、インストール後の処理をまとめて定義できる点です。このために autounattend.xmlで一度Administratorの自動ログオンを有効にし、<FirstLogonCommaneds>で指定したスクリプトを実行できるようにしています(同スクリプト内で自動ログオンは無効化しておく)。このあたりのアイディアはKubevirtのドキュメントでも紹介されています。一度作ってしまえばConfigMapとしてVMの定義と疎にして管理できるので、構成パターンに応じて複数用意しておく、なんてこともできそうですね。

同様にoc applyしておきましょう。

$ oc apply -f cm-win2k25-autounattend.yaml
configmap/win2k25-autounattend created

Windows VMを作成してみる

Virtual Machineを以下の通り作成します。

apiVersion: kubevirt.io/v1
kind: VirtualMachine
metadata:
  name: win2k25-bios
  labels:
    app: win2k25-bios
spec:
  dataVolumeTemplates:
    - apiVersion: cdi.kubevirt.io/v1beta1
      kind: DataVolume
      metadata:
        name: win2k25-bios-rootdisk
      spec:
        source:
          blank: {}
        storage:
          resources:
            requests:
              storage: 30Gi
  runStrategy: RerunOnFailure
  template:
    metadata:
      labels:
        kubevirt.io/domain: win2k25-bios
    spec:
      architecture: amd64
      domain:
        cpu:
          cores: 2
        memory:
          guest: 8Gi
        devices:
          disks:
            - name: install-cdrom
              cdrom:
                bus: sata
              bootOrder: 1
            - name: rootdisk
              disk:
                bus: sata
              bootOrder: 2
            - name: autounattend
              cdrom:
                bus: sata
              bootOrder: 3
            - name: windows-drivers-disk
              cdrom:
                bus: sata
              bootOrder: 4
          inputs:
            - bus: usb
              name: tablet
              type: tablet
          interfaces:
            - masquerade: {}
              model: e1000e
              name: default
        firmware:
          bootloader:
            bios: {}
      networks:
        - name: default
          pod: {}
      volumes:
        - name: rootdisk
          dataVolume:
            name: win2k25-bios-rootdisk
        - name: install-cdrom
          dataVolume:
            name: win2k25-iso
        - name: autounattend
          sysprep:
            configMap:
              name: win2k25-autounattend
        - name: windows-drivers-disk
          containerDisk:
            image: 'registry.redhat.io/container-native-virtualization/virtio-win-rhel9@sha256:1381651e31d98acb260df3f0fbd1347248c325161828da4181b12ad3f760ab05'

上記のポイントだけ拾います。
.spec.template.spec.domain.disks と .spec.template.spec.volumesでは、事前に準備したインストールメディアや、autounattend.xmlを抱えた仮想メディアをCD-ROMとして定義しています。また、Red Hatが提供しているvirtioドライバやQEMU Guest Agentが入ったコンテナディスクも利用します。また、.spec.template.spec.domain.disksにbootOrderを指定しないとCD-ROMから起動してないので、ここも指定しておきましょう。

では、oc applyでVMをプロビジョニングします。

$ oc apply -f vm-win2k25-bios.yaml
virtualmachine.kubevirt.io/win2k25-bios created

Web UIからVNC Consoleでインストール中の画面を確認してみると、インストールが進んでいることを確認できます。

インストールが完了すると自動でログインし、post-install.ps1のスクリプトが実行されます。

無事スクリプトの実行が完了し、ログアウトしました。

QEMU Guest Agentがインストールされたため、Web UIからホスト名が拾えるようになっています。

以上で完了です。インストールメディアやautounattend.xmlを使いまわせばVirtual Machineの定義だけでWindowsのインストール作業に煩わされずVMを起動できるようになります。

まとめ

当記事ではWindows ServerをOpenShift Virtualizationで手軽に利用するための方法をご紹介しました。ちょっとWindows VMで検証したい、という場面で活躍できるかもしれません。OSインストールの自動化はWindowsの機能に頼っているので、既存で同じような仕組みを利用されている場合は流用しやすいのではないでしょうか。ただ、この仕組みで人手のインストール作業が省略できても、インストールそのものは省略できないので多少時間がかかります。より高速に払い出すなら、標準化した設計/設定を施したVMをSysprepで汎化してゴールデンイメージを作る、など検討してもよさそうですね。

脚注
  1. https://learn.microsoft.com/ja-jp/windows-hardware/manufacture/desktop/configure-biosmbr-based-hard-drive-partitions?view=windows-11 ↩︎

Discussion