How to set the ComputeModel property to Serverless on an Azure SQL Database using PowerShell? - azure

I'm restoring an Azure SQL Database (Serverless) from a deleted database backup using Get-AzSqlDeletedDatabaseBackup and Restore-AzSqlDatabase PowerShell commandlets. The restore works, but the tags and ComputeModel are not restored with the database.
I've tried using Set-AzSqlDatabase:
Set-AzSqlDatabase -ResourceGroupName $resourcegroupname -DatabaseName $databasename -ServerName $servername -ComputeModel "Serverless" -AutoPauseDelayInMinutes 45
Update: I tried the following code and the Kind is set prior to using the Set-AzResource cmdlet, but it doesn't stick
$resource = Get-AzResource -ResourceGroupName $resourcegroupname -ResourceType "Microsoft.Sql/servers/databases" -Name "$servername/$databasename"
Write-Host "Setting ComputeModel to Serverless..."
$resource.Kind = "v12.0,user,vcore,serverless"
$resource
# resource.Kind is successfully set on the $resource object
Write-Host "Set-AzResource..."
$resource | Set-AzResource -Force
Anyone have any ideas?
Thank you.
Cheers,
Andy

The Get-AzSqlDeletedDatabaseBackup and Restore-AzSqlDatabase PowerShell cmdlets are doesn't contain a property to get the ComputeModel.
While Restore and Delete Backup database we don't require the ComputeModel properties. while setting database we need to require the ComputeModel.
If you want to get the compute model for the Azure SQL Database you can use, Get-AzResource command to fetch the specific information.
Thanks #joy wang SO Solution we can get the serverless Azure SQL Database.

Thanks to #holger and #Delliganesh Sevanesan for the help, I was able implement a solution that restores the most recent deleted database (SQL Database), adds some resource tags, and sets the ComputeModel to serverless.
Here's the code:
<#
Purpose: Restore the most recently deleted Azure Sql Database
Dependencies:
Az.Sql PowerShell module
#>
# Set variables first
$resourcegroupname = 'myresourcegroup'
$servername = 'myservername'
$databasename = 'mydatabasename'
[hashtable]$tags = #{
application = "testing"
}
try {
$deleteddatabases = Get-AzSqlDeletedDatabaseBackup -ResourceGroupName $resourcegroupname -ServerName $servername -DatabaseName $databasename
} catch {
Write-Error "Error getting database backups [Get-AzSqlDeletedDatabaseBackup]: " + $_.Exception.Message
exit(1)
}
# Get most recent backup in case there are multiple copies
# Assumes index and order in foreach is the same - proven in test
Write-Host "Database backups:"
$index = 0
$MostRecentBackupIndex = 0
$MostRecentBackupDate = (Get-date).AddDays(-2) # initialize variable with date from two days ago
foreach ($db in $deleteddatabases) {
if ($db.CreationDate -ge $MostRecentBackupDate) {
$MostRecentBackupIndex = $index
$MostRecentBackupDate = $db.CreationDate
Write-Host "Most Recent Database: $($db.DatabaseName) : Created: $($db.CreationDate) : DeleteDate: $($db.DeletionDate)"
}
$index++
}
$deleteddatabase = $deleteddatabases[$MostRecentBackupIndex]
Write-Host "----------------------------------------------------------------------------------"
Write-Host "Restoring: $($deleteddatabase.DatabaseName) from: $($deleteddatabase.CreationDate) backup"
Write-Host "----------------------------------------------------------------------------------"
Write-Host "Deleted database info ResourceId: "
Write-Host $deleteddatabase.ResourceId
try {
Restore-AzSqlDatabase -FromDeletedDatabaseBackup `
-DeletionDate $deleteddatabase.DeletionDate `
-ResourceGroupName $resourcegroupname `
-ServerName $servername `
-TargetDatabaseName $databasename `
-ResourceId $deleteddatabase.ResourceID `
-Edition $deleteddatabase.Edition `
-Vcore 2 `
-ComputeGeneration "Gen5"
} catch {
Write-Error "Error restoring database [Restore-AzSqlDatabase]: " + $_.Exception.Message
exit(1)
}
# Wait a few minutes to allow restore to complete before applying the tags
Start-Sleep -Seconds 180
Write-Host "Applying tags to database..."
try {
$resource = Get-AzResource -ResourceGroupName $resourcegroupname -ResourceType "Microsoft.Sql/servers/databases" -Name "$servername/$databasename"
New-AzTag -ResourceId $resource.Id -Tag $tags
} catch {
Write-Error "Error adding tags to database [Get-AzResource, New-AzTag]: " + $_.Exception.Message
exit(1)
}
Write-Host "Setting ComputeModel to Serverless..."
try {
# Important - must include -AutoPauseDelayInMinutes 60, -MinVcore, and MaxVcore parameters (thanks holger)
Set-AzSqlDatabase -ResourceGroupName $resourcegroupname -DatabaseName $databasename -ServerName $servername -ComputeModel Serverless -AutoPauseDelayInMinutes 60 -MinVcore 1 -MaxVcore 2
} catch {
Write-Error "Error setting serverless mode [Set-AzSqlDatabase]: " + $_.Exception.Message
exit(1)
}
Write-Host "Database restore complete."

Related

Lock azure resource with PowerShell

I've been trying to run a script to create a lock on azure resource to prevent resources being deleted inadvertently.
I get an error message and I can't figure out why it's showing me this error message.
Script:
#Sign in to Azure account
Login-AzAccount
#Select the subscription you want to work on
Select-AzSubscription -Subscription "test.subscription"
#Get All Resources in a resource group
$Resources = Get-AzResource -ResourceGroupName dummy_rg | Format-Table
# Create lock "delete" on each Resource if it doesn't exist
foreach($Resource in $Resources) {
$ResourceName = $Resource.Name
$lck = Get-AzResourceLock -ResourceGroupName $Resource.ResourceGroupName -ResourceName $ResourceName -ResourceType $Resource.ResourceType
if ($null -eq $lck)
{
Write-Host "$ResourceName has no lock"
New-AzResourceLock -resourceGroupName $rg -ResourceName $ResourceName -ResourceType $Resource.ResourceType -LockName "$ResourceName-lck" -LockLevel CanNotDelete -Force
Write-Host "$ResourceName has been locked"
}
else
{
Write-host "$ResourceName already locked"
}
}
Error message:
Gaurav request result:
#Start logging
Start-Transcript -Path "C:\Windows\Logs\Lock - $(((get-date).ToUniversalTime()).ToString("yyyy-MM-dd_hh-mm-ss")).log" -Force
#Connect to Azure account
Login-AzAccount
#Select Azure subscription
Set-AzContext -Subscription "subscription_id_numbers"
#Deny rule on Azure Data Factory and Azure Machine Learning
$Resources = Get-AzResource | Where-Object {$_.Name -NotLike '*adf*' -and $_.Name -NotLike '*aml*'}
# Create lock "delete" on each Resource if it doesn't exist
foreach($Resource in $Resources) {
$ResourceName = $Resource.Name
$lck = Get-AzResourceLock -ResourceGroupName $Resource.ResourceGroupName -ResourceName $ResourceName -ResourceType $Resource.ResourceType
if ($lck -eq $null)
{
Write-Host "$ResourceName has no lock"
Set-AzResourceLock -ResourceGroupName $Resource.ResourceGroupName -ResourceName $ResourceName -ResourceType $Resource.ResourceType -LockName "$ResourceName-lck" -LockLevel CanNotDelete -Force
Write-Host "$ResourceName has been locked"
}
else
{
Write-host "$ResourceName already locked"
}
}
#Stop Logging
Stop-Transcript
This will loop on every ressources except azure data factory in the tenant and create a "delete" type lock to make sure resources aren't deleted inadvertently.
Read comments in each section to understand the code.

Start/Stop VMs during off-hours - Azure

Need your help to find a runbook/automation script through which I could start/stop the VM's in Azure at a specific schedule & then in case we have to delay the shutdown schedule for a particular VM, it allows us to do so. Ideally, it should notify the end user, VM is going to shutdown in 30 min or so & gives option to delay the shutdown if need be.
Is there any existing runbook available in runbook gallary within automation account? Can anyone please advise or confirm?
You can simply do this by creating power shell runbook . This is for Starting VM for working hours. you can attached this to schedule inside workbook as required.
param (
[Parameter(Mandatory=$false)]
[String] $AzureConnectionAssetName = 'AzureRunAsConnection',
[Parameter(Mandatory=$false)]
[String] $ResourceGroupName = 'Your-VM-RG'
)
#Check for Weekends
$dayOfWeek = (Get-Date).DayOfWeek
if($dayOfWeek -eq 'Saturday' -or $dayOfWeek -eq 'Sunday'){
exit
}
# Get the connection
$Conn = Get-AutomationConnection -Name $AzureConnectionAssetName -ErrorAction Stop
$null = Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $Conn.TenantId `
-ApplicationId $Conn.ApplicationId `
-CertificateThumbprint $Conn.CertificateThumbprint `
-ErrorAction Stop `
-ErrorVariable err
if($err) {
throw $err
}
# Vet all VMs in the resource group
$VMs = Get-AzureRmVM -ResourceGroupName $ResourceGroupName
# Start each of the VMs
foreach ($VM in $VMs)
{
$StartRtn = $VM | Start-AzureRmVM -ErrorAction Continue
if ($StartRtn.IsSuccessStatusCode -ne $True)
{
# The VM failed to start, so send notice
Write-Output ($VM.Name + " failed to start")
Write-Error ($VM.Name + " failed to start. Error was:") -ErrorAction Continue
Write-Error (ConvertTo-Json $StartRtn) -ErrorAction Continue
}
else
{
# The VM stopped, so send notice
Write-Output ($VM.Name + " has been started")
}
}

Azure Automation Runbook missing mandatory parameters

I'm trying to set a Tag on all virtual machines in my subscription but I keep getting errors when running the Runbook.
The error is the following:
Get-AzureRmVM : Cannot process command because of one or more missing mandatory parameters: ResourceGroupName. At line:30
Here is my Runbook:
$azureConnection = Get-AutomationConnection -Name 'AzureRunAsConnection'
#Authenticate
try {
Clear-Variable -Name params -Force -ErrorAction Ignore
$params = #{
ServicePrincipal = $true
Tenant = $azureConnection.TenantID
ApplicationId = $azureConnection.ApplicationID
CertificateThumbprint = $azureConnection.CertificateThumbprint
}
$null = Add-AzureRmAccount #params
}
catch {
$errorMessage = $_
Throw "Unable to authenticate with error: $errorMessage"
}
# Discovery of all Azure VM's in the current subscription.
$azurevms = Get-AzureRmVM | Select-Object -ExpandProperty Name
Write-Host "Discovering Azure VM's in the following subscription $SubscriptionID Please hold...."
Write-Host "The following VM's have been discovered in subscription $SubscriptionID"
$azurevms
foreach ($azurevm in $azurevms) {
Write-Host "Checking for tag $vmtagname on $azurevm"
$tagRGname = Get-AzureRmVM -Name $azurevm | Select-Object -ExpandProperty ResourceGroupName
$tags = (Get-AzureRmResource -ResourceGroupName $tagRGname -Name $azurevm).Tags
If ($tags.UpdateWindow){
Write-Host "$azurevm already has the tag $vmtagname."
}
else
{
Write-Host "Creating Tag $vmtagname and Value $tagvalue for $azurevm"
$tags.Add($vmtagname,$tagvalue)
Set-AzureRmResource -ResourceGroupName $tagRGname -ResourceName $azurevm -ResourceType Microsoft.Compute/virtualMachines -Tag $tags -Force `
}
}
Write-Host "All tagging is done"
I tried importing the right modules but this doesn't seem to affect the outcome.
Running the same commands in Cloud Shell does work correctly.
I can reproduce your issue, the error was caused by this part Get-AzureRmVM -Name $azurevm, when running this command, the -ResourceGroupName is needed.
You need to use the Az command Get-AzVM -Name $azurevm, it will work.
Running the same commands in Cloud Shell does work correctly.
In Cloud shell, azure essentially uses the new Az module to run your command, you can understand it runs the Enable-AzureRmAlias before the command, you could check that via debug mode.
Get-AzureRmVM -Name joyWindowsVM -debug
To solve your issue completely, I recommend you to use the new Az module, because the AzureRM module was deprecated and will not be updated.
Please follow the steps below.
1.Navigate to your automation account in the portal -> Modules, check if you have imported the modules Az.Accounts, Az.Compute, Az.Resources, if not, go to Browse Gallery -> search and import them.
2.After import successfully, change your script to the one like below, then it should work fine.
$azureConnection = Get-AutomationConnection -Name 'AzureRunAsConnection'
#Authenticate
try {
Clear-Variable -Name params -Force -ErrorAction Ignore
$params = #{
ServicePrincipal = $true
Tenant = $azureConnection.TenantID
ApplicationId = $azureConnection.ApplicationID
CertificateThumbprint = $azureConnection.CertificateThumbprint
}
$null = Connect-AzAccount #params
}
catch {
$errorMessage = $_
Throw "Unable to authenticate with error: $errorMessage"
}
# Discovery of all Azure VM's in the current subscription.
$azurevms = Get-AzVM | Select-Object -ExpandProperty Name
Write-Host "Discovering Azure VM's in the following subscription $SubscriptionID Please hold...."
Write-Host "The following VM's have been discovered in subscription $SubscriptionID"
$azurevms
foreach ($azurevm in $azurevms) {
Write-Host "Checking for tag $vmtagname on $azurevm"
$tagRGname = Get-AzVM -Name $azurevm | Select-Object -ExpandProperty ResourceGroupName
$tags = (Get-AzResource -ResourceGroupName $tagRGname -Name $azurevm).Tags
If ($tags.UpdateWindow){
Write-Host "$azurevm already has the tag $vmtagname."
}
else
{
Write-Host "Creating Tag $vmtagname and Value $tagvalue for $azurevm"
$tags.Add($vmtagname,$tagvalue)
Set-AzResource -ResourceGroupName $tagRGname -ResourceName $azurevm -ResourceType Microsoft.Compute/virtualMachines -Tag $tags -Force `
}
}
Write-Host "All tagging is done"

Scaling CosmosDB Container using Powershell

I am trying to scale the CosmosDB Container using Powershell but couldn't find anything in the docs. I tried the following script which didn't work.
$resourceName = $CosmosDB + "/sql/" + $CosmosDatabase + "/" + $CosmosContainer
$ContainerProperties = #{
"resource"=#{
"id"=$CosmosContainer;
"partitionKey"=#{
"paths"=#("/DefaultKey");
"kind"="Hash"
}
};
"options"=#{ "Throughput"=$CosmosScale }
}
Set-AzResource -ResourceType "Microsoft.DocumentDb/databaseAccounts/apis/databases/containers" -ApiVersion "2015-04-08" -ResourceGroupName $resourceGroup -Name $resourceName -PropertyObject $ContainerProperties -Force
Any insights are appreciated.
Here is a PS script that will update throughput on either a database or container for a SQL (Core) API account.
# Update RU for an Azure Cosmos DB SQL (Core) API database or container
$resourceGroupName = "myResourceGroup"
$accountName = "mycosmosaccount"
$databaseName = "database1"
$containerName = "container1"
$databaseResourceName = $accountName + "/sql/" + $databaseName + "/throughput"
$containerResourceName = $accountName + "/sql/" + $databaseName + "/" + $containerName + "/throughput"
$throughput = 500
$updateResource = "database" # or "container"
$properties = #{
"resource"=#{"throughput"=$throughput}
}
if($updateResource -eq "database"){
Set-AzResource -ResourceType "Microsoft.DocumentDb/databaseAccounts/apis/databases/settings" `
-ApiVersion "2015-04-08" -ResourceGroupName $resourceGroupName `
-Name $databaseResourceName -PropertyObject $properties
}
elseif($updateResource -eq "container"){
Set-AzResource -ResourceType "Microsoft.DocumentDb/databaseAccounts/apis/databases/containers/settings" `
-ApiVersion "2015-04-08" -ResourceGroupName $resourceGroupName `
-Name $containerResourceName -PropertyObject $properties
}
else {
Write-Host("Must select database or container")
}
I have used this to update the Azure CosmosDb (SQL API) Collections on automation account but which gets timed Out with the cmdlet Set-AzResource - sometimes it works
Get-AzResource -ResourceType Microsoft.DocumentDB/databaseAccounts
$containerResourceType = "Microsoft.DocumentDb/databaseAccounts/apis/databases/containers/settings"
Using Set command with API Version in Runbook which got failed with ‘Operation failed because a request timed out.’
Set-AzResource -ResourceType $containerResourceType ***
Reference:
https://serverfault.com/questions/967942/scaling-cosmosdb-container-using-powershell

Automate deployment of JSON map

I have a Logic App in Azure which use a Liquid map, to transform JSON content. I am trying to deploy the map using New-AzureRmIntegrationAccountMap commandlet and the Set-AzureRmIntegrationAccountMap commandlet.
I get the following error when calling the Set-AzureRmIntegrationAccountMap commandlet:
Set-AzureRmIntegrationAccountMap : Unable to deserialize the response.
With this script:
Try
{
Write-Host -ForegroundColor Green "Creating $baseName..."
$mapContent = Get-Content -Path $fullName | Out-String
Write-Host -ForegroundColor Cyan "$mapContent"
New-AzureRmIntegrationAccountMap -ResourceGroupName $resourceGroupName -Name $iacName -MapName $baseName -MapDefinition $mapContent -ErrorAction Stop
Write-Host -ForegroundColor Green "Successfully created $baseName"
}
Catch
{
Write-Host -ForegroundColor Red "Error creating $baseName, trying update..."
Set-AzureRmIntegrationAccountMap -ResourceGroupName $resourceGroupName -Name $iacName -MapName $baseName -MapDefinition $mapContent -Force
if ($?) {
Write-Host -ForegroundColor Green "Successfully updated $baseName"
} else {
Write-Host -ForegroundColor Red "Error updating $baseName"
exit 1
}
}
After some searches, the two commandlets accept the MapType parameter, but only one value is allowed (XSLT).
Is there a way to automate the deployment of Liquid maps in an integration account in Azure (powershell, ARM template...) ?
Is there a way to automate the deployment of Liquid maps in an integration account in Azure (powershell, ARM template...) ?
Yes, I could create Liquid map with PowerShell on my side with the following code.
Login-AzureRmAccount
$IntegrationAccountName = "Integration Account name"
$ResouceGroupname = "ResourcegroupName"
$ResourceLocation = "West US" # location
$ResourceName = "liquid name"
$Content = Get-Content -Path "C:\Tom\simple.liquid" | Out-String
Write-Host $Content
$PropertiesObject = #{
mapType = "liquid"
content = "$Content"
contentType = "text/plain"
}
New-AzureRmResource -Location $ResourceLocation -PropertyObject $PropertiesObject -ResourceGroupName $ResouceGroupname -ResourceType Microsoft.Logic/integrationAccounts/maps -ResourceName " $IntegrationAccountName/$ResourceName" -ApiVersion 2016-06-01 -Force
Check it from azure portal.

Resources