【问题标题】:Unable to execute custom data in azure VM from terraform无法从 terraform 在 azure VM 中执行自定义数据
【发布时间】:2017-12-29 14:59:29
【问题描述】:

我正在尝试使用 terraform 创建 azure vm。但无法从 terraform 执行自定义数据。在服务器上创建 Customdata.bin 文件。 也尝试了供应商资源,但没有运气。

main.tf 文件 azure vm 资源语法:

resource "azurerm_virtual_machine" "avmweb0" {
  name                  = "${var.env}-${var.bu}-${var.company_name}-media-vm"
  location              = "${var.region}"
  resource_group_name   = "${module.network.resource-grp-name}"
  network_interface_ids = ["${azurerm_network_interface.nicweb0.id}"]
  vm_size               = "${var.vm_size}"


  storage_image_reference {
    publisher       = "${var.vm_publisher}"
    offer           = "${var.vm_offer}"
    sku             = "${var.vm_sku}"
    version         = "${var.vm_version}"

  }

  storage_os_disk {
    name              = "${var.env}-${var.bu}-${var.company_name}-media-osdisk"
    caching           = "ReadWrite"
    create_option     = "FromImage"
    managed_disk_type = "Standard_LRS"
  }



  os_profile {
    computer_name  = "${var.env}-${var.vm_computer_name}"
    admin_username = "${var.vm_admin_username}"
    admin_password = "${var.vm_admin_password}"
    custom_data    = "${data.template_file.userdata.rendered}" 
  }

   os_profile_windows_config{
     winrm {
       protocol="http"
     }

    }

   /* 
     connection {
      type     = "winrm"
      user     = "${var.vm_admin_username}"
      password = "${var.vm_admin_password}"
      host     = "${azurerm_public_ip.mediapubip.ip_address}"
      port     = 5985
      https    = false
      insecure = true
      timeout      = "15m"
      # cacert       = ""
    } */

   /* provisioner "file" {
    content      = "${data.template_file.userdata.rendered}"
    destination = "C:\\AzureData\\initdata.ps1"

    connection {
      type     = "winrm"
      user     = "${var.vm_admin_username}"
      password = "${var.vm_admin_password}"
    }
  }
   provisioner "remote-exec" {


    inline = [ "powershell.exe -ExecutionPolicy unrestricted -NoProfile -NonInteractive -File \"C:\\AzureData\\initdata.ps1\""]


  }  */

  /* provisioner "file" {
    content      = "${data.template_file.userdata.rendered}"
    destination = "C:\\AzureData\\initdata.ps1"
  }

   provisioner "local-exec" {
    command = "powershell.exe -ExecutionPolicy RemoteSigned -File \"C:\\AzureData\\initdata.ps1\" -NoProfile -NonInteractive "
  } */

  tags {
        Name            = "${var.env}-${var.bu}-${var.company_name}-media"
        BussinessUnit   = "${var.bu}"
        Environment     = "${var.env}"
        CompanyName     = "${var.company_name}"
        Application     = "${var.appname}"
   }
}

------------自定义数据文件-------------------------------- -

Set-ExecutionPolicy unrestricted
netsh advfirewall firewall add rule name="http" dir=in action=allow protocol=TCP localport=80

write-host "running init script"
if(!(test-path -Path "c:\temp"))
  {    
    New-Item -ItemType directory -Path "C:\temp"
    write-host "created temp directory"
  }
$client = new-object System.Net.WebClient
$client.DownloadFile("https://downloads.puppetlabs.com/windows/puppet5/puppet-agent-5.0.0-x64.msi","c:\temp\puppet.msi")
cd "c:\temp"
pwd
echo "`nx.x.x.x puppet"  | Out-File -FilePath "C:\Windows\System32\drivers\etc\hosts" -Append -Encoding ascii
msiexec /qn /norestart /i "c:\temp\puppet.msi" 
if(test-path -path "C:\ProgramData\PuppetLabs\facter\facts.d")
  {
    echo "`nhello"  | Out-File -FilePath "C:\ProgramData\PuppetLabs\facter\facts.d\facts.yaml" -Encoding ascii
    echo "`nconsolename : ${consolename}" | Out-File -FilePath "C:\ProgramData\PuppetLabs\facter\facts.d\facts.yaml" -Append -Encoding ascii
    echo "`nbu : ${bu}" | Out-File -FilePath "C:\ProgramData\PuppetLabs\facter\facts.d\facts.yaml" -Append -Encoding ascii
    echo "`nenv : ${env}" | Out-File -FilePath "C:\ProgramData\PuppetLabs\facter\facts.d\facts.yaml" -Append -Encoding ascii            
    echo "`ncompany_name : ${company_name}" | Out-File -FilePath "C:\ProgramData\PuppetLabs\facter\facts.d\facts.yaml" -Append -Encoding ascii
    echo "`napplication : ${application}" |  Out-File -FilePath "C:\ProgramData\PuppetLabs\facter\facts.d\facts.yaml" -Append -Encoding ascii
    echo "`nservertype : ${servertype}" |  Out-File -FilePath "C:\ProgramData\PuppetLabs\facter\facts.d\facts.yaml" -Append -Encoding ascii
 }

使用供应商资源时出错: 发生 1 个错误:

  • azurerm_virtual_machine.avmweb0: 发生 1 个错误:

  • 未知错误 Post http://x.x.x.x:5985/wsman: dial tcp xxxx:5985: connectex: 连接尝试失败,因为连接方在一段时间后没有正确响应,或者建立连接失败,因为连接的主机没有响应.

Terraform 在遇到错误时不会自动回滚。 相反,您的 Terraform 状态文件已部分更新为 任何成功完成的资源。请解决错误 并再次申请以逐步更改您的基础架构。[0m[0m

代码:

resource "azurerm_virtual_machine_extension" "avmme0" {
  name                 = "${var.env}-${var.vm_computer_name}-config"
  location             = "West US"
  resource_group_name  = "${module.network.resource-grp-name}"
  virtual_machine_name = "${azurerm_virtual_machine.avmweb0.name}"
  publisher            = "Microsoft.Compute"
  type                 = "CustomScriptExtension"
  type_handler_version = "1.8"

  settings = <<SETTINGS
    {
        "fileUris": ["https://raw.githubusercontent.com/saveshnshetty/devops/master/userdata.ps1"],
        "commandToExecute": "powershell.exe -ExecutionPolicy unrestricted -NoProfile -NonInteractive -File userdata.ps1"
    }
SETTINGS

  tags {
        Name            = "${var.env}-${var.bu}-${var.company_name}-media"
        BussinessUnit   = "${var.bu}"
        Environment     = "${var.env}"
        CompanyName     = "${var.company_name}"
        Application     = "${var.appname}"
   }
}

错误: [0m[1mazurerm_virtual_machine_extension.avmme0:仍在创建...(经过 25m20s)[0m[0m [31mError应用计划:

发生了 1 个错误:

  • azurerm_virtual_machine_extension.avmme0:发生 1 个错误:

  • azurerm_virtual_machine_extension.avmme0:compute.VirtualMachineExtensionsClient#CreateOrUpdate:发送请求失败:StatusCode=200 -- 原始错误:长时间运行的操作因状态“失败”而终止:代码=“VMAgentStatusCommunicationError”消息=“VM 'dev- it-mactores-media-vm' 没有报告 VM 代理或扩展的状态。请验证 VM 是否有正在运行的 VM 代理,并且可以建立到 Azure 存储的出站连接。”

我可以使用以下命令从服务器下载: $client = 新对象 System.Net.WebClient $client.DownloadFile("https://raw.githubusercontent.com/saveshnshetty/devops/master/userdata.ps1","c:\temp\userdata.ps1")

对 5985 开放入站和出站规则。

Tf var file  details :
region                  ="West US"
storage_account_type    =""
vm.size                 ="Standard_DS1_v2"
location                ="West US"
appname                 ="xxx"
bu                      ="it"
company_name            ="xxxx"
env                     ="dev"
tenant_id               =""
client_secret           =""
client_id               =""
storage_account_type    ="Standard_LRS"
vm_size                 = "Standard_DS1_v2"
vm_publisher            = "MicrosoftWindowsServer"
vm_offer                = "WindowsServer"
vm_sku                  = "2012-R2-Datacenter"
vm_version              = "latest"
vm_computer_name        = "web-media"
vm_admin_username       = "xxxx"
vm_admin_password       = "xxxx"

【问题讨论】:

  • 那么问题出在哪里?有一堵代码和配置墙,但没有错误或描述发生了什么以及应该发生什么。
  • 当我在 azure vm 资源中仅运行自定义数据脚本时,不会从 terraform 端抛出任何错误。但是当我执行provisioner资源时它会抛出错误。
  • 请编辑问题并在问题本身中添加错误详细信息。不要将它们添加为 cmets。
  • @sarveshshetty 您可以使用 Azure 自定义脚本扩展来执行此操作,请参考我的回答。

标签: powershell azure terraform


【解决方案1】:

错误日志的原因是您没有在 Azure NSG 上打开端口 5985。因此,您的脚本无法连接到 Azure VM。对于 Azure VM,我建议您可以使用 Custom Script Extension 而不是 winrm 您的 VM。

自定义脚本扩展在 Azure 上下载和执行脚本 虚拟机。此扩展对后期部署很有用 配置、软件安装或任何其他配置 / 管理任务。

Terraform 还支持自定义脚本扩展。请参考此link。根据您的情况,我建议您将自定义数据保存为 ps1 文件,然后将其上传到 GitHub 或 Azure 存储帐户。你可以参考我的answer。 Windows 自定义脚本扩展应使用如下:

resource "azurerm_virtual_machine_extension" "test" {
  name                 = "hostname"
  location             = "West US"
  resource_group_name  = "${azurerm_resource_group.test.name}"
  virtual_machine_name = "${azurerm_virtual_machine.test.name}"
  publisher            = "Microsoft.Compute"
  type                 = "CustomScriptExtension"
  type_handler_version = "1.8"

   settings = <<SETTINGS
    {
        "fileUris": ["https://raw.githubusercontent.com/saveshnshetty/devops/master/userdata.ps1"],
        "commandToExecute": "powershell.exe -ExecutionPolicy unrestricted -NoProfile -NonInteractive -File userdata.ps1"
    }
SETTINGS

你可以查看我的vm.tf

【讨论】:

  • 谢谢沃尔特!!我尝试了自定义扩展脚本并在自定义数据脚本中调用 *.ps1 文件,但没有运气!!
  • @sarveshshetty 这是您自己的 VHD 映像和 Azure 映像?我将在我的实验室进行测试。
  • 在上面添加了问题。
  • 这是蔚蓝图片
  • 在上面添加了 tf var 文件详细信息。
猜你喜欢
  • 2021-02-20
  • 2021-06-14
  • 1970-01-01
  • 1970-01-01
  • 2019-11-15
  • 1970-01-01
  • 2019-08-16
  • 2021-06-26
  • 1970-01-01
相关资源
最近更新 更多