1) I am trying to create VMs in azure using power-shell. There are multiple ways to create VMs. What is the recommended approach?
2) If the VM is created using Resource Manager, I am not able to find it in the current portal. Only preview portal is differentiating the VMs as "Virtual Machines (Classic)" & "Virtual Machines". When I click on the "Virtual Machines" and the created VM, it is not showing an option to capture VM. How to capture VM (in portal) that is created using Resource Manager powershell?
3) If the subscription has VMs of both types(classic & ARM) how to collect the inventory for both VM types?
ANS 1. Your approach depends on your requirement. If you need classic VM, go with ASM(Azure Service Manager) approach of spinning VM. If you are going with ARM(Azure Resource Manager) approach follow ARM cmdlets. I would recommend ARM as it is latest and as per MS they will depreciate ASM is future.
ANS 2. New portal doesn't have capture vm option. That option is only for classic vms. Rather it has the same functionality other way around, You can select a vhd and create a vm out of it using json template.
ANS 3. Almost every resource is listed in new portal however new vms can't be seen in old portal. If you are using latest PS cmdlets (1.0.1) even switching is not required. I recommend powershell as the output data is detailed.
First - use Preview Portal (portal.azure.com) , the new generation VM are available here only.
VMs created using the preview portal are new generation VMs, and Must be created with Resource manager Cmdlets, try to group your VMs of a particular solution in a resource group, and then you can manage and deploy the resource group as a logical unit.
so yes, First create a resource group, and then make the VM's which are belonging to this resource, a better approach is to make a template and add all your vm's to that template and deploy from template.
follow this https://azure.microsoft.com/en-us/documentation/articles/powershell-azure-resource-manager/
The classic VM can create by Azure Service Model (ASM) cmdlets. See the code snippets below.
Function New-VMByASM
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true)][String] $VMName,
[Parameter(Mandatory=$false)][String] $VMLabelPattern = "*Windows Server 2012 Datacenter*",
[Parameter(Mandatory=$false)]
[ValidateSet("North Europe", "East US", "South Central US", "Central US", "East US 2", "West US", "West Europe", "Southeast Asia", "East Asia", "Japan West", "Japan East")]
[String]$Location = "East Asia",
[Parameter(Mandatory=$false)]
[ValidateSet("ExtraSmall", "Small", "Medium", "Large", "ExtraLarge", "A5", "A6", "A7", "A8", "A9", "A10", "A11", "Basic_A0", "Basic_A1", "Basic_A2", "Basic_A3", "Basic_A4", "Standard_D1", "Standard_D2", "Standard_D3", "Standard_D4", "Standard_D11", "Standard_D12", "Standard_D13", "Standard_D14", "Standard_D1_v2", "Standard_D2_v2", "Standard_D3_v2", "Standard_D4_v2", "Standard_D5_v2", "Standard_D11_v2", "Standard_D12_v2", "Standard_D13_v2", "Standard_D14_v2", "Standard_DS1", "Standard_DS2", "Standard_DS3", "Standard_DS4", "Standard_DS11", "Standard_DS12", "Standard_DS13", "Standard_DS14", "Standard_DS1_v2", "Standard_DS2_v2", "Standard_DS3_v2", "Standard_DS4_v2", "Standard_DS5_v2", "Standard_DS11_v2", "Standard_DS12_v2", "Standard_DS13_v2", "Standard_DS14_v2", "Standard_G1", "Standard_G2", "Standard_G3", "Standard_G4", "Standard_G5", "Standard_GS1", "Standard_GS2", "Standard_GS3", "Standard_GS4", "Standard_GS5", "Standard_F1", "Standard_F2", "Standard_F4", "Standard_F8", "Standard_F16", "Standard_F1s", "Standard_F2s", "Standard_F4s", "Standard_F8s", "Standard_F16s")]
[String]$VMSize = "Basic_A0"
)
# 1. Login Azure by admin account
Add-AzureAccount
#
# 2. Select subscription name
$subscriptionName = Get-AzureSubscription | Select -ExpandProperty SubscriptionName
#
# 3. Create storage account
$storageAccountName = $VMName
# here we use VMName to play the storage account name and create it, you can choose your name or use existed one to replace the storage account creation operation
New-AzureStorageAccount -StorageAccountName $storageAccountName -Location $Location | Out-Null
#
# 4. Select subscription name and storage account name for current context
Select-AzureSubscription -SubscriptionName $subscriptionName -Current | Out-Null
Set-AzureSubscription -SubscriptionName $subscriptionName -CurrentStorageAccountName $storageAccountName | Out-Null
#
# 5. Select a VM image name
$label = $VMLabelPattern
# take care, please ensure the VM image location resides to the same location of your storage account and service below
$imageName = Get-AzureVMImage | where { $_.Label -like $label } | sort PublishedDate -Descending | select -ExpandProperty ImageName -First 1
#
# 6. Create cloud service
$svcName = $VMName
# here we use VMName to play the service name and create it, you can choose your name or use existed one to replace the service creation operation
New-AzureService -ServiceName $svcName -Location $Location | Out-Null
#
# 7. Build command set
$vmConfig = New-AzureVMConfig -Name $VMName -InstanceSize $VMSize -ImageName $imageName
#
# 8. Set local admin of this vm
$cred=Get-Credential -Message "Type the name and password of the local administrator account."
$vmConfig | Add-AzureProvisioningConfig -Windows -AdminUsername $cred.Username -Password $cred.GetNetworkCredential().Password
#
# 9. Execute the final cmdlet to create the VM
New-AzureVM -ServiceName $svcName -VMs $vmConfig | Out-Null
}
New-VMByASM -VMName $VMName -Location $StorageLocation
Write-Host "Done"
More details please read this sample post https://gallery.technet.microsoft.com/How-to-create-Azure-VM-by-b894d750
Related
I have resources in a Resource Group in Azure and it wont let me move the resource because it is in a Resource Group that is not the hosting Resource Group even though it has been moved .
I have tried to run the command in Powershell az resource list but cant seem to see the hosting Resource Group of the resource.
Is there a command I can run in Powershell that will give the current Resource Group of the resource and the hosting Resource Group of the resource?
Is there a Powershell command that will give the current Resource Group of the resource?
Yes its the Get-AzureRmResource command:
$resourceId = "/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/{resourceProviderNamespace}/{resourceType}/{resourceName}"
$resource = Get-AzureRmResource -ResourceId $resourceId
$resourceGroupName = $resource.ResourceGroupName
Fortunately there's an alternative to avoid specifying the "ResourceGroupName" which you're trying to find and that's specifying the ResourceType..
$resourceGroupName = Get-AzureRmResource -ResourceName {resourceName} -ResourceType {resourceType} | Select-Object -ExpandProperty ResourceGroupName
Also note the -ExpandProperties parameter in the documentation to include the resource properties.
Based on the shared information, I have understood that you want to know the
hosted resource group(in which resource group got created before move operation).
current resource group (currently where the resource resides in).
We don't have any direct cmdlets to pull this information.
You can make use of activity logs to see the resource move operation and pull the information of resources which were moved & respective target resource group names accordingly using the below cmdlet
Get-AzActivityLog -StartTime (get-date).AddDays(-90) -EndTime (get-date)| Where-Object {$_.Authorization.Action -like "Microsoft.Resources/subscriptions/resourceGroups/moveresources/action" -and $_.OperationName -like "Move Resource Group Resources" -and $_.EventName -like "Begin request" } | Select -ExpandProperty Properties
Sample screenshot for your reference:
Note: Using Get-AzActivityLog cmdlet you can pull logs for only last 90days.
We have a custom Managed Image that we built from Windows VM in Azure. We need to copy that Managed Image to China and create VMs from it. Unfortunately, we are unable to connect to VMs created from copied .vhd. The steps we did:
1. Created VM in Europe from custom Managed Image.
2. Ran Sysprep.
3. Exported Managed Disk, and uploaded .vhd to Storage Account in China.
4. Created VM from that image.
The problem is we are not able to RDP to that VM.
What is the proper way to do it? (connection time out)
We can't recreate that Image in China, because we need that Image to be consistent with the image we have in Europe.
A generalized VHD has had all of your personal account information removed using Sysprep. If you intend to use the VHD as an image to create new VMs. You should create a new user name and password to use as the local administrator account.
The following PowerShell script shows how to set up the virtual machine configurations and use the uploaded VM image as the source for the new installation.
# Enter a new user name and password to use as the local administrator account
# for remotely accessing the VM.
$cred = Get-Credential
# Name of the storage account where the VHD is located. This example sets the
# storage account name as "myStorageAccount"
$storageAccName = "myStorageAccount"
# Name of the virtual machine. This example sets the VM name as "myVM".
$vmName = "myVM"
# Size of the virtual machine. This example creates "Standard_D2_v2" sized VM.
# See the VM sizes documentation for more information:
# https://azure.microsoft.com/documentation/articles/virtual-machines-windows-sizes/
$vmSize = "Standard_D2_v2"
# Computer name for the VM. This examples sets the computer name as "myComputer".
$computerName = "myComputer"
# Name of the disk that holds the OS. This example sets the
# OS disk name as "myOsDisk"
$osDiskName = "myOsDisk"
# Assign a SKU name. This example sets the SKU name as "Standard_LRS"
# Valid values for -SkuName are: Standard_LRS - locally redundant storage, Standard_ZRS - zone redundant
# storage, Standard_GRS - geo redundant storage, Standard_RAGRS - read access geo redundant storage,
# Premium_LRS - premium locally redundant storage.
$skuName = "Standard_LRS"
# Get the storage account where the uploaded image is stored
$storageAcc = Get-AzureRmStorageAccount -ResourceGroupName $rgName -AccountName $storageAccName
# Set the VM name and size
$vmConfig = New-AzureRmVMConfig -VMName $vmName -VMSize $vmSize
#Set the Windows operating system configuration and add the NIC
$vm = Set-AzureRmVMOperatingSystem -VM $vmConfig -Windows -ComputerName $computerName `
-Credential $cred -ProvisionVMAgent -EnableAutoUpdate
$vm = Add-AzureRmVMNetworkInterface -VM $vm -Id $nic.Id
# Create the OS disk URI
$osDiskUri = '{0}vhds/{1}-{2}.vhd' `
-f $storageAcc.PrimaryEndpoints.Blob.ToString(), $vmName.ToLower(), $osDiskName
# Configure the OS disk to be created from the existing VHD image (-CreateOption fromImage).
$vm = Set-AzureRmVMOSDisk -VM $vm -Name $osDiskName -VhdUri $osDiskUri `
-CreateOption fromImage -SourceImageUri $imageURI -Windows
# Create the new VM
New-AzureRmVM -ResourceGroupName $rgName -Location $location -VM $vm
Ref: Upload a generalized VHD to Azure to create a new VM
Just now I started with Azure DevTest Lab. I created a VM in lab using a json template. I want to use the public IP of the VM using powershell or may be I would like to return the same using template, if I can.
The challenge here is as per DTL concept the VM is created in a new resource group other than the one where your lab exists. I can definitely see the name of resource group of lab VM on portal but I am not able to figure out how this can be done using powershell. I am working on an automation so I need to do it by powershell.
Refer to the picture. The lab seems to be in a resource group in the same where the lab exist shown in green box. But, technically the lab VM resides in dynamically created resource gruop (RG name pattern = labname + VM name + Some Random digits) shown in light yellow in screenshot.
Other solutions are helpful but not complete. I am doing in this way - I am returning the default output of template that is vmId. Refer from template link
Now we need to manipulate this vmId to get the name of resource group where the lab VM has been created.
$result = New-AzureRmResourceGroupDeployment -ResourceGroupName "aatifdtlrg207912" -TemplateFile "D:\AzureDeploy.json" -TemplateParameterObject $paramValues
$VMId = $result.outputs.Values.value
$VMComputeId = (Get-AzureRmResource -Id $VMId).Properties.ComputeId
$RGNameofVM = $VMComputeId.split("/")
$RGNameofVM = $RGNameofVM[4]
$IP = (Get-AzureRmNetworkInterface -Name $VMName -ResourceGroupName $RGNameofVM ).IpConfigurations.PrivateIpAddress
Well, generally a more elegant solution, oposed to bruteforce would be to use Get-AzureRmResource
$Resource = Get-AzureRmResource -ResourceId "/subscriptions/$sub_GUID/resourcegroups/$RG_devlab_Name/providers/microsoft.devtestlab/labs/$LabName/virtualmachines/$VMName"
$Resource.Properties.computeId -match 'resourceGroups/(.+)/providers'
$RGName = $Matches[1]
$IP = (Get-AzureRmNetworkInterface -Name $VMName-ResourceGroupName $RGName).IpConfigurations.PrivateIpAddress
Well, as we know for DevTest Labs there is no direct way for powershell. You can use the below powershell script to get the Private IP Address of the VM by just passing the Virtual machine name. We can use Find-AzureRmResource and Get-AzureRmResource by passing the ResourceId:
$vmNicdetails = Find-AzureRmResource -ResourceNameContains mytestVM | Where {$_.ResourceType -eq 'Microsoft.Network/networkInterfaces'}
$nicdetails = Get-AzureRmResource -ResourceId $vmNicdetails.ResourceId
$ipconfig = Get-AzureRmResource -ResourceId
$nicdetails.Properties.ipConfigurations.id -ApiVersion '2017-03-01'
$ipconfig.Properties.privateIPAddress
To run Azure Service Fabric on a cluster I have a vmset. I know the password, but it has to be changed. For a VM I would normally use the "reset password" function on the azure portal, but the vmset does not allow this. Adjusting the password in the resource template is also not allowed.
How to change the password of VM's in a vmset?
Update: See the VMSS FAQ:
Change the virtual machine scale set model directly. Available with Compute API 2017-12-01 and later.
Update the admin credentials directly in the scale set model (for example using the Azure Resource Explorer, PowerShell or CLI). Once the scale set is updated, all new VMs have the new credentials. Existing VMs only have the new credentials if they are reimaged.
Alternatively (and for older API versions) you can apply the VM Access extension. The Set-AzureRmVmssOSProfile cmdlet is useful when you're creating a scale set imperatively with PowerShell, but can't be used to change non-modifiable properties of an existing scale set.
Here's an example of using the VM Access extension to modify a scale set:
# Login to your azure account
Login-AzureRmAccount
# Set the scale set and resource group
$vmssName = "myvmss"
$vmssResourceGroup = "myvmssrg"
# Set the username / password
$publicConfig = #{"UserName" = "newuser"}
$privateConfig = #{"Password" = "********"}
$extName = "VMAccessAgent"
$publisher = "Microsoft.Compute"
$vmss = Get-AzureRmVmss -ResourceGroupName $vmssResourceGroup -VMScaleSetName $vmssName
$vmss = Add-AzureRmVmssExtension -VirtualMachineScaleSet $vmss -Name $extName -Publisher $publisher -Setting $publicConfig -ProtectedSetting $privateConfig -Type $extName -TypeHandlerVersion "2.0" -AutoUpgradeMinorVersion $true
Update-AzureRmVmss -ResourceGroupName $vmssResourceGroup -Name $vmssName -VirtualMachineScaleSet $vmss
Looking at the Azure PowerShell commandlets, Set-AzureRmVmssOsProfile makes sense:
PS C:\>Set-AzureRmVmssOSProfile -VirtualMachineScaleSet "ContosoVMSS" -ComputerNamePrefix "Test" -AdminUsername $AdminUsername -AdminPassword $AdminPassword
This command sets operating system profile properties for the virtual machines that belong to the VMSS named ContosoVMSS. The command sets the computer name prefix for all the virtual machine instances in the VMSS to Test and supplies the administrator username and password.
I am trying to get the list of reserved IP's that are assigned to resources in my subscriptions in ARM model.
Get-AzureReservedIP command does not work saying the default subscription is not selected. However I selected a default subscription and still the command does not work.
here is the snippet
Add-AzureRmAccount
$subName="subscriptioname"
Select-AzureSubscription -SubscriptionName $subName -Current
Get-AzureReservedIP
Any Suggestions?
Azure has two ways of deployment: Azure service management (ASM) and Azure resource manager (ARM).
You sign in with ARM mode and the "Get-AzureReservedIP" is a ASM command. In ARM, the reserved IP address is called static public IP address. To get them, please run the commands below:
Add-AzureRmAccount
$subName="subscriptioname"
Select-AzureRmSubscription -SubscriptionName $subName
Get-AzureRmPublicIpAddress | Where-Object { $_.PublicIpAllocationMethod -eq "Static" }
If you want to get the reserved IP address in ASM mode, please run the commands below:
Add-AzureAccount
$subName="subscriptioname"
Select-AzureSubscription -SubscriptionName $subName -Current
Get-AzureReservedIP
You can try :
Get-AzureRmNetworkInterface -Name TestNIC -ResourceGroupName TestRG