Terraform azurerm_virtual_machine_extension,使用CustomScriptExtension运行本地PowerShell脚本

jljoyd4f  于 2023-05-07  发布在  Shell
关注(0)|答案(4)|浏览(253)

如何在terraform azurerm_virtual_machine_extension中运行本地(不存储到blob存储帐户)PowerShell脚本
文件夹具有

  1. main.tf
  2. install.ps1
    资源“azurerm_virtual_machine_extension”“software”{ name =“install-software”resource_group_name = azurerm_resource_group.azrg.name virtual_machine_id = azurerm_virtual_machine.vm.id publisher =“Microsoft.Compute”type =“CustomScriptExtension”type_handler_version =“1.9”
settings = <<SETTINGS
    { 
      "commandToExecute": "powershell -ExecutionPolicy Unrestricted -File \"install.ps1\""
    } 
    SETTINGS
}

但是失败了

[
        {
            "code": "ComponentStatus/StdOut/succeeded",
            "level": "Info",
            "displayStatus": "Provisioning succeeded",
            "message": "Windows PowerShell \r\nCopyright (C) Microsoft Corporation. All rights reserved.\r\n\r\n"
        },
        {
            "code": "ComponentStatus/StdErr/succeeded",
            "level": "Info",
            "displayStatus": "Provisioning succeeded",
            "message": "The argument 'install.ps1' to the -File parameter does not exist. Provide the path to an existing '.ps1' file as an argument to the -File parameter.\r\n"
        }
    ]

任何线索
谢谢

k4emjkb1

k4emjkb11#

这对我很有效。

resource "azurerm_virtual_machine_extension" "software" {
  name                 = "install-software"
  resource_group_name  = azurerm_resource_group.azrg.name
  virtual_machine_id   = azurerm_virtual_machine.vm.id
  publisher            = "Microsoft.Compute"
  type                 = "CustomScriptExtension"
  type_handler_version = "1.9"

  protected_settings = <<SETTINGS
  {
    "commandToExecute": "powershell -command \"[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${base64encode(data.template_file.tf.rendered)}')) | Out-File -filepath install.ps1\" && powershell -ExecutionPolicy Unrestricted -File install.ps1"
  }
  SETTINGS
}

data "template_file" "tf" {
    template = "${file("install.ps1")}"
}
dwbf0jvd

dwbf0jvd2#

这里有一个更漂亮的解决方案,基于gsgill76's answer。注意,我们应该使用textencodebase64(Terraform〉= v0.14),因为它允许指定Unicode编码,这是
powershell -encodedCommand

resource "azurerm_virtual_machine_extension" "software" {
  name                 = "install-software"
  resource_group_name  = azurerm_resource_group.azrg.name
  virtual_machine_id   = azurerm_virtual_machine.vm.id
  publisher            = "Microsoft.Compute"
  type                 = "CustomScriptExtension"
  type_handler_version = "1.9"

  protected_settings = <<SETTINGS
  {
     "commandToExecute": "powershell -encodedCommand ${textencodebase64(file("install.ps1"), "UTF-16LE")}"
  }
  SETTINGS
}
jc3wubiy

jc3wubiy3#

我设法从数据“template_file”中获取参数,并将其传递到PowerShell命令行中,以便在服务器上执行,如果这对任何人都有帮助的话。
在我的情况下,证书实际上并不需要,但我还是想通过。在我的情况下,信用是从Azure中的VM设置中获取的。

resource "azurerm_virtual_machine_extension" "software" {
  name                 = "install-software"
#  resource_group_name  = azurerm_resource_group.main.name
  virtual_machine_id   = azurerm_windows_virtual_machine.ADVM1.id
  publisher            = "Microsoft.Compute"
  type                 = "CustomScriptExtension"
  type_handler_version = "1.9"

  protected_settings = <<SETTINGS
  {    
    "commandToExecute": "powershell -command \"[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${base64encode(data.template_file.DomainControllerSetup.rendered)}')) | Out-File -filepath DomainControllerSetup.ps1\" && powershell -ExecutionPolicy Unrestricted -File DomainControllerSetup.ps1 -DomainName ${data.template_file.DomainControllerSetup.vars.DomainName} -AdmincredsUserName ${data.template_file.DomainControllerSetup.vars.AdmincredsUserName} -AdmincredsPassword ${data.template_file.DomainControllerSetup.vars.AdmincredsPassword}" 
  }
  
  SETTINGS
}

data "template_file" "DomainControllerSetup" {
    template = "${file("DomainControllerSetup.ps1")}"
    vars = {
        DomainName              = "azlab.local"
        AdmincredsUserName      = "${azurerm_windows_virtual_machine.ADVM1.admin_username}"
        AdmincredsPassword      = "${azurerm_windows_virtual_machine.ADVM1.admin_password}"
  }
}

这是我的“创建新森林”脚本-如果有帮助的话。在此示例中不使用信用,仅使用DomainName。然而,我想把它放在那里,以防我想把一个成员服务器提升到一个现有的域中。

[CmdletBinding()]

param 
( 
    [Parameter(ValuefromPipeline=$true,Mandatory=$true)] [string]$DomainName,
    [Parameter(ValuefromPipeline=$true,Mandatory=$true)] [string]$AdmincredsUserName,
    [Parameter(ValuefromPipeline=$true,Mandatory=$true)] [string]$AdmincredsPassword
)

$username = $AdmincredsUserName
$password = ConvertTo-SecureString -AsPlainText $AdmincredsPassword -Force
$Cred = New-Object System.Management.Automation.PSCredential ($username, $password)

install-windowsfeature AD-Domain-Services -IncludeManagementTools

Install-ADDSForest `
-DomainName $DomainName `
-SafeModeAdministratorPassword $password `
-CreateDnsDelegation:$false `
-DatabasePath "C:\Windows\NTDS" `
-InstallDns:$true `
-LogPath "C:\Windows\NTDS" `
-NoRebootOnCompletion:$false `
-SysvolPath "C:\Windows\SYSVOL" `
-Force:$true
yfjy0ee7

yfjy0ee74#

感谢gsgill76提供的工作命令!
下面介绍如何使用函数来支持数据源

locals {
  scriptName     = "install.ps1"
  scriptRendered = filebase64("${path.module}/${local.scriptName}")
  # use templatefile() to parse script parameters
  ifTemplateFile = base64encode(templatefile("${path.module}/${local.scriptName}", {}))
  commandToExecute = jsonencode({
    commandToExecute = "powershell -command \"[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${local.scriptRendered}')) | Out-File -filepath ${local.scriptName}\" && powershell -ExecutionPolicy Unrestricted -File ${local.scriptName}"
  })
}

  # settings block will look like
  protected_settings = local.commandToExecute

path.module * 假定脚本与terraform代码位于同一目录中 *
filebase64
templatefile
jsonencode

相关问题