Hyper-V Terraform Provider

repository·master·Indexed 42 days ago

https://github.com/taliesins/terraform-provider-hyperv

A Terraform provider for managing Microsoft Hyper-V resources, including Network Switches, VHDs, and Virtual Machine Instances. It enables remote management of Windows hosts via WinRM, supporting operations from both Windows and Linux machines. Requires Terraform version 1.29.x and Go version 1.19 for building from source.

Tokens
16.8K
Snippets
41
Records
59
Agent score
54%

What's inside Hyper-V Terraform Provider

  1. Use the hyperv_machine_instance data source

    master

    The hyperv_machine_instance data source allows you to retrieve information about an existing Hyper-V virtual machine instance. This is useful for inspecting the configuration, state, or properties of a VM that was created outside of the current Terraform workspace or by a different resource.

    terraform {
      required_providers {
        hyperv = {
          source  = "taliesins/hyperv"
          version = ">= 1.0.3"
        }
      }
    }
    
    provider "hyperv" {}
    
    # Example: Fetching an existing machine named 'WebServer'
    data "hyperv_machine_instance" "default" {
      name = "WebServer"
    }
    
    output "vm_details" {
      value = data.hyperv_machine_instance.default
    }
  2. Configure Hyper-V machine memory settings

    master

    You can manage memory allocation using either static or dynamic memory modes:

    • Static Memory: Set static_memory = true and define the amount of memory in memory_startup_bytes.
    • Dynamic Memory: Set dynamic_memory = true. You can then specify:
      • memory_minimum_bytes: The minimum amount of memory allocated.
      • memory_maximum_bytes: The maximum amount of memory allocated.
      • memory_startup_bytes: The amount of memory allocated upon startup.
  3. Run HyperV Provider examples

    master

    To explore and run the various HyperV service examples provided in this repository, clone the repository and navigate to the specific example directory. Each example directory contains its own README.md with detailed instructions on its specific functionality and execution steps.

    $ git clone https://github.com/taliesins/terraform-provider-hyperv
    $ cd terraform-provider-hyperv/examples/vm-from-scratch
  4. Requirements for HyperV Terraform Provider

    master

    To use or build the HyperV Terraform Provider, ensure you meet the following requirements:

    • Terraform: version 1.29.x
    • Go: version 1.19 (required for building the provider plugin)
    • HyperV Host: A Windows machine running Windows 10, Windows Server 2016, or newer, with connectivity and credentials available.
  5. Configure Hyper-V provider credentials

    master

    To use the Hyper-V provider, you must provide credentials for the host machine. You can do this in two ways:

    1. Environment Variables: Set HYPERV_USER and HYPERV_PASSWORD in your shell.
    2. Provider Configuration: Define the user and password properties directly within the hyperv provider block in your Terraform configuration.
    provider "hyperv" {
    	user     = "${var.username}"
    	password = "${var.password}"
    }
  6. Verify WinRM connectivity

    master

    Before using the provider, verify you can connect to the Windows host using PowerShell. Use the following script to test the connection (replace $winrmPort with 5986 for HTTPS or 5985 for HTTP):

    $hostName=[System.Net.Dns]::GetHostName()
    $winrmPort = "5986"
    
    # Get the credentials of the machine
    $cred = Get-Credential
    
    # Connect to the machine
    $soptions = New-PSSessionOption -SkipCACheck -SkipCNCheck
    Enter-PSSession -ComputerName $hostName -Port $winrmPort -Credential $cred -SessionOption $soptions -UseSSL
    $hostName=[System.Net.Dns]::GetHostName()
    $winrmPort = "5986"
    
    # Get the credentials of the machine
    $cred = Get-Credential
    
    # Connect to the machine
    $soptions = New-PSSessionOption -SkipCACheck -SkipCNCheck
    Enter-PSSession -ComputerName $hostName -Port $winrmPort -Credential $cred -SessionOption $soptions -UseSSL
  7. Manage Virtual Hard Disks with hyperv_vhd

    master

    The hyperv_vhd resource allows you to create and manage Virtual Hard Disks (VHD/VHDX) in Hyper-V. You can create new disks from scratch, copy them from a source (URL or local path), or create differencing disks from a parent disk.

    terraform {
      required_providers {
        hyperv = {
          source  = "taliesins/hyperv"
          version = ">= 1.0.3"
        }
      }
    }
    
    provider "hyperv" {
    }
    
    resource "hyperv_vhd" "web_server_vhd" {
      path = "c:\\web_server\\web_server_g2.vhdx"
      vhd_type = "Dynamic"
      size = 10737418240 #10GB
    }
  8. Configure hyperv_machine_instance firmware, processor, and services

    master

    When defining or inspecting a hyperv_machine_instance, you can manage several nested configuration blocks:

    Firmware (vm_firmware)

    Controls boot behavior and security settings.

    • enable_secure_boot: Set to "On" or "Off".
    • preferred_network_boot_protocol: e.g., "IPv4".
    • boot_order: A list of boot_order blocks defining boot_type (e.g., "HardDiskDrive", "NetworkAdapter"), controller_number, and controller_location.

    Processor (vm_processor)

    Configures CPU resource allocation.

    • relative_weight: Integer value for CPU priority.
    • maximum: Percentage of CPU usage.
    • compatibility_for_migration_enabled: Boolean for live migration support.

    Integration Services (integration_services)

    A map of service names to boolean values to enable/disable specific Hyper-V guest services. Common keys include:

    • "Heartbeat"
    • "Key-Value Pair Exchange"
    • "Shutdown"
    • "Time Synchronization"
    • "VSS"
    resource "hyperv_machine_instance" "example" {
      name = "WebServer"
      
      vm_firmware {
        enable_secure_boot = "Off"
        boot_order {
          boot_type           = "HardDiskDrive"
          controller_number   = "0"
          controller_location = "0"
        }
      }
    
      vm_processor {
        relative_weight = 100
      }
    
      integration_services = {
        "Heartbeat"            = true
        "Time Synchronization" = true
      }
    }
  9. Run the VM from scratch example

    master

    This example demonstrates how to create a Hyper-V switch and attach two virtual machines to it.

    To run this example, you must provide credentials for the Hyper-V host. You can do this in two ways:

    1. Environment Variables: Set HYPERV_USER and HYPERV_PASSWORD in your shell.
    2. Provider Configuration: Define the user and password arguments within the hyperv provider block.

    After configuring credentials, execute the standard Terraform workflow:

    # Option 1: Provider Configuration
    provider "hyperv" {
    	user     = "${var.username}"
    	password = "${var.password}"
    }
    
    # Option 2: Execution commands
    terraform init
    terraform plan -out=tfplan
    terraform apply tfplan
  10. Configure network adaptors and drives for hyperv_machine_instance

    master

    The hyperv_machine_instance resource/data source supports defining hardware components:

    Network Adaptors (network_adaptors)

    Defines virtual network interfaces.

    • name: The name of the adapter.
    • switch_name: The name of the hyperv_network_switch to attach to.
    • is_legacy: Boolean for legacy vs synthetic adapters.
    • dynamic_mac_address: Boolean.

    DVD Drives (dvd_drives)

    Defines optical drives.

    • controller_number and controller_location: Used to position the drive in the controller hierarchy.
    • path: Path to the ISO file.

    Hard Disk Drives (hard_disk_drives)

    Defines virtual hard disks.

    • controller_type: e.g., "Scsi" or "IDE".
    • path: The absolute path to the .vhdx file.
    • disk_number: The disk index.
    resource "hyperv_machine_instance" "example" {
      name = "WebServer"
    
      network_adaptors {
        name        = "wan"
        switch_name = "DMZ"
      }
    
      hard_disk_drives {
        controller_type     = "Scsi"
        controller_number  = "0"
        controller_location = "0"
        path                = "C:\\path\\to\\disk.vhdx"
      }
    }
  11. Configure the hyperv provider

    master

    To use the hyperv provider, you must configure the provider "hyperv" block with connection details for your Hyper-V host. You can provide these settings directly in the Terraform configuration or via environment variables.

    Common configuration options include:

    • user: The username for API calls (defaults to Administrator).
    • password: The password for the user.
    • host: The target host (defaults to 127.0.0.1).
    • port: The port for API calls (defaults to 5986).
    • https: Whether to use HTTPS (defaults to true).
    • insecure: Whether to skip TLS verification (defaults to false). Use this for self-signed certificates if necessary.
    • use_ntlm: Whether to use NTLM for authentication (defaults to true).
    • timeout: Connection timeout string (e.g., 30s, 5m). Defaults to 30s.
    # Configure HyperV
    provider "hyperv" {
      user            = "Administator"
      password        = "P@ssw0rd"
      host            = "127.0.0.1"
      port            = 5986
      https           = true
      insecure        = false
      use_ntlm        = true
      tls_server_name = ""
      cacert_path     = ""
      cert_path       = ""
      key_path        = ""
      script_path     = "C:/Temp/terraform_%RAND%.cmd"
      timeout         = "30s"
    }