is there a way of automating $credential = Get-Credential when running Set-AzVMADDomainExtension - azure

I need to automate domain join in a pipleine for Azure vm , Im using this code, however I dont want the user to enter the credential during runtime, how can i use a saved credential?
$DomainName = "abc.com"
$VMName = "VMNAME01"
$credential = Get-Credential
$ResourceGroupName = "RG01"
Set-AzVMADDomainExtension -DomainName $DomainName -VMName $VMName -Credential $credential -ResourceGroupName $ResourceGroupName -JoinOption 0x00000001 -Restart -Verbose

Related

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

Azure Analytics Database with automate Backup

The powershell is used to automate the backup of AAS instance.
The instance have Multi-factor authentication and I think that is the problem.
Powershell:
$TenantId = "TenentID"
$Cred = Get-AutomationPSCredential -Name 'SSASModelBackup'
$Server = "ServerName"
$RolloutEnvironment = "location.asazure.windows.net"
$ResourceGroup = "ReourceGroupName"
#Create Credentials to convertToSecureString
$applicationId = "applicationId "
$securePassword = "securePassword " | ConvertTo-SecureString -AsPlainText -Force $Credential = New-Object
-TypeName System.Management.Automation.PSCredential -ArgumentList $applicationId, $securePassword
#Define the list of AAS databases
$asDBs = #('database1','database2')
Write-Output "Logging in to Azure..."
#Add-AzureAnalysisServicesAccount -Credential $Credential -ServicePrincipal -TenantId $TenantId -RolloutEnvironment $RolloutEnvironment
ForEach($db in $asDBs)
{
Write-Output "Starting Backup..."
Backup-ASDatabase `
–backupfile ($db +"." + (Get-Date).ToString("ddMMyyyy") + ".abf") `
–name $db `
-server $Server `
-Credential $Cred
Write-Output "Backup Completed!"
}
You are correct that the issue is with multi-factor authentication. Since the point of multi-factor is the require interaction with a secondary source like your phone there is no way to automate the process.
I would suggest that you look into using service principle authentication for the purpose of taking backups. By using a service principle to your server you can allow for automated tasks to run without 2-factor while minimizing the security risk.

where azure snapshots are stored with this script

I found this blog post
https://www.techmanyu.com/automate-disk-snapshots-azure/
And the author showes this script.
$clientID = "<client id>"
$key = "<client secret>"
$SecurePassword = $key | ConvertTo-SecureString -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $clientID, $SecurePassword
Add-AzureRmAccount -Credential $cred -Tenant "<Tenant ID>" -ServicePrincipal;
$disks=Get-AzureRmDisk | Select Name,Tags,Id,Location,ResourceGroupName ;
foreach($disk in $disks) { foreach($tag in $disk.Tags) { if($tag.Snapshot -eq 'True') {$snapshotconfig = New-AzureRmSnapshotConfig -SourceUri $disk.Id -CreateOption Copy -Location $disk.Location -AccountType PremiumLRS;$SnapshotName=$disk.Name+(Get-Date -Format "yyyy-MM-dd");New-AzureRmSnapshot -Snapshot $snapshotconfig -SnapshotName $SnapshotName -ResourceGroupName $disk.ResourceGroupName }}}
Trying to understand the script, I came up with the question, where are the snapshots stored? In the same managed disk as the VM disk?
After executing the script, it will create the snapshots that you can check them in the portal, they have the resource type of Microsoft.Compute/snapshots.
Essentially, they should be stored in the blob storage. Navigate to the snapshot in the portal -> Export, then you will find it generates a SAS token of the snapshot like https://md-nxxxqz.blob.core.windows.net/wxxxxxx0m/abcd?sv=2017-04-17&sr=b&si=31b3d91b-51be-4c1c-930e-996f382b8ad9&sig=xxxxxx. The md-nxxxqz is the storage account which stores the snapshots, it is managed by Azure.

Create VM in Azure with powershell with no public IP

I'm creating VM on Azure from an Image using powershell.
This is the script I'm using .
$UserName = "username"
$Password = ConvertTo-SecureString "password#123" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($UserName, $Password)
New-AzureRmVm `
-ResourceGroupName "RSG" `
-Name "VMName" `
-ImageName "ImageName" `
-Location "West US" `
-VirtualNetworkName "VNName" `
-SubnetName "default" `
-Credential $psCred
-PublicIpAddressName "None" `
-OpenPorts 3389
But, when I got into the Azure portal and see, some Public Ip is getting assigned by default. I have also tried without giving PublicIpAddressName property assuming , it wont assign any IP, but still it is assigning.
I want the Public IP to be none.Can anyone help me achieve this.Thanks!
Currently this an issue which is still in Open state on official azure-powershell github. You can refer it here . Incase if you still want to bypass this you can try using New-AzureReservedIP or after the deployment command try to remove the public ip by yourself Remove-AzureRmPublicIpAddress.
Note : I have'nt tested it yet. Just an idea.
Refer : Docs
To set no public ip address you have can just define it as "" , in powershell you will need to quote that again so it will be """" .
If you are using PowerShell, then you will need to escape all empty parameters by changing "" to '""' to properly pass an empty string into the command. Without this, PowerShell will not pass the empty string, and you will get an error from the command indicating it's missing a parameter.
$winVmCred = Get-Credential `
-Message "Enter username and password for the Windows management virtual machine."
# Create a NIC for the VM.
$winVmNic = New-AzNetworkInterface -Name "winVMNIC01" `
-ResourceGroupName $resourceGroup.ResourceGroupName `
-Location $location `
-SubnetId $targetVMSubnet.Id `
-PrivateIpAddress "10.10.12.10"
# Configure the Windows management VM.
$winVmConfig = New-AzVMConfig -VMName $winVmName -VMSize $winVmSize | `
Set-AzVMOperatingSystem -Windows -ComputerName $winVmName -Credential $winVmCred | `
Set-AzVMSourceImage -PublisherName $winVmPublisher `
-Offer $winVmOffer `
-Skus $winVmSku `
-Version $winVmVersion | `
Add-AzVMNetworkInterface -Id $winVmNic.Id
# Create the VM.
$winVM = New-AzVM -ResourceGroupName $resourceGroup.ResourceGroupName `
-Location $location `
-VM $winVmConfig `
-ErrorAction Stop

Multiple VM Creation by ARM Powershell approach

I have a ps workflow(.psm file) where I am trying to create 5 vms in parallel. I am using ARM cmdlets.I am getting an error-
Error- Cannot validate argument on parameter 'SubnetId'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command
again.
Here is my challange-
Even if I remove -parallel parameter from foreach even then its not making any difference.
If I run the same code NOT inside a workflow(ps1 file) removing -parralel parameter I am able to
create 5 vms
Code-
workflow Create-VMs
{
$UserName = "abc#cde.onmicrosoft.com"
$pwd = ConvertTo-SecureString "xxxxxxxx" -AsPlainText -Force
$AzureCredential = New-Object System.Management.Automation.PSCredential($UserName, $pwd)
login-azurermaccount -credential $AzureCredential
Add-AzureRmAccount -Credential $AzureCredential
Select-AzureRmSubscription -SubscriptionName "xxxxx"
$virtualNetworkName = "myvpn"
$locationName = "East US"
$ResourceGroupName = "myrg"
$user = "adminuser"
$password = "AdminPass123"
$VMSize = "Standard_D2"
$sourcevhd = "https://abc.blob.core.windows.net/vhds/windowsserver2008.vhd"
$virtualNetwork = Get-AzureRmVirtualNetwork -ResourceGroupName $ResourceGroupName -Name $virtualNetworkName
foreach -parallel($i in 1..5)
{
$VMName = "myname" + $i
$destinationVhd = "https://abc.blob.core.windows.net/vhds/windowsserver2008" + $i + ".vhd"
$staticip = "dynamicip" + $i
$virtualNetwork = Get-AzureRmVirtualNetwork -ResourceGroupName $ResourceGroupName -Name $virtualNetworkName
$publicIp = New-AzureRmPublicIpAddress -Name $staticip -ResourceGroupName $ResourceGroupName -Location $locationName -AllocationMethod Dynamic
$networkInterface = New-AzureRmNetworkInterface -ResourceGroupName $ResourceGroupName -Name $VMName -Location $locationName -SubnetId $virtualNetwork.Subnets[0].Id -PublicIpAddressId $publicIp.Id
$vmConfig = New-AzureRmVMConfig -VMName $VMName -VMSize $VMSize
$vmConfig = Set-AzureRmVMOSDisk -VM $vmConfig -Name $VMName -VhdUri $destinationVhd -CreateOption FromImage -Windows -SourceImageUri $sourcevhd
$vmConfig = Add-AzureRmVMNetworkInterface -VM $vmConfig -Id $networkInterface.Id
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential ($user, $securePassword)
Set-AzureRmVMOperatingSystem -VM $vmConfig -Windows -Credential $cred -ProvisionVMAgent -ComputerName $VMName
New-AzureRmVM -VM $vmConfig -Location $locationName -ResourceGroupName $ResourceGroupName
}
}
Not able to find out what is the actual problem. Any other approach for creating multiple vms in parallel using ARM ?
I've not had much luck with -parallel and the Azure cmdlets, but I can think of two options for you:
1) use PowerShell jobs - this would require you to login for each job, here's a snippet of how I do it - the "job" in this case is removing a resource group.
foreach ($AzureResourceGroup in $AzureResourceGroups) {
Start-Job -Name $AzureResourceGroup {
Param($AzureResourceGroup, $creds, $tenantID, $subscriptionName)
Login-AzureRmAccount -ServicePrincipal -Credential $creds -TenantId $tenantId
Select-AzureRmSubscription -SubscriptionName $subscriptionName
Remove-AzureRMResourceGroup -Force -Verbose -Name $AzureResourceGroup
} -ArgumentList $AzureResourceGroup, $creds, $tenantId, $subscriptionName
}
Get-Job | Wait-Job | Receive-Job
2) I think better way would be to use a JSON template, and have Azure orchestrate the deployment. There's a sample of how of the template and how to do it here: https://github.com/bmoore-msft/AzureRM-Samples/tree/master/VMFromImageMulti - there's a readme in the root to show how to deploy it.

Resources