Azure Logic Apps: how to run Powershell script or Azure CLI? - azure

I'm building my Azure Logic Apps worklow which is supposed to check some conditions and run following Powershell:
Stop-AzureWebsiteJob -Name MyWebsite -JobName MyWebJob
Start-AzureWebsiteJob -Name MyWebsite -JobName MyWebJob -JobType Continuous
The question is: what's the easiest way to invoke such script in Azure Logic Apps? It seems like there's no built in block/connector for Powershell so I'd like to know what are the possibilites. Or perhaps it might be easier to run az CLI command with similar operation

Finally I ended up with a solution which takes advantage of Azure Automation. From Azure Portal we can create new Resource typing in Automation:
Once the resource is created we can add new Runbook under runbooks tab:
Runbook can run Powershell Workflow and get authorized using AzureRunAsConnection option (details here). My sample Powershell which is supposed to restart WebJob an specific App Service looks like below:
Workflow RestartMyWebJob
{
$Conn = Get-AutomationConnection -Name AzureRunAsConnection
Add-AzureRMAccount -ServicePrincipal -Tenant $Conn.TenantID -ApplicationId $Conn.ApplicationID -CertificateThumbprint $Conn.CertificateThumbprint
$AzureContext = Select-AzureRmSubscription -SubscriptionId $Conn.SubscriptionID
$Apiversion = "2015-08-01"
$ResourceGroupName = 'My-Resource-Group-Name'
$ResourceName = 'My-Resource-Group-Name/My-AppService--WebJob-Name'
Invoke-AzureRmResourceAction -ResourceGroupName $ResourceGroupName -ResourceType Microsoft.Web/sites/ContinuousWebJobs -ResourceName $ResourceName -Action stop -ApiVersion $Apiversion -Force
Invoke-AzureRmResourceAction -ResourceGroupName $ResourceGroupName -ResourceType Microsoft.Web/sites/ContinuousWebJobs -ResourceName $ResourceName -Action start -ApiVersion $Apiversion -Force
}
Having this Workflow setup we can run it from Azure Logic Apps by adding new block to our logic.

Currently, azure logic seems not support to run powershell and cli script, here is a voice in azure feedback, you could vote it.
Workaround:
If you want to start and stop the webjob, you can call the Kudu WebJobs API in the logic app.
You can follow the steps below.
1.Run the powershell command locally to generate the Authorization token of your web app.
$creds = Invoke-AzureRmResourceAction -ResourceGroupName joywebapp -ResourceType Microsoft.Web/sites/config -ResourceName joywebapp2/publishingcredentials -Action list -ApiVersion 2015-08-01 -Force
$username = $creds.Properties.PublishingUserName
$password = $creds.Properties.PublishingPassword
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username, $password)))
The $base64AuthInfo is what we need, it should be like JGpveXdlYmFwcDI6NnJxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxzRktSdXlUcU5acUUzdFhNb05j.
The token will never be changed except you reset the publish profile, so you just need to do this step once.
2.In the logic app, specific the Method, URI, Headers(The header should be like
Authorization: Basic JGpveXdlYmFwcDI6NnJxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxzRktSdXlUcU5acUUzdFhNb05j, note use space to separate the Basic and token), for example , I start a triggered webjob in my web app.
Triggered result:
So you just need to follow the steps above, for your issue, refer to the APIS:
Start a continuous job
Stop a continuous job

Create an Azure Function with an http trigger with Powershell as the function language (or any other supported language). Then you call the Function easily in the Logic app by calling an Http endpoint.

actually nowdays Azure provide this option, without creating runbooks and automation accounts. It is still in preview mode, but seems to be working !

You can also have your PowerShell code run in an Azure Container Instance supporting PowerShell and create an new Container Group from the Logic App workflow.

Related

How do I change a Platform Setting in an Azure Function App using a Powershell runbook

Specifically, I am looking to write an automation runbook for changing a Function App's HTTP Version from it's 1.1 default to 2.0. I know there is a simple way to do this via CLI commands, but I'm trying to get a working solution using a powershell runbook.
So far, I've been able to find the setting by doing...
$FA = Get-AzFunctionApp -Name <foo> -ResourceGroupName <bar>
$FA.Config.Http20Enabled
False
I've attempted to alter $FA and then pipe it through Update-AzFunctionApp...
$FA.Config.Http20Enabled = $True
$FA | Update-AzFunctionApp
with no success.
Not sure if I'm close to the right solution but I can't seem to find any Azure functionality that changes platform settings in this way. Any insight would be much appreciated!
I was able to find a solution to my original question. Instead of using the AzFunctionApp cmdlets, I used AzResource.
$FA = Get-AzResource -ResourceGroupName <foo> -Name <bar> -ResourceType Microsoft.Web/sites/config -ApiVersion 2021-02-01
$FA.Properties.http20Enabled = $True
Set-AzResource -ResourceId $FA.ResourceId -Properties $FA.Properties
I presume other config settings can be changed along with the property I needed.
I found (as well as the Azure CLI) you can use the PowerShell cmdlets for Web Apps. These work on Azure Functions too!
For simple examples, perhaps to just toggle a feature you can call Set-AzWebApp in one line. Here are two examples:
(1) to enable HTTPS only:
Set-AzWebApp -Name $functionName -ResourceGroupName $rg -HttpsOnly $true
Or (2) to disable FTP/FTPs:
Set-AzWebApp -Name $functionName -ResourceGroupName $rg -FtpsState "Disabled"
For more complex property changes, like enabling HTTP 2.0. You can do this in just a few more lines of PowerShell. See for example:
$funcAsApp = Get-AzWebApp -Name $functionName -ResourceGroupName $rg
$funcAsApp.SiteConfig.Http20Enabled = $true
$funcAsApp | Set-AzWebApp
For more information see the MSDN help here: https://learn.microsoft.com/en-us/powershell/module/az.websites/set-azwebapp?view=azps-6.6.0

Azure storage account key updation using RM module

I am trying to setup a powershell code which would update the storage account credentials every once in a while and below is the script that I have come across and it works perfectly fine.
function setupContext(){
Add-AzureRmAccount
Save-AzureRmContext -Path “path\to\json\file”
}
#setupContext
Import-AzureRmContext -Path “path\to\json\file”
$subscriptionId='***********************************'
Select-AzureRMSubscription -SubscriptionId $subscriptionId -WarningAction SilentlyContinue
$resourceGroup="**************"
$storageAccountName="******************"
$BLOBKey= New-AzureRmStorageAccountKey -ResourceGroupName $resourceGroup -Name $storageAccountName -KeyName key2
Write-Host "BLOB Key:"$BLOBKey.Keys[0]
The above code does the required work, however it requires us to login to the azure-rm account which basically defeats the idea of automating this process since I would need keep updating this generated profile.
Note: I am not allowed to use az module as of now since the environment in which I work has some .NET version limitations.
So if there any other solution which could overcome the azure rm login issue, please suggest.
Use Azure Automation. This automatically sets up something called RunAs account. Which simply said is just Azure AD Service Principal.
Then assign this principal privileges on the storage account just like any other user and you are done.
And in the Automation Runbook do
$connection = Get-AutomationConnection -Name AzureRunAsConnection
Connect-AzureRmAccount `
-ServicePrincipal `
-Tenant $connection.TenantID `
-ApplicationID $connection.ApplicationID `
-CertificateThumbprint $connection.CertificateThumbprint
$AzureContext = Select-AzureRmSubscription -SubscriptionId $connection.SubscriptionID
... run rest of the code ...
If you want to run this from outside of Azure like on-prem server then set up manually service principal. Here is guide
https://learn.microsoft.com/en-us/azure/active-directory/develop/howto-create-service-principal-portal
And just log into this app from powershell instead of the user.
Looks you want to use a non-interactive way to do that automatically. To access the azure resource with a non-interactive way, your best option currently is to use the service principal(AD App).
An Azure service principal is an identity created for use with applications, hosted services, and automated tools to access Azure resources.
The other reply is for azure automation runbook, you could follow my steps to automate it in other places else.
1.Create an Azure Active Directory application and create a secret for the app, save the secret and get values for signing in.
2.Navigate to the storage account(or the subscription which the storage account located) in the portal -> Access control (IAM) -> Add -> Add role assignment -> search your service principal(AD App) with name and add it as a role(e.g. Owner/Contributor) -> Save.
Note: To give the role, you need to use an account which is an Owner of the specific scope(storage account/subscription).
3.Then use the script as below, replace the specific properties with the values in step 1.
function setupContext(){
$azureAplicationId ="<application id>"
$azureTenantId= "<tenant id>"
$azurePassword = ConvertTo-SecureString "<client secret>" -AsPlainText -Force
$psCred = New-Object System.Management.Automation.PSCredential($azureAplicationId , $azurePassword)
Add-AzureRmAccount -Credential $psCred -TenantId $azureTenantId -ServicePrincipal
Save-AzureRmContext -Path “path\to\json\file”
}
#setupContext
Import-AzureRmContext -Path “path\to\json\file”
$subscriptionId='***********************************'
Select-AzureRMSubscription -SubscriptionId $subscriptionId -WarningAction SilentlyContinue
$resourceGroup="**************"
$storageAccountName="******************"
$BLOBKey= New-AzureRmStorageAccountKey -ResourceGroupName $resourceGroup -Name $storageAccountName -KeyName key2
Write-Host "BLOB Key:"$BLOBKey.Keys[0]
Besides, if you want to learn more about the service principal, you could take a look at this link - Application and service principal objects in Azure Active Directory

How to update smart detection settings alerts through powershell scripts

Want to update Smart detection setting alerts provided under Azure application insights using powershell cmdlets.
I want to update Smart detection setting alerts provided under Azure application insights using powershell cmdlets, following is a scenario which i want to accomplish.
Scenario: I want to update Failure Anomalies alert and register my emailid under additional email recipients and want to disable the default mail to subscription owner configuration.
Is there any way above mentioned scenario can be accomplished using powershell cmdlets?
Update:
Here is a solution and assume your have azure powershell az module installed(it's ok if you're using powershell azureRM module, but you need to just change the cmdlet respectively):
#the -Name parameter is the Failure Anomalies alert name you see in azure portal, like "Failure Anomalies - your_app_insights_name"
$alets_all = Get-AzAlertRule -ResourceGroupName "xxx" -Name "xxx"
$a = $alets_all[0]
$AppIns = "xxx" #the application insights name
$ResourceGroup = "xxxx"
$SubscriptionId ="xxxx"
$Location =$a.Location
$MetricName =$a.Condition.DataSource.MetricName
$action=New-AzAlertRuleEmail -CustomEmail "abc#gmail.com; xyz#microsoft.com"
$action.SendToServiceOwners=$false
Add-AzMetricAlertRule -Name "Failure Anomalies - $AppIns" -ResourceGroupName $ResourceGroup -TargetResourceId "/subscriptions/$SubscriptionId/resourceGroups/$ResourceGroup/providers/microsoft.insights/components/$AppIns" -Operator GreaterThan -Threshold 0 -WindowSize 01:00:00 -Location $Location -TimeAggregationOperator Total -Action $action -MetricName $MetricName
it works well at my side, and test result as below:

Azure automation with cosmosDB

Trying to perform some updates to CosmosDB with the Azure automation run books. I have made a RunAs service principal Account to authenticate with Azure
Updating the Modules used for the Get-AzureRmResource appear to cause some issues where I can no longer retrieve the CosmosDB object.
$Conn = Get-AutomationConnection -Name "AzureRunAsConnection"
Add-AzureRmAccount -ServicePrincipal -Tenant $Conn.TenantID `
-ApplicationID $Conn.ApplicationID -CertificateThumbprint
$Conn.CertificateThumbprint
Select-AzureRmSubscription -SubscriptionName "Visual Studio Enterprise" -ErrorAction SilentlyContinue
#resource and app variables declared here.
$cosmosDbResource = (Get-AzureRmResource -ResourceType
"Microsoft.DocumentDb/DatabaseAccounts" -ResourceGroup $applicationGroup -
ApiVersion "2015-04-08" -Name $cosmosDBName)
"Before CosmosDB Resource"
$cosmosDbResource | FT
"Cosmos DB Properties"
$cosmosDbResource.Properties
This code works just fine on the plain deployment of automation accounts with the module. AzureRM.Resources at 1.0.3.
If I try and update the AzureRM.Resource and its dependencies to 6.1.0 I can no longer retrieve my CosmosDB instance.
I think that there may be a conflict with the powershell modules with the update
Depending on what you wish to update within cosmosdb.....
The official cosmosdb powershell modules are pretty laking at the moment, take a look at the community cosmosdb powershell module it is far more feature rich and easier to work with:
https://github.com/PlagueHO/CosmosDB

Azure: Powershell: Set-AzureRmWebApp: How to set the "alwaysOn" property

I am running Powershell 5 and trying to manipulate my Azure WebApp object using Set-AzureRmWebApp (and NOT Set-AzureResource) to set the "Always On" property of the web app.
My basic code snippet starts with a running web app named "myWebApp", and looks like this:
$name = "myWebApp"
$resourceGroupName = "myResourceGroup"
$app_settings = #{"WEBSITE_LOAD_CERTIFICATES"="*";"CommonDatabase"="Common";"WEBSITE_NODE_DEFAULT_VERSION"="0.10.32"}
$result1 = Set-AzureRmWebApp -ResourceGroupName $resourceGroupName -AppSettings $app_settings -Name $name
$result2 = Set-AzureRmResource -ResourceGroupName $resourceGroupName -ResourceType Microsoft.Web/sites/config -ResourceName $this.name -PropertyObject $propertiesObject -ApiVersion 2015-08-01 -Force
The first Set-AzureRmWebApp statement works. It sets all the variables in $app_settings, and they become visible in the Azure Portal blade for myWebApp.
I tried using "Always On"= on as a property in $app_settings with Set-AzureRmWebApp, and it appeared in the App Settings sub-list in the properties of "myWebApp" on the Azure portal blade, but the actual property "Always On" in the general settings remained off.
I read on another site that using Set-AzureRmResource would work, so I tried it, but it failed.
What do I need to do in Powershell to set a property in the General Settings of my Azure WebApp, specifically "Always On"?
"Always On" is not supported if WebApp is in a free Service Plan tier. If the WebApp is in a free tier, please scale up the App Service Plan. Please refer to the document for more info about how to scale up the App Service Plan.Please have a try to use the solution that sharbag mentioned. It is worked for me and I also check the run result from the azure portal. Snipped code from the solution is as followings:
$ResourceGroupName = 'Your Group Name'
$WebAppName = 'Your WebApp Name'
$WebAppPropertiesObject = #{"siteConfig" = #{"AlwaysOn" = $true}}
$WebAppResourceType = 'microsoft.web/sites'
$webAppResource = Get-AzureRmResource -ResourceType $WebAppResourceType -ResourceGroupName $ResourceGroupName -ResourceName $WebAppName
$webAppResource | Set-AzureRmResource -PropertyObject $WebAppPropertiesObject -Force
If the WebApp in a free tier service plan, when we try to run the PowerShell command to enable "Always On" then we will get the following error message.

Resources