Virtual Machine Extension in Terraform, error due to Version - azure

Below is the script. trying on windows machine.
resource "azurerm_virtual_machine_extension" "VMextn1" {
name = "avmextn1"
virtual_machine_id = azurerm_windows_virtual_machine.vm.id
publisher = "Microsoft.Compute"
type = "CustomScriptExtension"
type_handler_version = "1.10"
auto_upgrade_minor_version = true
settings = <<SETTINGS
{
"fileUris": ["https://storageforiotscripts.blob.core.windows.net/nodejsscript/installNodeJS.ps1"],
"commandToExecute": "powershell -ExecutionPolicy Unrestricted -file installNodeJS.ps1"
}
SETTINGS
}
Tried changing versions to 1.1,1.5,1.9,2.0... and also auto_upgrade_minor_version to false.
Its throwing the following error in the image attached Cannot update handler version or autoUpgradeMinorVerison and a conflict of other extensions with typeHandler version 1.9 and autoUpgradeMinorVerison = false :

According to my research it is not an version error, It is an extension and resource name error.
ErrorMessage: Cannot update handlerVersion or autoUpgradeMinorVersion for VM extension 'CustomScriptExtension'. Change is in conflict with other extensions under handler 'Microsoft.Compute.CustomScriptExtension', with typeHandler version '1.9' and autoUpgradeMinorVersion 'False'.
The above error indicates Custom Script Extension has already been installed as a resource name on the virtual machine.
You might be giving CustomScriptExtension a different resource name than Microsoft.Compute.CustomScriptExtension
-Ensure that the resource name is correct. The resource name can be anything. But, if the Custom Script Extension has already been set up, you can use the same extension for further steps of execution or else you can remove the previous extension if you using new or different extension.
Reference:
Debug PowerShell scripts run by Custom Script Extension or Run Command - Virtual Machines | Microsoft Docs

Related

Provisioning Script using CustomScriptExtension on Windows2019 Fails

I'm trying to wrap my brain around an issue with either the TF Code, or me. I've got a VM Set that I'm mapping over, and on each one, I have a CustomScriptExtension that should install Docker on the VMs.
When I run the plan, it builds the VMs, and the Custom Script runs, however when I RDP into the machine, and attempt a docker info It's telling me that docker isn't installed.
A quick cursory glance of C:\Packages\Plugins\Microsoft.Compute.CustomScriptExtension\1.*\Downloads\ Shows that the installer script is indeed being downloaded, but it doesn't seem to be installing.
Here's the AzureRM Resource (Sanitized):
resource "azurerm_virtual_machine_extension" "bootstrap-scripts" {
for_each = local.XXXXXX
name = "${each.key}-bootstrap"
virtual_machine_id = module.XXXXXXXX[each.key].virtual_machine_id
publisher = "Microsoft.Compute"
type = "CustomScriptExtension"
type_handler_version = "1.10"
settings = <<SETTINGS
{
"commandToExecute" : "powershell -ExecutionPolicy Unrestricted -File install-docker-ce.ps1",
"fileUris" : ["https://raw.githubusercontent.com/microsoft/Windows-Containers/Main/helpful_tools/Install-DockerCE/install-docker-ce.ps1"]
}
SETTINGS
}
And the output from the log at C:\WindowsAzure\Logs\Plugins\Microsoft.Compute.CustomScriptExtension
[
{
"version":"1",
"timestampUTC":"2022-10-21T20:03:44.6989395Z",
"status":{"name":"powershell -ExecutionPolicy Unrestricted -File install-docker-ce.ps1",
"operation":"Command Execution Finished",
"status":"success",
"code":0,
"formattedMessage":{
"lang":"en-US",
"message":"Command execution finished"
},
"substatus":[
{
"name":"StdOut",
"status":"success",
"code":0,"formattedMessage":{
"lang":"en-US",
"message":"Querying status of Windows feature: Containers...\r\nEnabling feature Containers...\r\nWARNING: You must restart this server to finish the installation process.\r\nRestart is required; restarting now...\r\nCreating scheduled task action (C:\\Packages\\Plugins\\Microsoft.Compute.CustomScriptExtension\\1.10.12\\Downloads\\0\\install-docker-ce.ps1 )...\r\nCreating scheduled task trigger...\r\nRegistering script to re-run at next user logon...\r\n"
}
},
{
"name":"StdErr",
"status":"success",
"code":0,
"formattedMessage":{
"lang":"en-US",
"message":"Register-ScheduledTask : No mapping between account names and security IDs was done.\r\n(12,8):UserId:\r\nAt C:\\Packages\\Plugins\\Microsoft.Compute.CustomScriptExtension\\1.10.12\\Downloads\\0\\install-docker-ce.ps1:150 char:5\r\n+ Register-ScheduledTask -TaskName $global:BootstrapTask -Action $a ...\r\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n + CategoryInfo : NotSpecified: (PS_ScheduledTask:Root/Microsoft/...S_ScheduledTask) [Register-ScheduledTa \r\n sk], CimException\r\n + FullyQualifiedErrorId : HRESULT 0x80070534,Register-ScheduledTask\r\n \r\n"
}
}
]
}
}
]
from what I'm reading, it seems to set up the scheduled task to reboot the server, but it looks like it never does? However even after a manual restart, it's still not installed.
Can anyone shed some light on this?
EDIT: I forgot to mention that I cannot use anything out of the Azure Public Marketplace, in case someone wanted to mention using a premade image. I am relegated to using images that are stored in our private collection

"Future#WaitForCompletion" while running a powershell script from GitHub - Terraform

I have a powershell script present in GitHub and using it in the "Settings" block inside "azurerm_virtual_machine_extension" to configure the Windows Server VM. Below is the code.
resource "azurerm_virtual_machine_extension" "iis-windows-vm" {
depends_on = [azurerm_windows_virtual_machine.web-windows-vm]
name = "win-${random_string.random-win-vm.result}-vm-extn"
virtual_machine_id = azurerm_windows_virtual_machine.web-windows-vm.id
publisher = "Microsoft.Compute"
type = "CustomScriptExtension"
type_handler_version = "1.9"
settings = <<SETTINGS
{
"commandToExecute": "powershell -ExecutionPolicy Unrestricted -File demo.ps1",
"fileUris": ["https://raw.githubusercontent.com/Configure/app/master/demo.ps1"]
}
SETTINGS
}
And the below are the content of "demo.ps1"
New-LocalUser "ansible" -Password (ConvertTo-SecureString -AsPlainText -Force ) -AccountNeverExpires:$true -PasswordNeverExpires:$true -FullName "ansible" | Add-LocalGroupMember -Group administrators
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$url = "https://raw.githubusercontent.com/ansible/ansible/devel/examples/scripts/ConfigureRemotingForAnsible.ps1"
$file = "$env:temp\ConfigureRemotingForAnsible.ps1"
(New-Object -TypeName System.Net.WebClient).DownloadFile($url, $file)
powershell.exe -ExecutionPolicy ByPass -File $file
Install-WindowsFeature -Name Web-Server -IncludeAllSubFeature -IncludeManagementTools
When I do "terraform apply", below error is displayed.
Error: Future#WaitForCompletion: context has been cancelled: StatusCode=200 -- Original Error: context deadline exceeded
The code was working fine until now. Not able to figure out the problem here. Request you assist me to make this work.
The error Original Error: context deadline exceeded means that we ran into a situation where a given action was not completed in an expected timeframe.
So there can be a handful of reason why you are encountering the execution timeout like Network Latency, Slow I/O, Firewall Rules and many more. One possible reason that I think is the URL is not responding as expected or it's taking to much time to respond.
Before being able to solve the problem, you need to determine what is actually failing. I would suggest to check the detailed terraform log file to find the reason of timeout.
But even after checking you find is good and you are still facing the issue then with v2.0 of the AzureRM Provider it is possible to add custom timeouts using timeouts block as shown in the example snippet below.
resource "azurerm_resource_group" "example" {
name = "example-resource-group"
location = "West Europe"
timeouts {
create = "10m"
delete = "30m"
}
}
For more information check this Custom Timeouts for Resources section of the terraform document.

Terraform Azure VM Extension Custom Script from Local Script

I'm trying to deploy Azure Windows VM with VM extension by Terraform that will install ADDS role for the Windows VM.
I have one Powershell script file for the installation named install_adds.ps1 from my local machine
The Terraform file of VM Extension as below:
resource "azurerm_virtual_machine_extension" "main" {
name = "extensionTest"
virtual_machine_id = azurerm_virtual_machine.main.id
publisher = "Microsoft.Azure.Extensions"
type = "CustomScript"
type_handler_version = "2.0"
settings = <<SETTINGS
{
"commandToExecute": "powershell.exe ./install_adds.ps1"
}
SETTINGS
}
I have deployed the VM Extension Terraform file but not working
I think my Terraform file syntax is wrong and the Windows does not run my PowerShell script.
Any way can run my local PowerShell Script by Terraform VM Extension file?
Based on the schemas you posted, you might be trying to deploy the wrong customer script extension (CSE for Linux VM) on Windows based VM.
Below extensions schemas what you could use depending on the OS:
Linux:
"publisher": "Microsoft.Azure.Extensions",
"type": "CustomScript",
"typeHandlerVersion": "2.1",
Windows:
"publisher": "Microsoft.Compute",
"type": "CustomScriptExtension",
"typeHandlerVersion": "1.10",
You used on Windows:
publisher = "Microsoft.Azure.Extensions"
type = "CustomScript"
type_handler_version = "2.0"

How to run custom scripts post terraform vmware vm deployment?

I have been researching on this topic for over a week now and couldn't find any good solution neither on terraform documentation site nor on the web.
Main issue trying to solve right now is: how to run a custom powershell script at the end of terraform vmware basic windows server 2016 vm build.
Tried following methods:
remote-exec - fail
provisioners inside vm resource definition - fail
null resource - Error: timeout - last error: http response error: 401 - invalid content type
Here's my null resource definition right below vm resource build within the same main.tf file
resource "null_resource" "vm" {
triggers = {
public_ip = <host ip address>
}
connection {
type = "winrm"
host = <host ip address>
user = <username>
password = <password>
agent = false
}
provisioner "file" {
source = "userdata.ps1"
destination = "C:/Windows"
}
provisioner "remote-exec" {
inline = [
"powershell.exe -ExecutionPolicy Bypass -File C:/Windows/userdata.ps1"
]
}
}
Please suggest what are the recommended practices and your working solution

Terraform and Azure: Unable to provision Storage Account

I am trying to provision a storage account but running it results in error:
Error: Error reading static website for AzureRM Storage Account "sa12345461234512name":
accounts.Client#GetServiceProperties:
Failure responding to request: StatusCode=403 -- Original Error: autorest/azure:
Service returned an error. Status=403 Code="AuthorizationPermissionMismatch"
Message="This request is not authorized to perform this operation using this permission.\n
RequestId:05930d46-301e-00ac-6d72-f021f0000000\n
Time:2020-03-02T09:09:44.9417598Z"
Running OS Windows 10 Pro.
Steps to replicate (in Powershell with Azure CLI installed)
az login
mkdir dummyFolder
cd dummyFolder
create config.tf
terraform init
terraform plan
terraform apply -auto-approve
Config.tf contents
# Configure the Azure Provider
provider "azurerm" {
version = "=2.0.0"
features {}
}
resource "azurerm_resource_group" "example" {
name = "example-resources"
location = "Australia East"
}
resource "azurerm_storage_account" "example" {
name = "sa12345461234512name"
resource_group_name = azurerm_resource_group.example.name
location = azurerm_resource_group.example.location
account_tier = "Standard"
account_replication_type = "LRS"
tags = {
environment = "staging"
}
}
Not sure what i am missing, all other resources work fine, just the storage account.
This is a bug in the azure provider, see: https://github.com/terraform-providers/terraform-provider-azurerm/issues/5869
Update your provider; it doesn't seem to be related to the terraform version.
From:
# Configure the Azure Provider
provider "azurerm" {
# whilst the `version` attribute is optional, we recommend pinning to a given version of the Provider
version = "=2.0.0"
features {}
}
To:
provider "azurerm" {
version = "~> 2.1.0"
features {}
}
Just to add to this since none of above worked. In my case it first didn't work, then next day worked just to not work again in the evening... Not changing versions or anything, was same computer.
It turned out that my time settings on my Ubuntu running in Windows was skewed. Just simply running a sudo ntpdate time.nist.gov to update time solved the problem.
Found the issue. Its got to do with Terraform.
Just checked for updates and notices 0.12.21 is out (I was runnning 0.12.20).
Seems like if running AzureARM 2.0.0 then really need to be min 0.12.21 to make it work.
Same problem as #tesharp experienced.
On my Ubuntu WSL2 the following command fixed the problem:
sudo hwclock -s

Resources