I need to deploy azure custom script extension.My script is powershell i want to use terraform variable in powershell script. my script works perfectly when i use null resource but i can sent value in azure custom script extension.
my terraform script is below
resource "azurerm_virtual_machine_extension" "example_extension" {
name = "exampleExtension"
virtual_machine_id = azurerm_virtual_machine.example_vm.id
publisher = "Microsoft.Compute"
type = "CustomScriptExtension"
type_handler_version = "1.10"
settings = <<SETTINGS
{
"commandToExecute": "powershell -command "[System.Text.Encoding]::UTF8.GetString([System.Convert]::FromBase64String('${base64encode(file("testing.ps1"))}')) | Out-File -filepath testing.ps1" && powershell -ExecutionPolicy Unrestricted -File testing.ps1 -example_variable '${var.example_variable}'"
}
SETTINGS
}
Powershell script
Param(
[Parameter(Mandatory=$true)]
[string]$example_variable
)
Write-Host "The value of example_variable is: $example_variable"
Getting error on extension
[
{
"code": "ComponentStatus/StdOut/succeeded",
"level": "Info",
"displayStatus": "Provisioning succeeded",
"message": "The value of example_variable is: rnrnrn Directory: C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.10.15\Downloads\0rnrnrnMode LastWriteTime Length Name rn---- ------------- ------ ---- rn-a---- 5/8/2023 1:10 AM 0 .txt rnrnrn"
},
{
"code": "ComponentStatus/StdErr/succeeded",
"level": "Info",
"displayStatus": "Provisioning succeeded",
"message": "?Param : The term '?Param' is not recognized as the name of a cmdlet, function, script file, or operable program. rnCheck the spelling of the name, or if a path was included, verify that the path is correct and try again.rnAt C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.10.15\Downloads\0\testing.ps1:1 char:1rn+ ?Param(rn+ ~~~~~~rn + CategoryInfo : ObjectNotFound: (?Param:String) [], CommandNotFoundExceptionrn + FullyQualifiedErrorId : CommandNotFoundExceptionrn rn"
}
]
i am not using ?param as it is showing me.
Is there any solution to deploy terraform variable in powershell script using microsoft extension.
2
Answers
Check if the file content after powershell execution is fetched properly .
Use
to fetch the powershell file.
Code:
Reference: Terraform azurerm_virtual_machine_extension, run local PowerShell Script using CustomScriptExtension – Stack Overflow
Here, I am storing the required files in storage account and getting the required secrets from keyvault(in my case).
in my file2.ps1, I get those values by
This method works for both linux and windows, and the only change is you have to modify your execution script, according to the os. Hope this helps!