enable / disable scaling on Azure VMSS with powershell - azure-powershell

Is there a way to enable or disable scaling for an Azure VMSS without providing all the rules and profiles to Add-AzureRmAutoscaleSetting

According to this there is the -DisableSetting switch which you can use to achieve what you want

Done it using the following powershell:
$myResourceGroup = 'my_rsg'
$myLocation = 'West Europe'
$myScaleName = 'scalename'
$scale = Get-AzureRmAutoscaleSetting -ResourceGroupName $myResourceGroup -Name $myScaleName
Add-AzureRmAutoscaleSetting -AutoscaleProfile $scale.Profiles `
-Location $myLocation `
-Name $scale.Name `
-ResourceGroupName $myResourceGroup `
-TargetResourceId $scale.TargetResourceUri `
-DisableSetting

Related

How to enable auto scaling for SQL app in Azure Portal

I am looking to allow auto-scaling from my SQL DB app in Azure portal so that allow it to increase to 200 DTUs on a particular day and then automatically scale back down to 20. I seem to be getting confused as to how to go about it as I'm aware I will need to use Azure cli also. Any help would be much appreciated.
If you wanna scale SQL in Azure on some schedule I would recommend you to prepare Automation service with PowerShell script and schedules connected to that Runbook. Also you would need to configure Run as options.
I personally use this script to scale DB up and down on daily base.
## Authentication
Write-Output ""
Write-Output "------------------------ Authentication ------------------------"
Write-Output "Logging into Azure ..."
$connectionName = "AzureRunAsConnection"
try
{
# Get the connection "AzureRunAsConnection "
$servicePrincipalConnection=Get-AutomationConnection -Name $connectionName
"Logging in to Azure..."
Add-AzureRmAccount `
-ServicePrincipal `
-TenantId $servicePrincipalConnection.TenantId `
-ApplicationId $servicePrincipalConnection.ApplicationId `
-CertificateThumbprint $servicePrincipalConnection.CertificateThumbprint
}
catch {
if (!$servicePrincipalConnection)
{
$ErrorMessage = "Connection $connectionName not found."
throw $ErrorMessage
} else{
Write-Error -Message $_.Exception
throw $_.Exception
}
}
##DB Part
$vCores = 18
$currentTier = "GP_Gen5"
$size = 200
$resourceGroup = ""
$serverName = ""
$databaseName = ""
$db_size = "GP_Gen5_4"
Write-Output "Changing DB type to GP_Gen5_4"
Set-AzureRmSqlDatabase `
-ServerName $serverName `
-ResourceGroupName $resourceGroup `
-DatabaseName $databaseName `
-RequestedServiceObjectiveName $db_size
# -RequestedServiceObjectiveName "$currentTier" + "_" + "$vCores"
Write-Output "Writing current DB parameters"
Get-AzureRmSqlDatabase `
-ServerName $serverName `
-ResourceGroupName $resourceGroup `
-DatabaseName $databaseName

Azure Powershell New-AzSynapseManagedPrivateEndpoint Definition File format?

I'm trying to deploy a managed private endpoint to my synapse instance to connect it to a key Vault in the same resource Group. The documentation for the same deployment in Bicep is very incomplete so I thought to try my luck with PowerShell using the following command :
New-AzSynapseManagedPrivateEndpoint `
-WorkspaceName "synapse-test-joao" `
-Name "managedPrivateEndpointKeyVault" `
-DefinitionFile file.json
However, I cannot seem to find the format for the definition file anywhere on the internet, so was wondering if anyone had any information regarding the json format and what parameters need to go inside.
This would be immensely helpful,
Joao
The sample -DefinitionFile should be in below format:
{
# here i am using sample blob storage
"name": "testblob", #ManagePrivate Endpoint Name
"properties": {
"privateLinkResourceId": "/subscriptions/<subscription ID>/resourceGroups/<ResourceGroup name>/providers/Microsoft.Storage/storageAccounts/<Storage Account Name>",
"groupId": "blob"
}
}
To get the -DefinitionFile Sample file to follow the below ways:
Way 1:
Go to your Azure Synapse Workspace -> Managed Private Endpoints
Drag your cursor into your private endpoint you can see {} - (Code) from there you can get the sample -DefinitionFile.
Way 2:
This way you can get the PrivateLinkResourceId of ManagedPrivateEndpoint
$ds = Get-AzSynapseWorkspace -Name <Synapse workspaces Name>
$ws | Get-AzSynapseManagedPrivateEndpoint -Name <Your Created Managed Private Endpoint Name>
# Private Link Resource Id
/subscriptions/<subscription ID>/resourceGroups/<ResourceGroup name>/providers/Microsoft.Storage/storageAccounts/<Storage Account Name>
Refer here
The code to deploy the managed private endpoint for Synapse in a devOps pipeline can be as follows:
param(
$environment,
$synapseWorkspaceVar,
$subscriptionId,
$resourceGroupNameVar,
$keyVaultNameVar
)
$createPrivateEndpointJsonString = #"
{
"properties": {
"privateLinkResourceId": "/subscriptions/$subscriptionId/resourceGroups/$resourceGroupNameVar/providers/Microsoft.KeyVault/vaults/$keyVaultNameVar",
"groupId": "vault"
}
}
"#
write-output $createPrivateEndpointJsonString
$tempFolderPath = ".\temp"
if (!(Test-path -path $tempFolderPath)) {
echo "new file"
New-Item -ItemType directory -path $tempFolderPath
}
write-output "creating the PrivateEndpoint Definition Json file...."
$jsonpath = ".\$tempFolderPath\createprivateendpoint.json"
Set-Content -Path $jsonpath -value $createPrivateEndpointJsonString
echo "Creating new Managed Private Endpoint from Synapse to KeyVault..."
New-AzSynapseManagedPrivateEndpoint `
-WorkspaceName $synapseWorkspaceVar `
-Name "managedPrivateEndpointKeyVaultACEP" `
-DefinitionFile $jsonpath
Get-AzSynapseManagedPrivateEndpoint -WorkspaceName $synapseWorkspaceVar

Toggle an Application Gateway WAF to Prevention/Detection mode

Goal:
Toggle an application Gateway WAF between prevention and detection mode via code.
Configuration Details:
App GW SKU: WAFv2
Application Gateway WAF deployed
Custom rules and managed policies are implemented
WAF is Associated to Application Gateway
Pre-requisite Commands:
$policyName = *Input*
$appGWName = *Input*
$appGWRG = *Input*
$location = *Input*
$gw = Get-AzApplicationGateway -Name $appGWName -ResourceGroupName $appGWRG
$policy = Get-AzApplicationGatewayFirewallPolicy -Name $policyName -ResourceGroupName $appGWRG
What I've attempted:
Manually I am able to switch from prevention to detection. (Successful)
Using a Powershell command I'm able to update the WAF policy setting directly, but it does not replicate to the resource itself.
$policy.PolicySettings.Mode = "Prevention"
$policy.PolicySettings.Mode = "Detection"
Using Powershell command I'm able to update the WAF policy via the Appliction gateway, but it doesn't replicate to the WAF or Application gateway.
Set-AzApplicationGatewayWebApplicationFirewallConfiguration -FirewallMode Detection -ApplicationGateway $gw -Enabled $true
Getting the following error:
quoteSet-AzApplicationGateway: WebApplicationFirewallConfiguration cannot be changed when there is a WAF Policy /subscriptions/7bba5d50-5df8-49be-b59d-b737e7663335/resourceGroups/pbolkun-RG/providers/Microsoft.Network/ApplicationGatewayWebApplicationFirewallPolicies/WafPolicyProdEusAgw associated with it.
I've also tried Set-AzApplicationGateway -ApplicationGateway $gw at the end of each implementation which again, doesn't work..
I'd like a programmatic way so that I can utilize IaC to the max. I'd prefer to avoid deploying an ARM template each time I want to switch between the two for testing.
Thank you in advanced!
I tested the same in my environment by creating a App Gateway & WAF Policy and associating the policy to the App Gateway.
Then I used the below code to change the Firewall Policy Setting and update the application gateway :
param
(
[string] $policyName = "ansumanwafpolicy",
[string]$appGWName = "appansumangw",
[string]$appGWRG = "ansumantest",
[string]$location = "West US 2",
[string] $policyMode = "Detection"
)
$gw = Get-AzApplicationGateway -Name $appGWName -ResourceGroupName $appGWRG
$policy= Get-AzApplicationGatewayFirewallPolicy -Name $policyName -ResourceGroupName $appGWRG
$update = #{
Mode = $policyMode
State = $policy.PolicySettings.State
RequestBodyCheck = $policy.PolicySettings.RequestBodyCheck
MaxRequestBodySizeInKb = $policy.PolicySettings.MaxRequestBodySizeInKb
FileUploadLimitInMb = $policy.PolicySettings.FileUploadLimitInMb
}
$UpdatePolicy = Set-AzApplicationGatewayFirewallPolicy -Name $policyName -ResourceGroupName $appGWRG -PolicySetting $update
$UpdateAPPGW = Set-AzApplicationGatewayWebApplicationFirewallConfiguration -FirewallMode $policyMode -ApplicationGateway $gw -Enabled $gw.WebApplicationFirewallConfiguration.Enabled -RuleSetType $gw.WebApplicationFirewallConfiguration.RuleSetType -RuleSetVersion $gw.WebApplicationFirewallConfiguration.RuleSetVersion
Output:
It doesn't reflect immediately but running the get appgw command after few mins it shows the change like below:

Powershell BitsTransfer https basic authentication syntax

I'm new to PowerShell scripting. I'm struggling with the MS documentation and finding few examples to work with.
I'm trying to automate the weekly download of a large txt file from ntis.gov with a BitsTransfer script. I'm using .ps1 script because apparently SSIS can't do this without writing .NET code.
Access to this text file is via https: with an NTIS issued username and password. How can I specify (hard code) the password into the authentication string? I know this is bad practice. Is there a better way to do this?
My script looks like this-
$date= Get-Date -format yyMMdd
Import-Module BitsTransfer
$Job = Start-BitsTransfer `
-DisplayName DMFweeklytrans `
-ProxyUsage AutoDetect `
-Source https://dmf.ntis.gov/dmldata/weekly/WA$date `
-Destination D:\Test.txt `
-Authentication Basic `
-Credential "myIssuedUsername" `
-Asynchronous
While (($Job.JobState -eq "Transferring") -or ($Job.JobState -eq "Connecting")) {sleep 5}
Switch($Job.JobState)
{
"Transfer Completed" {Complete-BitsTransfer -BitsJobs $Jobs}
default {$Job | Format-List}
}
When you have to provide credentials in non-interactive mode, you can create a PSCredential object in the following way.
$secpasswd = ConvertTo-SecureString "PlainTextPassword" -AsPlainText -Force
$yourcreds = New-Object System.Management.Automation.PSCredential ("username", $secpasswd)
$Job = Start-BitsTransfer `
-DisplayName DMFweeklytrans `
-ProxyUsage AutoDetect `
-Source https://dmf.ntis.gov/dmldata/weekly/WA$date `
-Destination D:\Test.txt `
-Authentication Basic `
-Credential $yourcreds `
-Asynchronous

Azure database backup to blob using Powershell

We need to backup the azure database and store it on blob so that it can be restored. I've seen this blog but it uses the third party cmdlets.
http://weblogs.thinktecture.com/cweyer/2011/01/automating-backup-of-a-sql-azure-database-to-azure-blob-storage-with-the-help-of-powershell-and-task-scheduler.html
Could someone please guide/help how above can be achieved using powershell.
Backing up to WA Blob Store is not supported from Azure DB, rather the service does automatic backups for you with PITR capability. You'll find the following documentation useful:
http://msdn.microsoft.com/en-us/library/azure/hh852669.aspx
http://msdn.microsoft.com/en-us/library/azure/jj650016.aspx
Hope this helps.
Here is my powershell script
https://gist.github.com/voxon2/be29a3fd6dabbb9155ca
Here is an article describing many different approaches other than powershell
http://blogs.msdn.com/b/mast/archive/2013/03/04/different-ways-to-backup-your-windows-azure-sql-database.aspx
First get your Azure Automation Settings done (see here).
Edit the blow script and save it as .ps1 file. When you run it for
the first time, it will ask you both your azure automation account and
your database credentials. During this process, it will save your
credentials in a local file securely (see here how it is done). After this time on wards, it uses the saved credentials.
The .psl file and the encrypted credential files should be stored in one
directory
Once you are happy you can schedule it to run in task scheduler.
function Get-MyCredential
{
param(
$CredPath,
[switch]$Help
)
$HelpText = #"
Get-MyCredential
Usage:
Get-MyCredential -CredPath `$CredPath
If a credential is stored in $CredPath, it will be used.
If no credential is found, Export-Credential will start and offer to
Store a credential at the location specified.
"#
if($Help -or (!($CredPath))){write-host $Helptext; Break}
if (!(Test-Path -Path $CredPath -PathType Leaf)) {
Export-Credential (Get-Credential) $CredPath
}
$cred = Import-Clixml $CredPath
$cred.Password = $cred.Password | ConvertTo-SecureString
$Credential = New-Object System.Management.Automation.PsCredential($cred.UserName, $cred.Password)
Return $Credential
}
function Export-Credential($cred, $path) {
$cred = $cred | Select-Object *
$cred.password = $cred.Password | ConvertFrom-SecureString
$cred | Export-Clixml $path
}
#Create a directory with you azure server name to isolate configurations
$FileRootPath = "C:\PowerShellScripts\AzureServerName"
Write-Host "Getting Azure credentials"
$AzureCred = Get-MyCredential ($FileRootPath + "AzureSyncred.txt")
#Use Azure Automation Account
#(If You do not have it will not work with other accounts)
Add-AzureAccount -Credential $AzureCred
Select-AzureSubscription -SubscriptionId "myAzureSubscriptionId"
#DO NOT use tcp:myServerName.database.windows.net,1433 but only myServerName
$ServerName = "myServerName"
$Date = Get-Date -format "yyyy-MM-dd-HH-mm"
$DatabaseName = "myTargetDatabaseName"
$BlobName = $Date + "-" + $DatabaseName.bacpac"
$StorageName = "myStorageAccountName"
$ContainerName = "myContainerNameToStoreBacpacFiles"
$StorageKey = "myStorageAccountKey"
Write-Host "Getting database user credential"
#DO NOT use myDatabaseUsername#myServerName but only myDatabaseUsername
$credential = Get-MyCredential ($FileRootPath + "DbSyncred.xml")
Write-Host "Connecting to Azure database"
$SqlCtx = New-AzureSqlDatabaseServerContext -ServerName $ServerName -Credential $credential
Write-Host "Connecting to Blob storage"
$StorageCtx = New-AzureStorageContext -StorageAccountName $StorageName -StorageAccountKey $StorageKey
$Container = Get-AzureStorageContainer -Name $ContainerName -Context $StorageCtx
Write-Host "Exporting data to blob"
$exportRequest = Start-AzureSqlDatabaseExport -SqlConnectionContext $SqlCtx -StorageContainer $Container -DatabaseName $DatabaseName -BlobName $BlobName
Get-AzureSqlDatabaseImportExportStatus -Request $exportRequest
# use the below script in powershell to execute the script
# powershell -ExecutionPolicy ByPass –File C:\PowerShellScripts\AzureServerName\mySavedScript.ps1 –noexit