Custome Linux VM Extension on Azure - azure

Ttrying to run .sh script via custome script extension via set-azvmextension but nither its througing an error nor output gettting generated on linux vm.
$resourceGroupName = "abc-RG"
$storageAccountName = "abcdiag"
$containerName = "public"
$location = "Central India"
$vmName = "abclinux2"
$extensionName = "vm_rwq"
$deploymentScript = "dd.sh"
$destintionPath = "/tmp/"
$storageAccountKeys = (Get-AzStorageAccountKey -ResourceGroupName $resourceGroupName -Name $storageAccountName).Value
$storageAccountKey = $storageAccountKeys[0]
$Settings = #{"fileUris" = "[https://abcdiag.blob.core.windows.net/public/dd.sh]"; "commandToExecute" = "sh dd.sh"};
$ProtectedSettings = #{"storageAccountName" = $storageAccountName; "storageAccountKey" = $storageAccountKey};
Set-AzVMExtension -ResourceGroupName $resourceGroupName -Location $location -VMName $vmName >>

If you want to use Azure Custom Script Extension Version 1 with Linux virtual machines, the publisher should be Microsoft.OSTCExtensions and the type should be CustomScriptForLinux. For more details, please refer to the document
For example
$resourceGroupName = ""
$storageAccountName = ""
$location = ""
$vmName = ""
$extensionName = "vm_rwq"
$fileUri = #("https://jimtestperfdiag516.blob.core.windows.net/test/config-music.sh")
$storageAccountKeys = (Get-AzStorageAccountKey -ResourceGroupName "test" -Name $storageAccountName).Value
$storageAccountKey = $storageAccountKeys[0]
$Settings = #{'fileUris' =$fileUri; "commandToExecute" = "./config-music.sh"};
$ProtectedSettings = #{"storageAccountName" = $storageAccountName; "storageAccountKey" = $storageAccountKey};
Set-AzVMExtension -ResourceGroupName $resourceGroupName -Location $location -VMName $vmName -Name $extensionName -Publisher "Microsoft.OSTCExtensions" -Type "CustomScriptForLinux" -TypeHandlerVersion "1.5" -Settings $Settings -ProtectedSettings $ProtectedSettings
Update
According to my research, Azure Custom Script Extension Version 1 does not support Red Hat operating System VM. For more details, please refer to the document
So if you want to install Custom Script Extension on Red Hat VM, we should use the new version: version 2. For further information, please refer to the article. Besides, if you want to use script to install the extension on Azure Linux VM, Azure CLI is a better way.
az vm extension set \
--resource-group myResourceGroup \
--vm-name myVM \
--name customScript \
--publisher Microsoft.Azure.Extensions \
--settings ./script-config.json \
--protected-settings ./protected-config.json
But, if you still want to use PowerShell, please refer to the following script
$resourceGroupName = ""
$storageAccountName = ""
$location = ""
$vmName = ""
$extensionName = "vm_rwq"
$fileUri = #("https://jimtestperfdiag516.blob.core.windows.net/test/config-music.sh")
$storageAccountKeys = (Get-AzStorageAccountKey -ResourceGroupName "test" -Name $storageAccountName).Value
$storageAccountKey = $storageAccountKeys[0]
$Settings = #{'fileUris' =$fileUri; "commandToExecute" = "./config-music.sh"};
$ProtectedSettings = #{"storageAccountName" = $storageAccountName; "storageAccountKey" = $storageAccountKey};
Set-AzVMExtension -ResourceGroupName $resourceGroupName -Location $location -VMName $vmName -Name $extensionName `
-Publisher "Microsoft.Azure.Extensions" -Type "CustomScript" `
-TypeHandlerVersion "2.1" -Settings $Settings -ProtectedSettings $ProtectedSettings

Related

Azure VMs fails as public ip is allocated to other resource

I am using a powershell script to create multiple Vms based on an image. The first Vm is ok but when attempting the second Vm I get an error saying that :
| Resource /subscriptions/....../networkInterfaces/xxxxx/ipConfigurations/xxxxx is referencing public IP address
| /subscriptions/xxxxxxxxx/providers/Microsoft.Network/publicIPAddresses/Microsoft.Azure.Commands.Network.Models.PSPublicIpAddress that is already allocated to
| resource /subscriptions/......./networkInterfaces/xxxxx/ipConfigurations/xxxxx.
Here is the script I am using:
param(
[string] $WeekNo="NoWeek",
[int] $VmCount=0
)
#$cred = Get-Credential -Message "Enter a username and password for the virtual machine."
## VM Account
# Credentials for Local Admin account you created in the sysprepped (generalized) vhd image
$VMLocalAdminUser = "xxxxx"
$VMLocalAdminSecurePassword = ConvertTo-SecureString "xxxxxxx" -AsPlainText -Force
$image = "/subscriptions/xxxxxxx/resourceGroups/xxxxxx/providers/Microsoft.Compute/images/xxxxxxxxx"
## Azure Account
$LocationName = "SwedenCentral"
$ResourceGroupName = "xxxx_" + $WeekNo
if( -Not( Get-AzureRmResourceGroup -Name $ResourceGroupName -Location $LocationName -ErrorAction Ignore)) {
New-AzureRmResourceGroup -Name $ResourceGroupName -Location $LocationName
Write-Host "ResourceGroup" $ResourceGroupName "created"
$VMSize = "Standard_B2ms"
## Networking
$NetworkName = "xxxxxx_" + $WeekNo + "_net" # "MyNet"
$SubnetName = "MySubnet"
$SubnetAddressPrefix = "10.0.0.0/24"
$VnetAddressPrefix = "10.0.0.0/16"
$SingleSubnet = New-AzVirtualNetworkSubnetConfig -Name $SubnetName -AddressPrefix $SubnetAddressPrefix
$Vnet = New-AzVirtualNetwork -Name $NetworkName -ResourceGroupName $ResourceGroupName -Location $LocationName -AddressPrefix $VnetAddressPrefix -Subnet $SingleSubnet
}
$Credential = New-Object System.Management.Automation.PSCredential ($VMLocalAdminUser, $VMLocalAdminSecurePassword);
$VMName = "xxxx" + $WeekNo
##New-AzVM -ResourceGroupName $ResourceGroupName -Location $LocationName -VM $VirtualMachine -Verbose -Image $image
for($i=1; $i -le $VmCount; $i++){
$VMBaseName = "iCPSEDU" + $WeekNo + $i
$StorageAccount = "xxxxx" + $WeekNo + $i
$PublicIPAddressName = $VMBaseName + "PIP$(Get-Random)"
$NICName = $VMBaseName + "NIC"
$DNSNameLabel = "xxxx" + $WeekNo + $i + "dns" # mydnsname.westus.cloudapp.azure.com
$PIP = New-AzPublicIpAddress -Name $PublicIPAddressName -DomainNameLabel $DNSNameLabel -ResourceGroupName $ResourceGroupName -Location $LocationName -AllocationMethod Dynamic
$NIC = New-AzNetworkInterface -Name $NICName -ResourceGroupName $ResourceGroupName -Location $LocationName -SubnetId $Vnet.Subnets[0].Id -PublicIpAddressId $PIP.Id
Write-Host "Creating VM " $VMBaseName
New-AzVm `
-ResourceGroupName $ResourceGroupName `
-Name $VMBaseName `
-ImageName $image `
-Location $LocationName `
-VirtualNetworkName $Vnet `
-SubnetName $SubnetName `
-SecurityGroupName "myImageNSG" `
-PublicIpAddressName $PIP -Credential $Credential -Size $VMSize -PublicIpSku Standard
Write-Host "VM " $VMBaseName " Created"
Stop-AzVM -ResourceGroupName $ResourceGroupName $VMBaseName -Force -NoWait
Write-Host "VM " $VMBaseName " Stopped"
}
Write-Host "Done."`
To me it seems that the variable used for the PIP is not "flushed" properly between the executions but I have no idea on how to do this?
Or is there something else causing the error?
I have tried adding some delays but without effect.
Create a public IP address and specify a DNS name
Create a NSG
Create a NIC and associate with created pub IP address and NSG
Create a virtual machine configuration and assign the NIC
Create the VM with the config
https://github.com/Azure/azure-docs-powershell-samples/blob/master/virtual-machine/create-vm-detailed/create-windows-vm-detailed.ps1
rough summary of important steps:
$pip = New-AzPublicIpAddress -ResourceGroupName $resourceGroup -Location $location `
-Name "mypublicdns$(Get-Random)" -AllocationMethod Static -IdleTimeoutInMinutes 4
$nsg = New-AzNetworkSecurityGroup -ResourceGroupName $resourceGroup -Location $location `
-Name myNetworkSecurityGroup -SecurityRules $nsgRuleRDP
$nic = New-AzNetworkInterface -Name myNic -ResourceGroupName $resourceGroup -Location $location `
-SubnetId $vnet.Subnets[0].Id -PublicIpAddressId $pip.Id -NetworkSecurityGroupId $nsg.Id
$vmConfig = New-AzVMConfig -VMName $vmName -VMSize Standard_D1 | `
Set-AzVMOperatingSystem -Windows -ComputerName $vmName -Credential $cred | `
Set-AzVMSourceImage -PublisherName MicrosoftWindowsServer -Offer WindowsServer -Skus 2016-Datacenter -Version latest | `
Add-AzVMNetworkInterface -Id $nic.Id
New-AzVM -ResourceGroupName $resourceGroup -Location $location -VM $vmConfig
MS is providing well tested powershell code for various tasks:
I prefer the github samples https://github.com/Azure/azure-docs-powershell-samples over the steps in learn and doc.microsoft.com
also have a deeper look at the Azure CLI examples and template based deployments. It seems to me that MS is abandoning PS a bit.

Deploying multiple scripts with CustomScriptExtension on an Azure Windows VM

I'm trying to deploy multiple PowerShell scripts to an Azure Windows VM by using the CustomScriptExtension.
The scripts are independent from each other so the order of their deployment doesn't matter. Also the scripts are in same blob container.
I have already a working template as below for installing one script at the moment:
$resourceGroup = "myResourceGroup"
$vmName = "myVM"
$location = "easteurope"
$storageAcctName = "myStorageAcct"
$storageKey = $env:ARM_ACCESS_KEY
$fileUri = #("https://xxxxx.blob.core.windows.net/xxxx/01-installTools.ps1")
$protectedSettings = #{"storageAccountName" = $storageAcctName; "storageAccountKey" = $storageKey};
$settings = #{"fileUris" = $fileUri;"commandToExecute" ="powershell -ExecutionPolicy Unrestricted -File 01-installTools.ps1"};
#run command
Set-AzVMExtension -ResourceGroupName $resourceGroup `
-Location $location `
-ExtensionName "IIS" `
-VMName $vmName `
-Publisher "Microsoft.Compute" `
-ExtensionType "CustomScriptExtension" `
-TypeHandlerVersion "1.8" `
-Settings $settings `
-ProtectedSettings $protectedSettings;
Also is it possible to use 2 CustomScriptExtensions?
I get a TypeHandlerVersion error if i try to do that.

Change password of Azure VM using PowerShell

I have tried this approach to change a password of an Azure VM:
$resgroup = "rsource1"
$vmName = "virtualmachine1"
$VM = Get-AzVM -ResourceGroupName $resgroup -Name $vmName
$Credential = Get-Credential
$VM | Set-AzureVMAccessExtension –UserName $Credential.UserName `
–Password $Credential.GetNetworkCredential().Password
$VM | Update-AzVM
But I keep getting this error:
Object reference not set to an instance of an object.
When I console.log the values of $Credential.UserName and $Credential.GetNetworkCredential().Password I got the values of username and password that I have inputted.
What am I missing here?
I've never used Set-AzureVMAccessExtension, but I've used the Az PowerShell equivalant Set-AzVMAccessExtension. It needs you to pass -Credential $Credential instead of -UserName and -Password.
You can try this script I made a while ago to to reset passwords for Azure VMs:
# Replace these values with your own
$resourceGroupName = "Servers-RG"
$vmName = "server1"
# Get the VM into an object
$vm = Get-AzVM -ResourceGroupName $resourceGroupName -Name $vmName
# Store credentials you want to change
$credential = Get-Credential -Message "Enter your username and password for $vmName"
# Store parameters in a hashtable for splatting
# Have a look at https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting?view=powershell-7
$extensionParams = #{
'VMName' = $vmName
'Credential' = $credential
'ResourceGroupName' = $resourceGroupName
'Name' = 'AdminPasswordReset'
'Location' = $vm.Location
}
# Pass splatted parameters and update password
Set-AzVMAccessExtension #extensionParams
# Restart VM
# Don't need to pass any switches since they are inferred ByPropertyName
# Have a look at https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_pipelines?view=powershell-7
$vm | Restart-AzVM
I found that the password update doesn't happen until you restart the VM, so Restart-VM is required.
If anyone interested in the Linux (KISS) version (no VM restart needed):
$settings = '{}'
$protectedSettings = '{
"username": "<yourusername, prefer using Credentials object>",
"password": "<yourpassword, prefer using Credentials object>"
}'
Set-AzVMExtension `
-VMName $vmName `
-ResourceGroupName $rgName `
-Location $location `
-Name "VMAccessForLinux" `
-Publisher "Microsoft.OSTCExtensions" `
-ExtensionType "VMAccessForLinux" `
-TypeHandlerVersion "1.4" `
-Settingstring $settings `
-ProtectedSettingString $protectedSettings

How to Create App Service with a subType of api

In powershell and using the new-azwebapp to create a website in our app service plan. But it only ever seems to create a type of app
I'm trying to create it with the type of api like you can when you select from the Azure Portal UI, but I can't see a setting in the configuration to do this.
After creating I set the AppSettings and then try to update the Type, but it doesn't seem to matter.
Hoping that I'm missing something simple.
$siteName = "namegoeshere"
$sitePlan = "myplanname"
$siteLocation = "Australia East"
$siteResourceGroup = "resourcegroupname"
$createdSite = new-azWebApp -Name $siteName -ResourceGroupName $siteResourceGroup -AppServicePlan $sitePlan -Location $siteLocation
$newAppSettings = #{ "name"="value"}
Set-AzWebApp -Name $siteName -ResourceGroupName $siteResourceGroup -AppSettings $newAppSettings -AppServicePlan Grower #-PhpVersion 0
$p = #{ 'type' = "api" }
$r = Set-AzResource -Name $siteName -ResourceGroupName $siteResourceGroup -ResourceType Microsoft.Web/sites -PropertyObject $p -ApiVersion 2016-03-01 -Kind "app"
echo $r.Properties
The type api is not set with type, in the New-AzureRmResource parameters there is a parameter to set it, it's [-Kind <String>]. You could check it here.
Here is an example.
# CREATE "just-an-api" API App
$ResourceLocation = "West US"
$ResourceName = "just-an-api"
$ResourceGroupName = "demo"
$PropertiesObject = #{
# serverFarmId points to the App Service Plan resource id
serverFarmId = "/subscriptions/SUBSCRIPTION-GUID/resourceGroups/demo/providers/Microsoft.Web/serverfarms/plan1"
}
New-AzureRmResource -Location $ResourceLocation `
-PropertyObject $PropertiesObject `
-ResourceGroupName $ResourceGroupName `
-ResourceType Microsoft.Web/sites `
-ResourceName "just-an-api/$ResourceName" `
-Kind 'api' `
-ApiVersion 2016-08-01 -Force

how to create multiple vms in azure resourcemanager portal with same NIC using powershell

I am trying to create multiple vms in azure resourcemanager portal with same NIC using powershell. But single VM alone getting created. when I use array for this exception occurs.
$i = 1;
[System.Collections.ArrayList]$vmArray1=#()
Do
{
$i;
switch($i){
{$vmName="Namenode"+$i}
{$vmName="Namenode"+$i}
default {$vmName="Datanode"+($i-2)}
}
$vmconfig=New-AzureRmVMConfig -VMName $vmName -VMSize $vmSize
$vmArray1.Add($vmconfig)
$i +=1
} Until ($i -gt $NumberOfVM)
$vm=Set-AzureRmVMOperatingSystem -VM $vmconfig -Windows -ComputerName $vmArray1 -Credential $credvm -ProvisionVMAgent -EnableAutoUpdate
But an exception occurs. Please let me know how to resolve this.
I am not sure whether it's your typing error or not. Your Set-AzureRmVMOperatingSystem Command is not inside the loop. That means it will always run only once. Beside of Operating System, you also need to provide Source Image, OS Disk, and Network Interface.
I have written something for you, and I have tested it at my end. It will create a set of VMs in one resource group and one Virtual Network. If you want the VMs in different resource groups or VNet, you can move the creation commands of resource groups or Vnet into the loop.
$credvm = Get-Credential
$NumberOfVM = <the number of VM you want to create>;
$ResourceGroupName = "<your resource group name>"
$Location = "East Asia"
## Storage
$StorageName = "<your storage account name>"
$StorageType = "Standard_GRS"
# Resource Group, if resource group has been created comment this out.
New-AzureRmResourceGroup -Name $ResourceGroupName -Location $Location
## Network
$InterfaceName = "<your interface name>"
$Subnet1Name = "Subnet1"
$VNetName = "<your vnet name>"
$VNetAddressPrefix = "10.0.0.0/16"
$VNetSubnetAddressPrefix = "10.0.0.0/24"
## Compute
$vmSize = "Standard_A2"
# Network
$SubnetConfig = New-AzureRmVirtualNetworkSubnetConfig -Name $Subnet1Name -AddressPrefix $VNetSubnetAddressPrefix
$VNet = New-AzureRmVirtualNetwork -Name $VNetName -ResourceGroupName $ResourceGroupName -Location $Location -AddressPrefix $VNetAddressPrefix -Subnet $SubnetConfig
$i = 1;
Do
{
$i;
$vmName="Namenode"+$i
$vmconfig=New-AzureRmVMConfig -VMName $vmName -VMSize $vmSize
$vm=Set-AzureRmVMOperatingSystem -VM $vmconfig -Windows -ComputerName $vmName -Credential $credvm -ProvisionVMAgent -EnableAutoUpdate
$OSDiskName = $vmName + "osDisk"
# Storage
$StorageAccount = New-AzureRmStorageAccount -ResourceGroupName $ResourceGroupName -Name $StorageName$i -Type $StorageType -Location $Location
## Setup local VM object
$vm = Set-AzureRmVMSourceImage -VM $vm -PublisherName MicrosoftWindowsServer -Offer WindowsServer -Skus 2012-R2-Datacenter -Version "latest"
$PIp = New-AzureRmPublicIpAddress -Name $InterfaceName$i -ResourceGroupName $ResourceGroupName -Location $Location -AllocationMethod Dynamic
$Interface = New-AzureRmNetworkInterface -Name $InterfaceName$i -ResourceGroupName $ResourceGroupName -Location $Location -SubnetId $VNet.Subnets[0].Id -PublicIpAddressId $PIp.Id
$VirtualMachine = Add-AzureRmVMNetworkInterface -VM $vm -Id $Interface.Id
$OSDiskUri = $StorageAccount.PrimaryEndpoints.Blob.ToString() + "vhds/" + $OSDiskName + ".vhd"
$VirtualMachine = Set-AzureRmVMOSDisk -VM $VirtualMachine -Name $OSDiskName -VhdUri $OSDiskUri -CreateOption FromImage
## Create the VM in Azure
New-AzureRmVM -ResourceGroupName $ResourceGroupName -Location $Location -VM $VirtualMachine
$i +=1
}
Until ($i -gt $NumberOfVM)

Resources