【问题标题】:Terraform Windows server 2016 adding and running scripts using wineryTerraform Windows server 2016 使用酒厂添加和运行脚本
【发布时间】:2021-11-22 04:59:52
【问题描述】:

我需要在 windows server 2016 中添加一个 powershell 脚本,然后运行以安装特定程序。

我使用的代码将仅用于创建 Windows 机器,因为其余部分只是默认设置。

resource "azurerm_windows_virtual_machine" "vm-clt" {
  count = local.VMInstance
  name                        = "windows${count.index + 1}"
  location                    = var.location
  availability_set_id         = azurerm_availability_set.avset.id
  resource_group_name         = var.resource_group_name
  network_interface_ids       = [element(azurerm_network_interface.nic_vm.*.id, count.index)]
  size                        = "Standard_B1s"
  admin_username              = var.username
  admin_password              = var.adminpassword
  enable_automatic_updates    = "false"
  provision_vm_agent          = "true"
  depends_on                  = [azurerm_network_interface.nic_vm]

  source_image_reference {
    publisher = "MicrosoftWindowsServer"
    offer     = "WindowsServer"
    sku       = "2016-Datacenter"
    version   = "latest"
  }

  os_disk {
    name              = lower("${local.prefixStorageName}${count.index + 1}")
    caching           = "ReadWrite"
    storage_account_type  = "Premium_LRS"
  }
provisioner "file" {
  source      = "Agent.ps1"
  destination = "C:/Windows/Temp/Agent.ps1"

  connection {
    type     = "winrm"
    port = "5985"
    https = false
    insecure = true 
    user     = var.username
    password = var.adminpassword
    host     = "${element(azurerm_public_ip.pip_vm.*.ip_address, count.index)}"
    timeout  = "5m" 
  }
}

  provisioner "remote-exec" {
inline = [         
           "powershell.exe -ExecutionPolicy Bypass -File C:\\Windows\\Temp\\Agent.ps1  -APIKey 2b076e91c7xxxxxxxx4fd25a094dce"
     ]
    connection {
      type     = "winrm"
      user     = var.username
      password = var.adminpassword
      host     = "${element(azurerm_public_ip.pip_vm.*.ip_address, count.index)}"
      timeout  = "5m" 
    }
  }
}

我在部署时收到的错误是:timeout - last error: unknown error Post "http://XXX.XXX.XXX.XXX:5985/wsman": dial tcp XXX.XXX.XXX.XXX:5985:输入输出超时

注意:该错误仅在 terraform apply 期间可用

【问题讨论】:

    标签: terraform-provider-azure windows-server-2016 winrm


    【解决方案1】:

    您在azurerm_windows_virtual_machine 中缺少一些配置,例如winrm_listneradditional_unattend_content。也不确定您是否为WinRm 端口添加了 NSG。

    所以,在做了一些修改之后,我用下面的脚本进行了测试:

    provider "azurerm"{
      features{}
    }
    
    variable "admin_username" {
        type = string
        default = "adminuser"
    }
    
    variable "admin_password" {
        type = string
        default = "Paassworrdd@12344"
    }
    data "azurerm_resource_group" "example" {
      name     = "ansumantest"
    }
    
    resource "azurerm_virtual_network" "example" {
      name                = "example-network"
      address_space       = ["10.0.0.0/16"]
      location            = data.azurerm_resource_group.example.location
      resource_group_name = data.azurerm_resource_group.example.name
    }
    
    resource "azurerm_subnet" "example" {
      name                 = "internal"
      resource_group_name  = data.azurerm_resource_group.example.name
      virtual_network_name = azurerm_virtual_network.example.name
      address_prefixes     = ["10.0.2.0/24"]
    }
    resource "azurerm_public_ip" "windows_pip" {
      name                = "examplevm-PIP"
      location            = data.azurerm_resource_group.example.location
      resource_group_name = data.azurerm_resource_group.example.name
      allocation_method   = "Static"
    }
    resource "azurerm_network_security_group" "windows_nsg" {
      name                = "exampleVM-NSG"
      location            = data.azurerm_resource_group.example.location
      resource_group_name = data.azurerm_resource_group.example.name
    
      security_rule {
        name                       = "RDP"
        priority                   = 100
        direction                  = "Inbound"
        access                     = "Allow"
        protocol                   = "Tcp"
        source_port_range          = "*"
        destination_port_range     = "3389"
        source_address_prefix      = "*"
        destination_address_prefix = "*"
      }
      security_rule {
        name                       = "WinRM"
        priority                   = 110
        direction                  = "Inbound"
        access                     = "Allow"
        protocol                   = "Tcp"
        source_port_range          = "*"
        destination_port_range     = "5985"
        source_address_prefix      = "*"
        destination_address_prefix = "*"
      }
      security_rule {
        name                       = "HTTP"
        priority                   = 120
        direction                  = "Inbound"
        access                     = "Allow"
        protocol                   = "Tcp"
        source_port_range          = "*"
        destination_port_range     = "80"
        source_address_prefix      = "*"
        destination_address_prefix = "*"
      }
    }
    
    resource "azurerm_subnet_network_security_group_association" "example" {
      subnet_id                 = azurerm_subnet.example.id
      network_security_group_id = azurerm_network_security_group.windows_nsg.id
    }
    
    resource "azurerm_network_interface" "example" {
      name                = "example-nic"
      location            = data.azurerm_resource_group.example.location
      resource_group_name = data.azurerm_resource_group.example.name
    
      ip_configuration {
        name                          = "internal"
        subnet_id                     = azurerm_subnet.example.id
        private_ip_address_allocation = "Dynamic"
        public_ip_address_id = azurerm_public_ip.windows_pip.id
      }
    }
    
    resource "azurerm_windows_virtual_machine" "vm_persistent" {
      name                = "vm-persistent"
      resource_group_name = data.azurerm_resource_group.example.name
      location            = data.azurerm_resource_group.example.location
      size                = "Standard_D4_v3"
    
    # Here my variables for User/Password
      admin_username      = var.admin_username
      admin_password      = var.admin_password
      network_interface_ids = [azurerm_network_interface.example.id]
      custom_data = "${filebase64("C:/Users/user/terraform/test/winrm.ps1")}"
      provision_vm_agent = "true" 
      winrm_listener {
          protocol = "Http" 
      }
      os_disk {
        caching              = "ReadWrite"
        storage_account_type = "Standard_LRS"
      }
      source_image_reference {
        publisher = "MicrosoftWindowsServer"
        offer     = "WindowsServer"
        sku       = "2016-Datacenter"
        version   = "latest"
      }
      additional_unattend_content {
          setting      = "AutoLogon"
          content      = "<AutoLogon><Password><Value>${var.admin_password}</Value></Password><Enabled>true</Enabled><LogonCount>1</LogonCount><Username>${var.admin_username}</Username></AutoLogon>"
      }
      additional_unattend_content {
          setting      = "FirstLogonCommands"
          content      = "${file("C:/Users/user/terraform/test/firstlogincommand.xml")}"
      }
    provisioner "remote-exec" {
        connection {
          host     = azurerm_public_ip.windows_pip.ip_address
          type     = "winrm"
          port     = 5985
          https    = false
          timeout  = "5m"
          user     = var.admin_username
          password = var.admin_password
        }
        inline = [
          "powershell.exe -ExecutionPolicy Unrestricted -Command {Install-WindowsFeature -name Web-Server -IncludeManagementTools}",
        ]
    }
    }
    

    FirstLogincommand.xml 文件

    <FirstLogonCommands>
        <SynchronousCommand>
            <CommandLine>cmd /c "copy C:\AzureData\CustomData.bin C:\winrm.ps1"</CommandLine>
            <Description>Move the CustomData file to the working directory</Description>
            <Order>12</Order>
        </SynchronousCommand>
        <SynchronousCommand>
            <CommandLine>powershell.exe -sta -ExecutionPolicy Unrestricted -file C:\winrm.ps1</CommandLine>
            <Description>Execute the WinRM enabling script</Description>
            <Order>13</Order>
        </SynchronousCommand>
    </FirstLogonCommands>
    

    winrm.ps1

    Write-Host "Delete any existing WinRM listeners"
    winrm delete winrm/config/listener?Address=*+Transport=HTTP  2>$Null
    winrm delete winrm/config/listener?Address=*+Transport=HTTPS 2>$Null
    
    Write-Host "Create a new WinRM listener and configure"
    winrm create winrm/config/listener?Address=*+Transport=HTTP
    winrm set winrm/config/winrs '@{MaxMemoryPerShellMB="0"}'
    winrm set winrm/config '@{MaxTimeoutms="7200000"}'
    winrm set winrm/config/service '@{AllowUnencrypted="true"}'
    winrm set winrm/config/service '@{MaxConcurrentOperationsPerUser="12000"}'
    winrm set winrm/config/service/auth '@{Basic="true"}'
    winrm set winrm/config/client/auth '@{Basic="true"}'
    
    Write-Host "Configure UAC to allow privilege elevation in remote shells"
    $Key = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System'
    $Setting = 'LocalAccountTokenFilterPolicy'
    Set-ItemProperty -Path $Key -Name $Setting -Value 1 -Force
    
    Write-Host "turn off PowerShell execution policy restrictions"
    Set-ExecutionPolicy -ExecutionPolicy Unrestricted
    
    Write-Host "Configure and restart the WinRM Service; Enable the required firewall exception"
    Stop-Service -Name WinRM
    Set-Service -Name WinRM -StartupType Automatic
    netsh advfirewall firewall set rule name="Windows Remote Management (HTTP-In)" new action=allow localip=any remoteip=any
    Start-Service -Name WinRM
    

    输出:

    【讨论】:

    • 谢谢@AnsumanBal-MT 我还有其他问题需要解决,这就是我无法更快响应的原因。该解决方案有效,我可以执行 powershell 脚本
    • Np @Igor,很高兴能帮上忙!!
    猜你喜欢
    • 1970-01-01
    • 2022-01-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-10
    • 2020-06-01
    • 2018-01-09
    • 1970-01-01
    相关资源
    最近更新 更多